@haneullabs/deepbook-v3 0.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (612) hide show
  1. package/CHANGELOG.md +342 -81
  2. package/dist/client.d.mts +238 -0
  3. package/dist/client.d.mts.map +1 -0
  4. package/dist/client.mjs +397 -0
  5. package/dist/client.mjs.map +1 -0
  6. package/dist/contracts/deepbook/account.d.mts +37 -0
  7. package/dist/contracts/deepbook/account.d.mts.map +1 -0
  8. package/dist/contracts/deepbook/account.mjs +31 -0
  9. package/dist/contracts/deepbook/account.mjs.map +1 -0
  10. package/dist/contracts/deepbook/balances.d.mts +12 -0
  11. package/dist/contracts/deepbook/balances.d.mts.map +1 -0
  12. package/dist/contracts/deepbook/balances.mjs +24 -0
  13. package/dist/contracts/deepbook/balances.mjs.map +1 -0
  14. package/dist/contracts/deepbook/deep_price.d.mts +12 -0
  15. package/dist/contracts/deepbook/deep_price.d.mts.map +1 -0
  16. package/dist/contracts/deepbook/deep_price.mjs +49 -0
  17. package/dist/contracts/deepbook/deep_price.mjs.map +1 -0
  18. package/dist/contracts/deepbook/deps/haneul/vec_set.d.mts +21 -0
  19. package/dist/contracts/deepbook/deps/haneul/vec_set.d.mts.map +1 -0
  20. package/dist/contracts/deepbook/deps/haneul/vec_set.mjs +26 -0
  21. package/dist/contracts/deepbook/deps/haneul/vec_set.mjs.map +1 -0
  22. package/dist/contracts/deepbook/order.d.mts +23 -0
  23. package/dist/contracts/deepbook/order.d.mts.map +1 -0
  24. package/dist/contracts/deepbook/order.mjs +63 -0
  25. package/dist/contracts/deepbook/order.mjs.map +1 -0
  26. package/dist/contracts/pyth/data_source.mjs +20 -0
  27. package/dist/contracts/pyth/data_source.mjs.map +1 -0
  28. package/dist/contracts/pyth/deps/0x0000000000000000000000000000000000000000000000000000000000000002/package.mjs +21 -0
  29. package/dist/contracts/pyth/deps/0x0000000000000000000000000000000000000000000000000000000000000002/package.mjs.map +1 -0
  30. package/dist/contracts/pyth/deps/0x0000000000000000000000000000000000000000000000000000000000000002/table.mjs +19 -0
  31. package/dist/contracts/pyth/deps/0x0000000000000000000000000000000000000000000000000000000000000002/table.mjs.map +1 -0
  32. package/dist/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/bytes32.mjs +16 -0
  33. package/dist/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/bytes32.mjs.map +1 -0
  34. package/dist/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/consumed_vaas.mjs +16 -0
  35. package/dist/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/consumed_vaas.mjs.map +1 -0
  36. package/dist/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/external_address.mjs +16 -0
  37. package/dist/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/external_address.mjs.map +1 -0
  38. package/dist/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/set.mjs +16 -0
  39. package/dist/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/set.mjs.map +1 -0
  40. package/dist/contracts/pyth/i64.mjs +19 -0
  41. package/dist/contracts/pyth/i64.mjs.map +1 -0
  42. package/dist/contracts/pyth/price.mjs +22 -0
  43. package/dist/contracts/pyth/price.mjs.map +1 -0
  44. package/dist/contracts/pyth/price_feed.mjs +21 -0
  45. package/dist/contracts/pyth/price_feed.mjs.map +1 -0
  46. package/dist/contracts/pyth/price_identifier.mjs +16 -0
  47. package/dist/contracts/pyth/price_identifier.mjs.map +1 -0
  48. package/dist/contracts/pyth/price_info.mjs +28 -0
  49. package/dist/contracts/pyth/price_info.mjs.map +1 -0
  50. package/dist/contracts/pyth/state.mjs +36 -0
  51. package/dist/contracts/pyth/state.mjs.map +1 -0
  52. package/dist/contracts/utils/index.d.mts +34 -0
  53. package/dist/contracts/utils/index.d.mts.map +1 -0
  54. package/dist/contracts/utils/index.mjs +35 -0
  55. package/dist/contracts/utils/index.mjs.map +1 -0
  56. package/dist/contracts/wormhole/bytes32.mjs +16 -0
  57. package/dist/contracts/wormhole/bytes32.mjs.map +1 -0
  58. package/dist/contracts/wormhole/consumed_vaas.mjs +16 -0
  59. package/dist/contracts/wormhole/consumed_vaas.mjs.map +1 -0
  60. package/dist/contracts/wormhole/deps/0x0000000000000000000000000000000000000000000000000000000000000002/balance.mjs +16 -0
  61. package/dist/contracts/wormhole/deps/0x0000000000000000000000000000000000000000000000000000000000000002/balance.mjs.map +1 -0
  62. package/dist/contracts/wormhole/deps/0x0000000000000000000000000000000000000000000000000000000000000002/package.mjs +21 -0
  63. package/dist/contracts/wormhole/deps/0x0000000000000000000000000000000000000000000000000000000000000002/package.mjs.map +1 -0
  64. package/dist/contracts/wormhole/deps/0x0000000000000000000000000000000000000000000000000000000000000002/table.mjs +19 -0
  65. package/dist/contracts/wormhole/deps/0x0000000000000000000000000000000000000000000000000000000000000002/table.mjs.map +1 -0
  66. package/dist/contracts/wormhole/external_address.mjs +16 -0
  67. package/dist/contracts/wormhole/external_address.mjs.map +1 -0
  68. package/dist/contracts/wormhole/fee_collector.mjs +20 -0
  69. package/dist/contracts/wormhole/fee_collector.mjs.map +1 -0
  70. package/dist/contracts/wormhole/set.mjs +16 -0
  71. package/dist/contracts/wormhole/set.mjs.map +1 -0
  72. package/dist/contracts/wormhole/state.mjs +31 -0
  73. package/dist/contracts/wormhole/state.mjs.map +1 -0
  74. package/dist/index.d.mts +25 -0
  75. package/dist/index.mjs +26 -0
  76. package/dist/pyth/PriceServiceConnection.d.mts +26 -0
  77. package/dist/pyth/PriceServiceConnection.d.mts.map +1 -0
  78. package/dist/pyth/PriceServiceConnection.mjs +35 -0
  79. package/dist/pyth/PriceServiceConnection.mjs.map +1 -0
  80. package/dist/pyth/pyth-helpers.mjs +18 -0
  81. package/dist/pyth/pyth-helpers.mjs.map +1 -0
  82. package/dist/pyth/pyth.d.mts +69 -0
  83. package/dist/pyth/pyth.d.mts.map +1 -0
  84. package/dist/pyth/pyth.mjs +220 -0
  85. package/dist/pyth/pyth.mjs.map +1 -0
  86. package/dist/queries/accountQueries.mjs +104 -0
  87. package/dist/queries/accountQueries.mjs.map +1 -0
  88. package/dist/queries/balanceManagerQueries.mjs +113 -0
  89. package/dist/queries/balanceManagerQueries.mjs.map +1 -0
  90. package/dist/queries/context.mjs +15 -0
  91. package/dist/queries/context.mjs.map +1 -0
  92. package/dist/queries/marginManagerQueries.mjs +365 -0
  93. package/dist/queries/marginManagerQueries.mjs.map +1 -0
  94. package/dist/queries/marginPoolQueries.mjs +184 -0
  95. package/dist/queries/marginPoolQueries.mjs.map +1 -0
  96. package/dist/queries/orderQueries.mjs +165 -0
  97. package/dist/queries/orderQueries.mjs.map +1 -0
  98. package/dist/queries/poolQueries.mjs +234 -0
  99. package/dist/queries/poolQueries.mjs.map +1 -0
  100. package/dist/queries/priceFeedQueries.mjs +83 -0
  101. package/dist/queries/priceFeedQueries.mjs.map +1 -0
  102. package/dist/queries/quantityQueries.mjs +216 -0
  103. package/dist/queries/quantityQueries.mjs.map +1 -0
  104. package/dist/queries/referralQueries.mjs +96 -0
  105. package/dist/queries/referralQueries.mjs.map +1 -0
  106. package/dist/queries/registryQueries.mjs +162 -0
  107. package/dist/queries/registryQueries.mjs.map +1 -0
  108. package/dist/queries/tpslQueries.mjs +62 -0
  109. package/dist/queries/tpslQueries.mjs.map +1 -0
  110. package/dist/transactions/balanceManager.d.mts +174 -0
  111. package/dist/transactions/balanceManager.d.mts.map +1 -0
  112. package/dist/transactions/balanceManager.mjs +234 -0
  113. package/dist/transactions/balanceManager.mjs.map +1 -0
  114. package/dist/transactions/deepbook.d.mts +490 -0
  115. package/dist/transactions/deepbook.d.mts.map +1 -0
  116. package/dist/transactions/deepbook.mjs +979 -0
  117. package/dist/transactions/deepbook.mjs.map +1 -0
  118. package/dist/transactions/deepbookAdmin.d.mts +111 -0
  119. package/dist/transactions/deepbookAdmin.d.mts.map +1 -0
  120. package/dist/transactions/deepbookAdmin.mjs +222 -0
  121. package/dist/transactions/deepbookAdmin.mjs.map +1 -0
  122. package/dist/transactions/flashLoans.d.mts +61 -0
  123. package/dist/transactions/flashLoans.d.mts.map +1 -0
  124. package/dist/transactions/flashLoans.mjs +77 -0
  125. package/dist/transactions/flashLoans.mjs.map +1 -0
  126. package/dist/transactions/governance.d.mts +47 -0
  127. package/dist/transactions/governance.d.mts.map +1 -0
  128. package/dist/transactions/governance.mjs +91 -0
  129. package/dist/transactions/governance.mjs.map +1 -0
  130. package/dist/transactions/marginAdmin.d.mts +138 -0
  131. package/dist/transactions/marginAdmin.d.mts.map +1 -0
  132. package/dist/transactions/marginAdmin.mjs +250 -0
  133. package/dist/transactions/marginAdmin.mjs.map +1 -0
  134. package/dist/transactions/marginLiquidations.d.mts +67 -0
  135. package/dist/transactions/marginLiquidations.d.mts.map +1 -0
  136. package/dist/transactions/marginLiquidations.mjs +110 -0
  137. package/dist/transactions/marginLiquidations.mjs.map +1 -0
  138. package/dist/transactions/marginMaintainer.d.mts +86 -0
  139. package/dist/transactions/marginMaintainer.d.mts.map +1 -0
  140. package/dist/transactions/marginMaintainer.mjs +161 -0
  141. package/dist/transactions/marginMaintainer.mjs.map +1 -0
  142. package/dist/transactions/marginManager.d.mts +247 -0
  143. package/dist/transactions/marginManager.d.mts.map +1 -0
  144. package/dist/transactions/marginManager.mjs +548 -0
  145. package/dist/transactions/marginManager.mjs.map +1 -0
  146. package/dist/transactions/marginPool.d.mts +140 -0
  147. package/dist/transactions/marginPool.d.mts.map +1 -0
  148. package/dist/transactions/marginPool.mjs +207 -0
  149. package/dist/transactions/marginPool.mjs.map +1 -0
  150. package/dist/transactions/marginRegistry.d.mts +100 -0
  151. package/dist/transactions/marginRegistry.d.mts.map +1 -0
  152. package/dist/transactions/marginRegistry.mjs +128 -0
  153. package/dist/transactions/marginRegistry.mjs.map +1 -0
  154. package/dist/transactions/marginTPSL.d.mts +100 -0
  155. package/dist/transactions/marginTPSL.d.mts.map +1 -0
  156. package/dist/transactions/marginTPSL.mjs +173 -0
  157. package/dist/transactions/marginTPSL.mjs.map +1 -0
  158. package/dist/transactions/poolProxy.d.mts +123 -0
  159. package/dist/transactions/poolProxy.d.mts.map +1 -0
  160. package/dist/transactions/poolProxy.mjs +336 -0
  161. package/dist/transactions/poolProxy.mjs.map +1 -0
  162. package/dist/types/bcs.d.mts +5 -0
  163. package/dist/types/bcs.mjs +7 -0
  164. package/dist/types/index.d.mts +374 -0
  165. package/dist/types/index.d.mts.map +1 -0
  166. package/dist/types/index.mjs +18 -0
  167. package/dist/types/index.mjs.map +1 -0
  168. package/dist/utils/config.d.mts +90 -0
  169. package/dist/utils/config.d.mts.map +1 -0
  170. package/dist/utils/config.mjs +104 -0
  171. package/dist/utils/config.mjs.map +1 -0
  172. package/dist/utils/constants.d.mts +93 -0
  173. package/dist/utils/constants.d.mts.map +1 -0
  174. package/dist/utils/constants.mjs +408 -0
  175. package/dist/utils/constants.mjs.map +1 -0
  176. package/dist/utils/conversion.mjs +26 -0
  177. package/dist/utils/conversion.mjs.map +1 -0
  178. package/dist/utils/errors.d.mts +46 -0
  179. package/dist/utils/errors.d.mts.map +1 -0
  180. package/dist/utils/errors.mjs +59 -0
  181. package/dist/utils/errors.mjs.map +1 -0
  182. package/dist/{cjs/utils/validation.d.ts → utils/validation.d.mts} +11 -7
  183. package/dist/utils/validation.d.mts.map +1 -0
  184. package/dist/utils/validation.mjs +76 -0
  185. package/dist/utils/validation.mjs.map +1 -0
  186. package/package.json +30 -26
  187. package/src/client.ts +467 -2255
  188. package/src/contracts/deepbook/account.ts +15 -15
  189. package/src/contracts/deepbook/balance_manager.ts +343 -57
  190. package/src/contracts/deepbook/balances.ts +3 -2
  191. package/src/contracts/deepbook/big_vector.ts +6 -7
  192. package/src/contracts/deepbook/book.ts +3 -2
  193. package/src/contracts/deepbook/constants.ts +95 -3
  194. package/src/contracts/deepbook/deep_price.ts +7 -7
  195. package/src/contracts/deepbook/deps/{sui → haneul}/bag.ts +8 -8
  196. package/src/contracts/deepbook/deps/{sui → haneul}/balance.ts +4 -3
  197. package/src/contracts/deepbook/deps/{sui → haneul}/table.ts +6 -6
  198. package/src/contracts/deepbook/deps/{sui → haneul}/vec_map.ts +4 -4
  199. package/src/contracts/deepbook/deps/{sui → haneul}/vec_set.ts +4 -4
  200. package/src/contracts/deepbook/deps/{sui → haneul}/versioned.ts +4 -4
  201. package/src/contracts/deepbook/deps/std/type_name.ts +3 -2
  202. package/src/contracts/deepbook/ewma.ts +14 -3
  203. package/src/contracts/deepbook/fill.ts +21 -21
  204. package/src/contracts/deepbook/governance.ts +4 -3
  205. package/src/contracts/deepbook/history.ts +4 -3
  206. package/src/contracts/deepbook/math.ts +15 -15
  207. package/src/contracts/deepbook/order.ts +16 -16
  208. package/src/contracts/deepbook/order_info.ts +39 -27
  209. package/src/contracts/deepbook/order_query.ts +12 -12
  210. package/src/contracts/deepbook/pool.ts +883 -526
  211. package/src/contracts/deepbook/registry.ts +149 -38
  212. package/src/contracts/deepbook/state.ts +14 -3
  213. package/src/contracts/deepbook/trade_params.ts +3 -2
  214. package/src/contracts/deepbook/vault.ts +5 -4
  215. package/src/contracts/pyth/batch_price_attestation.ts +92 -0
  216. package/src/contracts/pyth/contract_upgrade.ts +54 -0
  217. package/src/contracts/pyth/data_source.ts +64 -0
  218. package/src/contracts/pyth/deps/0x0000000000000000000000000000000000000000000000000000000000000002/package.ts +15 -0
  219. package/src/contracts/pyth/deps/0x0000000000000000000000000000000000000000000000000000000000000002/table.ts +13 -0
  220. package/src/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/bytes32.ts +12 -0
  221. package/src/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/consumed_vaas.ts +13 -0
  222. package/src/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/external_address.ts +13 -0
  223. package/src/contracts/pyth/deps/0xf47329f4344f3bf0f8e436e2f7b485466cff300f12a166563995d3888c296a94/set.ts +12 -0
  224. package/src/contracts/pyth/deserialize.ts +117 -0
  225. package/src/contracts/pyth/event.ts +20 -0
  226. package/src/contracts/pyth/governance.ts +113 -0
  227. package/src/contracts/pyth/governance_action.ts +130 -0
  228. package/src/contracts/pyth/governance_instruction.ts +98 -0
  229. package/src/contracts/pyth/hot_potato_vector.ts +70 -0
  230. package/src/contracts/pyth/i64.ts +94 -0
  231. package/src/contracts/pyth/merkle_tree.ts +41 -0
  232. package/src/contracts/pyth/migrate.ts +29 -0
  233. package/src/contracts/pyth/price.ts +102 -0
  234. package/src/contracts/pyth/price_feed.ts +101 -0
  235. package/src/contracts/pyth/price_identifier.ts +46 -0
  236. package/src/contracts/pyth/price_info.ts +220 -0
  237. package/src/contracts/pyth/price_status.ts +74 -0
  238. package/src/contracts/pyth/pyth.ts +236 -0
  239. package/src/contracts/pyth/set.ts +93 -0
  240. package/src/contracts/pyth/set_data_sources.ts +14 -0
  241. package/src/contracts/pyth/set_fee_recipient.ts +13 -0
  242. package/src/contracts/pyth/set_governance_data_source.ts +16 -0
  243. package/src/contracts/pyth/set_stale_price_threshold.ts +13 -0
  244. package/src/contracts/pyth/set_update_fee.ts +14 -0
  245. package/src/contracts/pyth/setup.ts +12 -0
  246. package/src/contracts/pyth/state.ts +227 -0
  247. package/src/contracts/pyth/version_control.ts +25 -0
  248. package/src/contracts/utils/index.ts +100 -50
  249. package/src/contracts/wormhole/bytes32.ts +12 -0
  250. package/src/contracts/wormhole/consumed_vaas.ts +13 -0
  251. package/src/contracts/wormhole/deps/0x0000000000000000000000000000000000000000000000000000000000000002/balance.ts +12 -0
  252. package/src/contracts/wormhole/deps/0x0000000000000000000000000000000000000000000000000000000000000002/package.ts +15 -0
  253. package/src/contracts/wormhole/deps/0x0000000000000000000000000000000000000000000000000000000000000002/table.ts +13 -0
  254. package/src/contracts/wormhole/external_address.ts +13 -0
  255. package/src/contracts/wormhole/fee_collector.ts +15 -0
  256. package/src/contracts/wormhole/set.ts +12 -0
  257. package/src/contracts/wormhole/state.ts +25 -0
  258. package/src/index.ts +44 -3
  259. package/src/pyth/pyth.ts +51 -50
  260. package/src/queries/accountQueries.ts +117 -0
  261. package/src/queries/balanceManagerQueries.ts +156 -0
  262. package/src/queries/context.ts +44 -0
  263. package/src/queries/index.ts +16 -0
  264. package/src/queries/marginManagerQueries.ts +575 -0
  265. package/src/queries/marginPoolQueries.ts +226 -0
  266. package/src/queries/orderQueries.ts +202 -0
  267. package/src/queries/poolQueries.ts +266 -0
  268. package/src/queries/priceFeedQueries.ts +141 -0
  269. package/src/queries/quantityQueries.ts +266 -0
  270. package/src/queries/referralQueries.ts +112 -0
  271. package/src/queries/registryQueries.ts +185 -0
  272. package/src/queries/tpslQueries.ts +88 -0
  273. package/src/transactions/balanceManager.ts +5 -4
  274. package/src/transactions/deepbook.ts +117 -84
  275. package/src/transactions/deepbookAdmin.ts +10 -9
  276. package/src/transactions/flashLoans.ts +5 -4
  277. package/src/transactions/governance.ts +5 -4
  278. package/src/transactions/marginAdmin.ts +12 -8
  279. package/src/transactions/marginLiquidations.ts +5 -4
  280. package/src/transactions/marginMaintainer.ts +28 -16
  281. package/src/transactions/marginManager.ts +78 -29
  282. package/src/transactions/marginPool.ts +7 -7
  283. package/src/transactions/marginTPSL.ts +16 -11
  284. package/src/transactions/poolProxy.ts +62 -11
  285. package/src/types/bcs.ts +1 -1
  286. package/src/types/index.ts +217 -53
  287. package/src/utils/config.ts +38 -17
  288. package/src/utils/constants.ts +73 -18
  289. package/src/utils/conversion.ts +33 -0
  290. package/src/utils/validation.ts +1 -1
  291. package/dist/cjs/client.d.ts +0 -861
  292. package/dist/cjs/client.js +0 -1982
  293. package/dist/cjs/client.js.map +0 -7
  294. package/dist/cjs/contracts/deepbook/account.d.ts +0 -105
  295. package/dist/cjs/contracts/deepbook/account.js +0 -163
  296. package/dist/cjs/contracts/deepbook/account.js.map +0 -7
  297. package/dist/cjs/contracts/deepbook/balance_manager.d.ts +0 -268
  298. package/dist/cjs/contracts/deepbook/balance_manager.js +0 -361
  299. package/dist/cjs/contracts/deepbook/balance_manager.js.map +0 -7
  300. package/dist/cjs/contracts/deepbook/balances.d.ts +0 -10
  301. package/dist/cjs/contracts/deepbook/balances.js +0 -35
  302. package/dist/cjs/contracts/deepbook/balances.js.map +0 -7
  303. package/dist/cjs/contracts/deepbook/big_vector.d.ts +0 -62
  304. package/dist/cjs/contracts/deepbook/big_vector.js +0 -80
  305. package/dist/cjs/contracts/deepbook/big_vector.js.map +0 -7
  306. package/dist/cjs/contracts/deepbook/book.d.ts +0 -34
  307. package/dist/cjs/contracts/deepbook/book.js +0 -50
  308. package/dist/cjs/contracts/deepbook/book.js.map +0 -7
  309. package/dist/cjs/contracts/deepbook/constants.d.ts +0 -176
  310. package/dist/cjs/contracts/deepbook/constants.js +0 -338
  311. package/dist/cjs/contracts/deepbook/constants.js.map +0 -7
  312. package/dist/cjs/contracts/deepbook/deep_price.d.ts +0 -60
  313. package/dist/cjs/contracts/deepbook/deep_price.js +0 -87
  314. package/dist/cjs/contracts/deepbook/deep_price.js.map +0 -7
  315. package/dist/cjs/contracts/deepbook/deps/std/type_name.d.ts +0 -14
  316. package/dist/cjs/contracts/deepbook/deps/std/type_name.js +0 -42
  317. package/dist/cjs/contracts/deepbook/deps/std/type_name.js.map +0 -7
  318. package/dist/cjs/contracts/deepbook/deps/sui/bag.d.ts +0 -33
  319. package/dist/cjs/contracts/deepbook/deps/sui/bag.js +0 -47
  320. package/dist/cjs/contracts/deepbook/deps/sui/bag.js.map +0 -7
  321. package/dist/cjs/contracts/deepbook/deps/sui/balance.d.ts +0 -9
  322. package/dist/cjs/contracts/deepbook/deps/sui/balance.js +0 -33
  323. package/dist/cjs/contracts/deepbook/deps/sui/balance.js.map +0 -7
  324. package/dist/cjs/contracts/deepbook/deps/sui/object.d.ts +0 -5
  325. package/dist/cjs/contracts/deepbook/deps/sui/object.js +0 -33
  326. package/dist/cjs/contracts/deepbook/deps/sui/object.js.map +0 -7
  327. package/dist/cjs/contracts/deepbook/deps/sui/table.d.ts +0 -28
  328. package/dist/cjs/contracts/deepbook/deps/sui/table.js +0 -47
  329. package/dist/cjs/contracts/deepbook/deps/sui/table.js.map +0 -7
  330. package/dist/cjs/contracts/deepbook/deps/sui/vec_map.d.ts +0 -27
  331. package/dist/cjs/contracts/deepbook/deps/sui/vec_map.js +0 -45
  332. package/dist/cjs/contracts/deepbook/deps/sui/vec_map.js.map +0 -7
  333. package/dist/cjs/contracts/deepbook/deps/sui/vec_set.d.ts +0 -15
  334. package/dist/cjs/contracts/deepbook/deps/sui/vec_set.js +0 -35
  335. package/dist/cjs/contracts/deepbook/deps/sui/vec_set.js.map +0 -7
  336. package/dist/cjs/contracts/deepbook/deps/sui/versioned.d.ts +0 -7
  337. package/dist/cjs/contracts/deepbook/deps/sui/versioned.js +0 -45
  338. package/dist/cjs/contracts/deepbook/deps/sui/versioned.js.map +0 -7
  339. package/dist/cjs/contracts/deepbook/ewma.d.ts +0 -17
  340. package/dist/cjs/contracts/deepbook/ewma.js +0 -39
  341. package/dist/cjs/contracts/deepbook/ewma.js.map +0 -7
  342. package/dist/cjs/contracts/deepbook/fill.d.ts +0 -153
  343. package/dist/cjs/contracts/deepbook/fill.js +0 -251
  344. package/dist/cjs/contracts/deepbook/fill.js.map +0 -7
  345. package/dist/cjs/contracts/deepbook/governance.d.ts +0 -63
  346. package/dist/cjs/contracts/deepbook/governance.js +0 -79
  347. package/dist/cjs/contracts/deepbook/governance.js.map +0 -7
  348. package/dist/cjs/contracts/deepbook/history.d.ts +0 -60
  349. package/dist/cjs/contracts/deepbook/history.js +0 -78
  350. package/dist/cjs/contracts/deepbook/history.js.map +0 -7
  351. package/dist/cjs/contracts/deepbook/math.d.ts +0 -94
  352. package/dist/cjs/contracts/deepbook/math.js +0 -132
  353. package/dist/cjs/contracts/deepbook/math.js.map +0 -7
  354. package/dist/cjs/contracts/deepbook/order.d.ts +0 -135
  355. package/dist/cjs/contracts/deepbook/order.js +0 -218
  356. package/dist/cjs/contracts/deepbook/order.js.map +0 -7
  357. package/dist/cjs/contracts/deepbook/order_info.d.ts +0 -296
  358. package/dist/cjs/contracts/deepbook/order_info.js +0 -386
  359. package/dist/cjs/contracts/deepbook/order_info.js.map +0 -7
  360. package/dist/cjs/contracts/deepbook/order_query.d.ts +0 -85
  361. package/dist/cjs/contracts/deepbook/order_query.js +0 -96
  362. package/dist/cjs/contracts/deepbook/order_query.js.map +0 -7
  363. package/dist/cjs/contracts/deepbook/pool.d.ts +0 -1218
  364. package/dist/cjs/contracts/deepbook/pool.js +0 -1236
  365. package/dist/cjs/contracts/deepbook/pool.js.map +0 -7
  366. package/dist/cjs/contracts/deepbook/registry.d.ts +0 -134
  367. package/dist/cjs/contracts/deepbook/registry.js +0 -182
  368. package/dist/cjs/contracts/deepbook/registry.js.map +0 -7
  369. package/dist/cjs/contracts/deepbook/state.d.ts +0 -117
  370. package/dist/cjs/contracts/deepbook/state.js +0 -104
  371. package/dist/cjs/contracts/deepbook/state.js.map +0 -7
  372. package/dist/cjs/contracts/deepbook/trade_params.d.ts +0 -7
  373. package/dist/cjs/contracts/deepbook/trade_params.js +0 -35
  374. package/dist/cjs/contracts/deepbook/trade_params.js.map +0 -7
  375. package/dist/cjs/contracts/deepbook/vault.d.ts +0 -30
  376. package/dist/cjs/contracts/deepbook/vault.js +0 -65
  377. package/dist/cjs/contracts/deepbook/vault.js.map +0 -7
  378. package/dist/cjs/contracts/utils/index.d.ts +0 -25
  379. package/dist/cjs/contracts/utils/index.js +0 -148
  380. package/dist/cjs/contracts/utils/index.js.map +0 -7
  381. package/dist/cjs/index.d.ts +0 -23
  382. package/dist/cjs/index.js +0 -81
  383. package/dist/cjs/index.js.map +0 -7
  384. package/dist/cjs/package.json +0 -4
  385. package/dist/cjs/pyth/PriceServiceConnection.d.ts +0 -26
  386. package/dist/cjs/pyth/PriceServiceConnection.js +0 -68
  387. package/dist/cjs/pyth/PriceServiceConnection.js.map +0 -7
  388. package/dist/cjs/pyth/pyth-helpers.d.ts +0 -7
  389. package/dist/cjs/pyth/pyth-helpers.js +0 -36
  390. package/dist/cjs/pyth/pyth-helpers.js.map +0 -7
  391. package/dist/cjs/pyth/pyth.d.ts +0 -65
  392. package/dist/cjs/pyth/pyth.js +0 -269
  393. package/dist/cjs/pyth/pyth.js.map +0 -7
  394. package/dist/cjs/transactions/balanceManager.d.ts +0 -168
  395. package/dist/cjs/transactions/balanceManager.js +0 -384
  396. package/dist/cjs/transactions/balanceManager.js.map +0 -7
  397. package/dist/cjs/transactions/deepbook.d.ts +0 -477
  398. package/dist/cjs/transactions/deepbook.js +0 -1335
  399. package/dist/cjs/transactions/deepbook.js.map +0 -7
  400. package/dist/cjs/transactions/deepbookAdmin.d.ts +0 -105
  401. package/dist/cjs/transactions/deepbookAdmin.js +0 -334
  402. package/dist/cjs/transactions/deepbookAdmin.js.map +0 -7
  403. package/dist/cjs/transactions/flashLoans.d.ts +0 -56
  404. package/dist/cjs/transactions/flashLoans.js +0 -124
  405. package/dist/cjs/transactions/flashLoans.js.map +0 -7
  406. package/dist/cjs/transactions/governance.d.ts +0 -42
  407. package/dist/cjs/transactions/governance.js +0 -135
  408. package/dist/cjs/transactions/governance.js.map +0 -7
  409. package/dist/cjs/transactions/marginAdmin.d.ts +0 -133
  410. package/dist/cjs/transactions/marginAdmin.js +0 -393
  411. package/dist/cjs/transactions/marginAdmin.js.map +0 -7
  412. package/dist/cjs/transactions/marginLiquidations.d.ts +0 -61
  413. package/dist/cjs/transactions/marginLiquidations.js +0 -173
  414. package/dist/cjs/transactions/marginLiquidations.js.map +0 -7
  415. package/dist/cjs/transactions/marginMaintainer.d.ts +0 -80
  416. package/dist/cjs/transactions/marginMaintainer.js +0 -251
  417. package/dist/cjs/transactions/marginMaintainer.js.map +0 -7
  418. package/dist/cjs/transactions/marginManager.d.ts +0 -236
  419. package/dist/cjs/transactions/marginManager.js +0 -688
  420. package/dist/cjs/transactions/marginManager.js.map +0 -7
  421. package/dist/cjs/transactions/marginPool.d.ts +0 -134
  422. package/dist/cjs/transactions/marginPool.js +0 -330
  423. package/dist/cjs/transactions/marginPool.js.map +0 -7
  424. package/dist/cjs/transactions/marginRegistry.d.ts +0 -94
  425. package/dist/cjs/transactions/marginRegistry.js +0 -221
  426. package/dist/cjs/transactions/marginRegistry.js.map +0 -7
  427. package/dist/cjs/transactions/marginTPSL.d.ts +0 -93
  428. package/dist/cjs/transactions/marginTPSL.js +0 -286
  429. package/dist/cjs/transactions/marginTPSL.js.map +0 -7
  430. package/dist/cjs/transactions/poolProxy.d.ts +0 -104
  431. package/dist/cjs/transactions/poolProxy.js +0 -435
  432. package/dist/cjs/transactions/poolProxy.js.map +0 -7
  433. package/dist/cjs/types/bcs.d.ts +0 -5
  434. package/dist/cjs/types/bcs.js +0 -33
  435. package/dist/cjs/types/bcs.js.map +0 -7
  436. package/dist/cjs/types/index.d.ts +0 -218
  437. package/dist/cjs/types/index.js +0 -38
  438. package/dist/cjs/types/index.js.map +0 -7
  439. package/dist/cjs/utils/config.d.ts +0 -65
  440. package/dist/cjs/utils/config.js +0 -144
  441. package/dist/cjs/utils/config.js.map +0 -7
  442. package/dist/cjs/utils/constants.d.ts +0 -76
  443. package/dist/cjs/utils/constants.js +0 -382
  444. package/dist/cjs/utils/constants.js.map +0 -7
  445. package/dist/cjs/utils/errors.d.ts +0 -42
  446. package/dist/cjs/utils/errors.js +0 -70
  447. package/dist/cjs/utils/errors.js.map +0 -7
  448. package/dist/cjs/utils/validation.js +0 -67
  449. package/dist/cjs/utils/validation.js.map +0 -7
  450. package/dist/esm/client.d.ts +0 -861
  451. package/dist/esm/client.js +0 -1967
  452. package/dist/esm/client.js.map +0 -7
  453. package/dist/esm/contracts/deepbook/account.d.ts +0 -105
  454. package/dist/esm/contracts/deepbook/account.js +0 -133
  455. package/dist/esm/contracts/deepbook/account.js.map +0 -7
  456. package/dist/esm/contracts/deepbook/balance_manager.d.ts +0 -268
  457. package/dist/esm/contracts/deepbook/balance_manager.js +0 -331
  458. package/dist/esm/contracts/deepbook/balance_manager.js.map +0 -7
  459. package/dist/esm/contracts/deepbook/balances.d.ts +0 -10
  460. package/dist/esm/contracts/deepbook/balances.js +0 -15
  461. package/dist/esm/contracts/deepbook/balances.js.map +0 -7
  462. package/dist/esm/contracts/deepbook/big_vector.d.ts +0 -62
  463. package/dist/esm/contracts/deepbook/big_vector.js +0 -50
  464. package/dist/esm/contracts/deepbook/big_vector.js.map +0 -7
  465. package/dist/esm/contracts/deepbook/book.d.ts +0 -34
  466. package/dist/esm/contracts/deepbook/book.js +0 -20
  467. package/dist/esm/contracts/deepbook/book.js.map +0 -7
  468. package/dist/esm/contracts/deepbook/constants.d.ts +0 -176
  469. package/dist/esm/contracts/deepbook/constants.js +0 -318
  470. package/dist/esm/contracts/deepbook/constants.js.map +0 -7
  471. package/dist/esm/contracts/deepbook/deep_price.d.ts +0 -60
  472. package/dist/esm/contracts/deepbook/deep_price.js +0 -67
  473. package/dist/esm/contracts/deepbook/deep_price.js.map +0 -7
  474. package/dist/esm/contracts/deepbook/deps/std/type_name.d.ts +0 -14
  475. package/dist/esm/contracts/deepbook/deps/std/type_name.js +0 -22
  476. package/dist/esm/contracts/deepbook/deps/std/type_name.js.map +0 -7
  477. package/dist/esm/contracts/deepbook/deps/sui/bag.d.ts +0 -33
  478. package/dist/esm/contracts/deepbook/deps/sui/bag.js +0 -17
  479. package/dist/esm/contracts/deepbook/deps/sui/bag.js.map +0 -7
  480. package/dist/esm/contracts/deepbook/deps/sui/balance.d.ts +0 -9
  481. package/dist/esm/contracts/deepbook/deps/sui/balance.js +0 -13
  482. package/dist/esm/contracts/deepbook/deps/sui/balance.js.map +0 -7
  483. package/dist/esm/contracts/deepbook/deps/sui/object.d.ts +0 -5
  484. package/dist/esm/contracts/deepbook/deps/sui/object.js +0 -13
  485. package/dist/esm/contracts/deepbook/deps/sui/object.js.map +0 -7
  486. package/dist/esm/contracts/deepbook/deps/sui/table.d.ts +0 -28
  487. package/dist/esm/contracts/deepbook/deps/sui/table.js +0 -17
  488. package/dist/esm/contracts/deepbook/deps/sui/table.js.map +0 -7
  489. package/dist/esm/contracts/deepbook/deps/sui/vec_map.d.ts +0 -27
  490. package/dist/esm/contracts/deepbook/deps/sui/vec_map.js +0 -25
  491. package/dist/esm/contracts/deepbook/deps/sui/vec_map.js.map +0 -7
  492. package/dist/esm/contracts/deepbook/deps/sui/vec_set.d.ts +0 -15
  493. package/dist/esm/contracts/deepbook/deps/sui/vec_set.js +0 -15
  494. package/dist/esm/contracts/deepbook/deps/sui/vec_set.js.map +0 -7
  495. package/dist/esm/contracts/deepbook/deps/sui/versioned.d.ts +0 -7
  496. package/dist/esm/contracts/deepbook/deps/sui/versioned.js +0 -15
  497. package/dist/esm/contracts/deepbook/deps/sui/versioned.js.map +0 -7
  498. package/dist/esm/contracts/deepbook/ewma.d.ts +0 -17
  499. package/dist/esm/contracts/deepbook/ewma.js +0 -19
  500. package/dist/esm/contracts/deepbook/ewma.js.map +0 -7
  501. package/dist/esm/contracts/deepbook/fill.d.ts +0 -153
  502. package/dist/esm/contracts/deepbook/fill.js +0 -221
  503. package/dist/esm/contracts/deepbook/fill.js.map +0 -7
  504. package/dist/esm/contracts/deepbook/governance.d.ts +0 -63
  505. package/dist/esm/contracts/deepbook/governance.js +0 -49
  506. package/dist/esm/contracts/deepbook/governance.js.map +0 -7
  507. package/dist/esm/contracts/deepbook/history.d.ts +0 -60
  508. package/dist/esm/contracts/deepbook/history.js +0 -48
  509. package/dist/esm/contracts/deepbook/history.js.map +0 -7
  510. package/dist/esm/contracts/deepbook/math.d.ts +0 -94
  511. package/dist/esm/contracts/deepbook/math.js +0 -112
  512. package/dist/esm/contracts/deepbook/math.js.map +0 -7
  513. package/dist/esm/contracts/deepbook/order.d.ts +0 -135
  514. package/dist/esm/contracts/deepbook/order.js +0 -188
  515. package/dist/esm/contracts/deepbook/order.js.map +0 -7
  516. package/dist/esm/contracts/deepbook/order_info.d.ts +0 -296
  517. package/dist/esm/contracts/deepbook/order_info.js +0 -356
  518. package/dist/esm/contracts/deepbook/order_info.js.map +0 -7
  519. package/dist/esm/contracts/deepbook/order_query.d.ts +0 -85
  520. package/dist/esm/contracts/deepbook/order_query.js +0 -66
  521. package/dist/esm/contracts/deepbook/order_query.js.map +0 -7
  522. package/dist/esm/contracts/deepbook/pool.d.ts +0 -1218
  523. package/dist/esm/contracts/deepbook/pool.js +0 -1206
  524. package/dist/esm/contracts/deepbook/pool.js.map +0 -7
  525. package/dist/esm/contracts/deepbook/registry.d.ts +0 -134
  526. package/dist/esm/contracts/deepbook/registry.js +0 -152
  527. package/dist/esm/contracts/deepbook/registry.js.map +0 -7
  528. package/dist/esm/contracts/deepbook/state.d.ts +0 -117
  529. package/dist/esm/contracts/deepbook/state.js +0 -74
  530. package/dist/esm/contracts/deepbook/state.js.map +0 -7
  531. package/dist/esm/contracts/deepbook/trade_params.d.ts +0 -7
  532. package/dist/esm/contracts/deepbook/trade_params.js +0 -15
  533. package/dist/esm/contracts/deepbook/trade_params.js.map +0 -7
  534. package/dist/esm/contracts/deepbook/vault.d.ts +0 -30
  535. package/dist/esm/contracts/deepbook/vault.js +0 -35
  536. package/dist/esm/contracts/deepbook/vault.js.map +0 -7
  537. package/dist/esm/contracts/utils/index.d.ts +0 -25
  538. package/dist/esm/contracts/utils/index.js +0 -128
  539. package/dist/esm/contracts/utils/index.js.map +0 -7
  540. package/dist/esm/index.d.ts +0 -23
  541. package/dist/esm/index.js +0 -81
  542. package/dist/esm/index.js.map +0 -7
  543. package/dist/esm/package.json +0 -4
  544. package/dist/esm/pyth/PriceServiceConnection.d.ts +0 -26
  545. package/dist/esm/pyth/PriceServiceConnection.js +0 -38
  546. package/dist/esm/pyth/PriceServiceConnection.js.map +0 -7
  547. package/dist/esm/pyth/pyth-helpers.d.ts +0 -7
  548. package/dist/esm/pyth/pyth-helpers.js +0 -16
  549. package/dist/esm/pyth/pyth-helpers.js.map +0 -7
  550. package/dist/esm/pyth/pyth.d.ts +0 -65
  551. package/dist/esm/pyth/pyth.js +0 -249
  552. package/dist/esm/pyth/pyth.js.map +0 -7
  553. package/dist/esm/transactions/balanceManager.d.ts +0 -168
  554. package/dist/esm/transactions/balanceManager.js +0 -364
  555. package/dist/esm/transactions/balanceManager.js.map +0 -7
  556. package/dist/esm/transactions/deepbook.d.ts +0 -477
  557. package/dist/esm/transactions/deepbook.js +0 -1321
  558. package/dist/esm/transactions/deepbook.js.map +0 -7
  559. package/dist/esm/transactions/deepbookAdmin.d.ts +0 -105
  560. package/dist/esm/transactions/deepbookAdmin.js +0 -314
  561. package/dist/esm/transactions/deepbookAdmin.js.map +0 -7
  562. package/dist/esm/transactions/flashLoans.d.ts +0 -56
  563. package/dist/esm/transactions/flashLoans.js +0 -104
  564. package/dist/esm/transactions/flashLoans.js.map +0 -7
  565. package/dist/esm/transactions/governance.d.ts +0 -42
  566. package/dist/esm/transactions/governance.js +0 -115
  567. package/dist/esm/transactions/governance.js.map +0 -7
  568. package/dist/esm/transactions/marginAdmin.d.ts +0 -133
  569. package/dist/esm/transactions/marginAdmin.js +0 -373
  570. package/dist/esm/transactions/marginAdmin.js.map +0 -7
  571. package/dist/esm/transactions/marginLiquidations.d.ts +0 -61
  572. package/dist/esm/transactions/marginLiquidations.js +0 -153
  573. package/dist/esm/transactions/marginLiquidations.js.map +0 -7
  574. package/dist/esm/transactions/marginMaintainer.d.ts +0 -80
  575. package/dist/esm/transactions/marginMaintainer.js +0 -231
  576. package/dist/esm/transactions/marginMaintainer.js.map +0 -7
  577. package/dist/esm/transactions/marginManager.d.ts +0 -236
  578. package/dist/esm/transactions/marginManager.js +0 -668
  579. package/dist/esm/transactions/marginManager.js.map +0 -7
  580. package/dist/esm/transactions/marginPool.d.ts +0 -134
  581. package/dist/esm/transactions/marginPool.js +0 -310
  582. package/dist/esm/transactions/marginPool.js.map +0 -7
  583. package/dist/esm/transactions/marginRegistry.d.ts +0 -94
  584. package/dist/esm/transactions/marginRegistry.js +0 -201
  585. package/dist/esm/transactions/marginRegistry.js.map +0 -7
  586. package/dist/esm/transactions/marginTPSL.d.ts +0 -93
  587. package/dist/esm/transactions/marginTPSL.js +0 -266
  588. package/dist/esm/transactions/marginTPSL.js.map +0 -7
  589. package/dist/esm/transactions/poolProxy.d.ts +0 -104
  590. package/dist/esm/transactions/poolProxy.js +0 -415
  591. package/dist/esm/transactions/poolProxy.js.map +0 -7
  592. package/dist/esm/types/bcs.d.ts +0 -5
  593. package/dist/esm/types/bcs.js +0 -13
  594. package/dist/esm/types/bcs.js.map +0 -7
  595. package/dist/esm/types/index.d.ts +0 -218
  596. package/dist/esm/types/index.js +0 -18
  597. package/dist/esm/types/index.js.map +0 -7
  598. package/dist/esm/utils/config.d.ts +0 -65
  599. package/dist/esm/utils/config.js +0 -135
  600. package/dist/esm/utils/config.js.map +0 -7
  601. package/dist/esm/utils/constants.d.ts +0 -76
  602. package/dist/esm/utils/constants.js +0 -362
  603. package/dist/esm/utils/constants.js.map +0 -7
  604. package/dist/esm/utils/errors.d.ts +0 -42
  605. package/dist/esm/utils/errors.js +0 -50
  606. package/dist/esm/utils/errors.js.map +0 -7
  607. package/dist/esm/utils/validation.d.ts +0 -50
  608. package/dist/esm/utils/validation.js +0 -47
  609. package/dist/esm/utils/validation.js.map +0 -7
  610. package/dist/tsconfig.esm.tsbuildinfo +0 -1
  611. package/dist/tsconfig.tsbuildinfo +0 -1
  612. package/src/contracts/deepbook/deps/sui/object.ts +0 -14
package/src/client.ts CHANGED
@@ -1,48 +1,119 @@
1
1
  // Copyright (c) Mysten Labs, Inc.
2
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
3
 
4
+ import type { ClientWithCoreApi, HaneulClientRegistration, HaneulClientTypes } from '@haneullabs/haneul/client';
5
+ import type { Transaction } from '@haneullabs/haneul/transactions';
6
+
7
+ import type { QueryContext } from './queries/context.js';
8
+ import { AccountQueries } from './queries/accountQueries.js';
9
+ import { BalanceManagerQueries } from './queries/balanceManagerQueries.js';
10
+ import { MarginManagerQueries } from './queries/marginManagerQueries.js';
11
+ import { MarginPoolQueries } from './queries/marginPoolQueries.js';
12
+ import { OrderQueries } from './queries/orderQueries.js';
13
+ import { PoolQueries } from './queries/poolQueries.js';
14
+ import { PriceFeedQueries } from './queries/priceFeedQueries.js';
15
+ import { QuantityQueries } from './queries/quantityQueries.js';
16
+ import { ReferralQueries } from './queries/referralQueries.js';
17
+ import { RegistryQueries } from './queries/registryQueries.js';
18
+ import { TPSLQueries } from './queries/tpslQueries.js';
9
19
  import { BalanceManagerContract } from './transactions/balanceManager.js';
10
20
  import { DeepBookContract } from './transactions/deepbook.js';
11
21
  import { DeepBookAdminContract } from './transactions/deepbookAdmin.js';
12
22
  import { FlashLoanContract } from './transactions/flashLoans.js';
13
23
  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
24
  import { MarginAdminContract } from './transactions/marginAdmin.js';
25
+ import { MarginLiquidationsContract } from './transactions/marginLiquidations.js';
29
26
  import { MarginMaintainerContract } from './transactions/marginMaintainer.js';
30
- import { MarginPoolContract } from './transactions/marginPool.js';
31
27
  import { MarginManagerContract } from './transactions/marginManager.js';
28
+ import { MarginPoolContract } from './transactions/marginPool.js';
32
29
  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
30
  import { MarginTPSLContract } from './transactions/marginTPSL.js';
31
+ import { PoolProxyContract } from './transactions/poolProxy.js';
32
+ import type {
33
+ AccountInfo,
34
+ BalanceManager,
35
+ BaseQuantityIn,
36
+ BaseQuantityOut,
37
+ BorrowedShares,
38
+ CanPlaceLimitOrderParams,
39
+ CanPlaceMarketOrderParams,
40
+ DecodedOrderId,
41
+ Level2Range,
42
+ Level2TicksFromMid,
43
+ LockedBalances,
44
+ ManagerBalance,
45
+ MarginManager,
46
+ MarginManagerAssets,
47
+ MarginManagerBalancesResult,
48
+ MarginManagerDebts,
49
+ MarginManagerState,
50
+ OrderDeepRequiredResult,
51
+ PoolBookParams,
52
+ PoolDeepPrice,
53
+ PoolTradeParams,
54
+ QuantityOut,
55
+ QuoteQuantityIn,
56
+ QuoteQuantityOut,
57
+ ReferralBalances,
58
+ VaultBalances,
59
+ } from './types/index.js';
60
+ import { DeepBookConfig } from './utils/config.js';
61
+ import type { CoinMap, DeepbookPackageIds, PoolMap } from './utils/constants.js';
62
+ import { normalizeHaneulAddress } from '@haneullabs/haneul/utils';
63
+
64
+ export interface DeepBookCompatibleClient extends ClientWithCoreApi {}
65
+
66
+ export interface DeepBookOptions<Name = 'deepbook'> {
67
+ address: string;
68
+ balanceManagers?: { [key: string]: BalanceManager };
69
+ marginManagers?: { [key: string]: MarginManager };
70
+ coins?: CoinMap;
71
+ pools?: PoolMap;
72
+ adminCap?: string;
73
+ marginAdminCap?: string;
74
+ marginMaintainerCap?: string;
75
+ packageIds?: DeepbookPackageIds;
76
+ pyth?: { pythStateId: string; wormholeStateId: string };
77
+ name?: Name;
78
+ }
79
+
80
+ export interface DeepBookClientOptions extends DeepBookOptions {
81
+ client: DeepBookCompatibleClient;
82
+ network: HaneulClientTypes.Network;
83
+ }
84
+
85
+ export function deepbook<Name extends string = 'deepbook'>({
86
+ name = 'deepbook' as Name,
87
+ ...options
88
+ }: DeepBookOptions<Name>): HaneulClientRegistration<DeepBookCompatibleClient, Name, DeepBookClient> {
89
+ return {
90
+ name,
91
+ register: (client) => {
92
+ return new DeepBookClient({
93
+ client,
94
+ network: client.network,
95
+ ...options,
96
+ });
97
+ },
98
+ };
99
+ }
38
100
 
39
101
  /**
40
102
  * DeepBookClient class for managing DeepBook operations.
41
103
  */
42
104
  export class DeepBookClient {
43
- client: HaneulClient;
44
- #config: DeepBookConfig;
45
- #address: string;
105
+ #balanceManagerQueries: BalanceManagerQueries;
106
+ #poolQueries: PoolQueries;
107
+ #quantityQueries: QuantityQueries;
108
+ #orderQueries: OrderQueries;
109
+ #accountQueries: AccountQueries;
110
+ #referralQueries: ReferralQueries;
111
+ #priceFeedQueries: PriceFeedQueries;
112
+ #marginPoolQueries: MarginPoolQueries;
113
+ #marginManagerQueries: MarginManagerQueries;
114
+ #tpslQueries: TPSLQueries;
115
+ #registryQueries: RegistryQueries;
116
+
46
117
  balanceManager: BalanceManagerContract;
47
118
  deepBook: DeepBookContract;
48
119
  deepBookAdmin: DeepBookAdminContract;
@@ -58,21 +129,12 @@ export class DeepBookClient {
58
129
  marginTPSL: MarginTPSLContract;
59
130
 
60
131
  /**
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
132
+ * Creates a new DeepBookClient instance
71
133
  */
72
134
  constructor({
73
135
  client,
74
136
  address,
75
- env,
137
+ network,
76
138
  balanceManagers,
77
139
  marginManagers,
78
140
  coins,
@@ -80,23 +142,13 @@ export class DeepBookClient {
80
142
  adminCap,
81
143
  marginAdminCap,
82
144
  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,
145
+ packageIds,
146
+ pyth,
147
+ }: DeepBookClientOptions) {
148
+ const normalizedAddress = normalizeHaneulAddress(address);
149
+ const config = new DeepBookConfig({
150
+ address: normalizedAddress,
151
+ network,
100
152
  balanceManagers,
101
153
  marginManagers,
102
154
  coins,
@@ -104,2348 +156,508 @@ export class DeepBookClient {
104
156
  adminCap,
105
157
  marginAdminCap,
106
158
  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)),
159
+ packageIds,
160
+ pyth,
161
+ });
162
+
163
+ this.balanceManager = new BalanceManagerContract(config);
164
+ this.deepBook = new DeepBookContract(config);
165
+ this.deepBookAdmin = new DeepBookAdminContract(config);
166
+ this.flashLoans = new FlashLoanContract(config);
167
+ this.governance = new GovernanceContract(config);
168
+ this.marginAdmin = new MarginAdminContract(config);
169
+ this.marginMaintainer = new MarginMaintainerContract(config);
170
+ this.marginPool = new MarginPoolContract(config);
171
+ this.marginManager = new MarginManagerContract(config);
172
+ this.marginRegistry = new MarginRegistryContract(config);
173
+ this.marginLiquidations = new MarginLiquidationsContract(config);
174
+ this.poolProxy = new PoolProxyContract(config);
175
+ this.marginTPSL = new MarginTPSLContract(config);
176
+
177
+ const ctx: QueryContext = {
178
+ client,
179
+ config,
180
+ address: normalizedAddress,
181
+ balanceManager: this.balanceManager,
182
+ deepBook: this.deepBook,
183
+ marginManager: this.marginManager,
184
+ marginPool: this.marginPool,
185
+ marginRegistry: this.marginRegistry,
186
+ marginTPSL: this.marginTPSL,
147
187
  };
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
188
 
167
- return whitelisted;
189
+ this.#balanceManagerQueries = new BalanceManagerQueries(ctx);
190
+ this.#poolQueries = new PoolQueries(ctx);
191
+ this.#quantityQueries = new QuantityQueries(ctx);
192
+ this.#orderQueries = new OrderQueries(ctx);
193
+ this.#accountQueries = new AccountQueries(ctx);
194
+ this.#referralQueries = new ReferralQueries(ctx);
195
+ this.#priceFeedQueries = new PriceFeedQueries(ctx);
196
+ this.#marginPoolQueries = new MarginPoolQueries(ctx);
197
+ this.#marginManagerQueries = new MarginManagerQueries(ctx);
198
+ this.#tpslQueries = new TPSLQueries(ctx);
199
+ this.#registryQueries = new RegistryQueries(ctx);
168
200
  }
169
201
 
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])));
202
+ // === Balance Manager Queries ===
192
203
 
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
- };
204
+ checkManagerBalance(managerKey: string, coinKey: string): Promise<ManagerBalance> {
205
+ return this.#balanceManagerQueries.checkManagerBalance(managerKey, coinKey);
199
206
  }
200
207
 
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
- };
208
+ checkManagerBalanceWithAddress(managerAddress: string, coinKey: string): Promise<ManagerBalance> {
209
+ return this.#balanceManagerQueries.checkManagerBalanceWithAddress(managerAddress, coinKey);
230
210
  }
231
211
 
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
- };
212
+ checkManagerBalancesWithAddress(
213
+ managerAddresses: string[],
214
+ coinKeys: string[],
215
+ ): Promise<Record<string, Record<string, number>>> {
216
+ return this.#balanceManagerQueries.checkManagerBalancesWithAddress(managerAddresses, coinKeys);
263
217
  }
264
218
 
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;
219
+ getBalanceManagerIds(owner: string): Promise<string[]> {
220
+ return this.#balanceManagerQueries.getBalanceManagerIds(owner);
283
221
  }
284
222
 
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();
223
+ accountExists(poolKey: string, managerKey: string): Promise<boolean> {
224
+ return this.#balanceManagerQueries.accountExists(poolKey, managerKey);
225
+ }
293
226
 
294
- tx.add(this.deepBook.getOrder(poolKey, orderId));
295
- const res = await this.client.devInspectTransactionBlock({
296
- sender: normalizeHaneulAddress(this.#address),
297
- transactionBlock: tx,
298
- });
227
+ // === Pool Queries ===
299
228
 
300
- try {
301
- const orderInformation = res.results![0].returnValues![0][0];
302
- return Order.parse(new Uint8Array(orderInformation));
303
- } catch {
304
- return null;
305
- }
229
+ whitelisted(poolKey: string): Promise<boolean> {
230
+ return this.#poolQueries.whitelisted(poolKey);
306
231
  }
307
232
 
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
- });
233
+ vaultBalances(poolKey: string): Promise<VaultBalances> {
234
+ return this.#poolQueries.vaultBalances(poolKey);
235
+ }
321
236
 
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
- }
237
+ getPoolIdByAssets(baseType: string, quoteType: string): Promise<string> {
238
+ return this.#poolQueries.getPoolIdByAssets(baseType, quoteType);
351
239
  }
352
240
 
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();
241
+ midPrice(poolKey: string): Promise<number> {
242
+ return this.#poolQueries.midPrice(poolKey);
243
+ }
363
244
 
364
- tx.add(this.deepBook.getOrders(poolKey, orderIds));
365
- const res = await this.client.devInspectTransactionBlock({
366
- sender: normalizeHaneulAddress(this.#address),
367
- transactionBlock: tx,
368
- });
245
+ poolTradeParams(poolKey: string): Promise<PoolTradeParams> {
246
+ return this.#poolQueries.poolTradeParams(poolKey);
247
+ }
369
248
 
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
- }
249
+ poolBookParams(poolKey: string): Promise<PoolBookParams> {
250
+ return this.#poolQueries.poolBookParams(poolKey);
376
251
  }
377
252
 
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
- });
253
+ stablePool(poolKey: string): Promise<boolean> {
254
+ return this.#poolQueries.stablePool(poolKey);
255
+ }
398
256
 
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
- };
257
+ registeredPool(poolKey: string): Promise<boolean> {
258
+ return this.#poolQueries.registeredPool(poolKey);
412
259
  }
413
260
 
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
- });
261
+ poolTradeParamsNext(poolKey: string): Promise<PoolTradeParams> {
262
+ return this.#poolQueries.poolTradeParamsNext(poolKey);
263
+ }
432
264
 
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
- };
265
+ quorum(poolKey: string): Promise<number> {
266
+ return this.#poolQueries.quorum(poolKey);
457
267
  }
458
268
 
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
- });
269
+ poolId(poolKey: string): Promise<string> {
270
+ return this.#poolQueries.poolId(poolKey);
271
+ }
476
272
 
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])));
273
+ canPlaceLimitOrder(params: CanPlaceLimitOrderParams): Promise<boolean> {
274
+ return this.#poolQueries.canPlaceLimitOrder(params);
275
+ }
480
276
 
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
- };
277
+ canPlaceMarketOrder(params: CanPlaceMarketOrderParams): Promise<boolean> {
278
+ return this.#poolQueries.canPlaceMarketOrder(params);
486
279
  }
487
280
 
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));
281
+ checkMarketOrderParams(poolKey: string, quantity: number | bigint): Promise<boolean> {
282
+ return this.#poolQueries.checkMarketOrderParams(poolKey, quantity);
283
+ }
497
284
 
498
- const res = await this.client.devInspectTransactionBlock({
499
- sender: normalizeHaneulAddress(this.#address),
500
- transactionBlock: tx,
501
- });
285
+ checkLimitOrderParams(
286
+ poolKey: string,
287
+ price: number | bigint,
288
+ quantity: number | bigint,
289
+ expireTimestamp: number,
290
+ ): Promise<boolean> {
291
+ return this.#poolQueries.checkLimitOrderParams(poolKey, price, quantity, expireTimestamp);
292
+ }
502
293
 
503
- const address = bcs.Address.parse(new Uint8Array(res.results![0].returnValues![0][0]));
294
+ // === Quantity Queries ===
504
295
 
505
- return address;
296
+ getQuoteQuantityOut(poolKey: string, baseQuantity: number | bigint): Promise<QuoteQuantityOut> {
297
+ return this.#quantityQueries.getQuoteQuantityOut(poolKey, baseQuantity);
506
298
  }
507
299
 
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);
300
+ getBaseQuantityOut(poolKey: string, quoteQuantity: number | bigint): Promise<BaseQuantityOut> {
301
+ return this.#quantityQueries.getBaseQuantityOut(poolKey, quoteQuantity);
302
+ }
520
303
 
521
- const res = await this.client.devInspectTransactionBlock({
522
- sender: normalizeHaneulAddress(this.#address),
523
- transactionBlock: tx,
524
- });
304
+ getQuantityOut(
305
+ poolKey: string,
306
+ baseQuantity: number | bigint,
307
+ quoteQuantity: number | bigint,
308
+ ): Promise<QuantityOut> {
309
+ return this.#quantityQueries.getQuantityOut(poolKey, baseQuantity, quoteQuantity);
310
+ }
525
311
 
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;
312
+ getQuoteQuantityOutInputFee(
313
+ poolKey: string,
314
+ baseQuantity: number | bigint,
315
+ ): Promise<QuoteQuantityOut> {
316
+ return this.#quantityQueries.getQuoteQuantityOutInputFee(poolKey, baseQuantity);
317
+ }
530
318
 
531
- return Number(adjusted_mid_price.toFixed(9));
319
+ getBaseQuantityOutInputFee(
320
+ poolKey: string,
321
+ quoteQuantity: number | bigint,
322
+ ): Promise<BaseQuantityOut> {
323
+ return this.#quantityQueries.getBaseQuantityOutInputFee(poolKey, quoteQuantity);
532
324
  }
533
325
 
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();
326
+ getQuantityOutInputFee(
327
+ poolKey: string,
328
+ baseQuantity: number | bigint,
329
+ quoteQuantity: number | bigint,
330
+ ): Promise<QuantityOut> {
331
+ return this.#quantityQueries.getQuantityOutInputFee(poolKey, baseQuantity, quoteQuantity);
332
+ }
541
333
 
542
- tx.add(this.deepBook.poolTradeParams(poolKey));
543
- const res = await this.client.devInspectTransactionBlock({
544
- sender: normalizeHaneulAddress(this.#address),
545
- transactionBlock: tx,
546
- });
334
+ getBaseQuantityIn(
335
+ poolKey: string,
336
+ targetQuoteQuantity: number | bigint,
337
+ payWithDeep: boolean,
338
+ ): Promise<BaseQuantityIn> {
339
+ return this.#quantityQueries.getBaseQuantityIn(poolKey, targetQuoteQuantity, payWithDeep);
340
+ }
547
341
 
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
- );
342
+ getQuoteQuantityIn(
343
+ poolKey: string,
344
+ targetBaseQuantity: number | bigint,
345
+ payWithDeep: boolean,
346
+ ): Promise<QuoteQuantityIn> {
347
+ return this.#quantityQueries.getQuoteQuantityIn(poolKey, targetBaseQuantity, payWithDeep);
348
+ }
553
349
 
554
- return {
555
- takerFee: Number(takerFee / FLOAT_SCALAR),
556
- makerFee: Number(makerFee / FLOAT_SCALAR),
557
- stakeRequired: Number(stakeRequired / DEEP_SCALAR),
558
- };
350
+ getOrderDeepRequired(
351
+ poolKey: string,
352
+ baseQuantity: number | bigint,
353
+ price: number | bigint,
354
+ ): Promise<OrderDeepRequiredResult> {
355
+ return this.#quantityQueries.getOrderDeepRequired(poolKey, baseQuantity, price);
559
356
  }
560
357
 
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
- });
358
+ // === Order Queries ===
577
359
 
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])));
360
+ accountOpenOrders(poolKey: string, managerKey: string): Promise<string[]> {
361
+ return this.#orderQueries.accountOpenOrders(poolKey, managerKey);
362
+ }
581
363
 
582
- return {
583
- tickSize: Number((tickSize * baseScalar) / quoteScalar / FLOAT_SCALAR),
584
- lotSize: Number(lotSize / baseScalar),
585
- minSize: Number(minSize / baseScalar),
586
- };
364
+ getOrder(poolKey: string, orderId: string) {
365
+ return this.#orderQueries.getOrder(poolKey, orderId);
587
366
  }
588
367
 
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
- });
368
+ getOrderNormalized(poolKey: string, orderId: string) {
369
+ return this.#orderQueries.getOrderNormalized(poolKey, orderId);
370
+ }
606
371
 
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
- };
372
+ getOrders(poolKey: string, orderIds: string[]) {
373
+ return this.#orderQueries.getOrders(poolKey, orderIds);
635
374
  }
636
375
 
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
- });
376
+ getLevel2Range(
377
+ poolKey: string,
378
+ priceLow: number | bigint,
379
+ priceHigh: number | bigint,
380
+ isBid: boolean,
381
+ ): Promise<Level2Range> {
382
+ return this.#orderQueries.getLevel2Range(poolKey, priceLow, priceHigh, isBid);
383
+ }
655
384
 
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])));
385
+ getLevel2TicksFromMid(poolKey: string, ticks: number): Promise<Level2TicksFromMid> {
386
+ return this.#orderQueries.getLevel2TicksFromMid(poolKey, ticks);
387
+ }
659
388
 
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
- };
389
+ getAccountOrderDetails(poolKey: string, managerKey: string) {
390
+ return this.#orderQueries.getAccountOrderDetails(poolKey, managerKey);
665
391
  }
666
392
 
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
- });
393
+ // === Account Queries ===
685
394
 
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
- }
395
+ account(poolKey: string, managerKey: string): Promise<AccountInfo> {
396
+ return this.#accountQueries.account(poolKey, managerKey);
704
397
  }
705
398
 
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 };
399
+ lockedBalance(poolKey: string, balanceManagerKey: string): Promise<LockedBalances> {
400
+ return this.#accountQueries.lockedBalance(poolKey, balanceManagerKey);
717
401
  }
718
402
 
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));
403
+ getPoolDeepPrice(poolKey: string): Promise<PoolDeepPrice> {
404
+ return this.#accountQueries.getPoolDeepPrice(poolKey);
405
+ }
727
406
 
728
- const res = await this.client.devInspectTransactionBlock({
729
- sender: normalizeHaneulAddress(this.#address),
730
- transactionBlock: tx,
731
- });
407
+ // === Referral Queries ===
732
408
 
733
- const bytes = res.results![0].returnValues![0][0];
734
- const vecOfAddresses = bcs.vector(bcs.Address).parse(new Uint8Array(bytes));
409
+ balanceManagerReferralOwner(referral: string): Promise<string> {
410
+ return this.#referralQueries.balanceManagerReferralOwner(referral);
411
+ }
735
412
 
736
- return vecOfAddresses.map((id: string) => normalizeHaneulAddress(id));
413
+ getPoolReferralBalances(poolKey: string, referral: string): Promise<ReferralBalances> {
414
+ return this.#referralQueries.getPoolReferralBalances(poolKey, referral);
737
415
  }
738
416
 
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));
417
+ balanceManagerReferralPoolId(referral: string): Promise<string> {
418
+ return this.#referralQueries.balanceManagerReferralPoolId(referral);
419
+ }
747
420
 
748
- const res = await this.client.devInspectTransactionBlock({
749
- sender: normalizeHaneulAddress(this.#address),
750
- transactionBlock: tx,
751
- });
421
+ poolReferralMultiplier(poolKey: string, referral: string): Promise<number> {
422
+ return this.#referralQueries.poolReferralMultiplier(poolKey, referral);
423
+ }
752
424
 
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
- }
425
+ getBalanceManagerReferralId(managerKey: string, poolKey: string): Promise<string | null> {
426
+ return this.#referralQueries.getBalanceManagerReferralId(managerKey, poolKey);
427
+ }
756
428
 
757
- const bytes = res.results[0].returnValues![0][0];
758
- const owner = bcs.Address.parse(new Uint8Array(bytes));
429
+ // === Price Feed Queries ===
759
430
 
760
- return owner;
431
+ getPriceInfoObject(tx: Transaction, coinKey: string): Promise<string> {
432
+ return this.#priceFeedQueries.getPriceInfoObject(tx, coinKey);
761
433
  }
762
434
 
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
- });
435
+ getPriceInfoObjects(tx: Transaction, coinKeys: string[]): Promise<Record<string, string>> {
436
+ return this.#priceFeedQueries.getPriceInfoObjects(tx, coinKeys);
437
+ }
784
438
 
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];
439
+ getPriceInfoObjectAge(coinKey: string): Promise<number> {
440
+ return this.#priceFeedQueries.getPriceInfoObjectAge(coinKey);
441
+ }
789
442
 
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)));
443
+ // === Margin Pool Queries ===
793
444
 
794
- return {
795
- base: baseBalance / baseScalar,
796
- quote: quoteBalance / quoteScalar,
797
- deep: deepBalance / DEEP_SCALAR,
798
- };
445
+ getMarginPoolId(coinKey: string): Promise<string> {
446
+ return this.#marginPoolQueries.getMarginPoolId(coinKey);
799
447
  }
800
448
 
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));
449
+ isDeepbookPoolAllowed(coinKey: string, deepbookPoolId: string): Promise<boolean> {
450
+ return this.#marginPoolQueries.isDeepbookPoolAllowed(coinKey, deepbookPoolId);
451
+ }
810
452
 
811
- const res = await this.client.devInspectTransactionBlock({
812
- sender: normalizeHaneulAddress(this.#address),
813
- transactionBlock: tx,
814
- });
453
+ getMarginPoolTotalSupply(coinKey: string, decimals: number = 6): Promise<string> {
454
+ return this.#marginPoolQueries.getMarginPoolTotalSupply(coinKey, decimals);
455
+ }
815
456
 
816
- const bytes = res.results![0].returnValues![0][0];
817
- const poolId = bcs.Address.parse(new Uint8Array(bytes));
457
+ getMarginPoolSupplyShares(coinKey: string, decimals: number = 6): Promise<string> {
458
+ return this.#marginPoolQueries.getMarginPoolSupplyShares(coinKey, decimals);
459
+ }
818
460
 
819
- return normalizeHaneulAddress(poolId);
461
+ getMarginPoolTotalBorrow(coinKey: string, decimals: number = 6): Promise<string> {
462
+ return this.#marginPoolQueries.getMarginPoolTotalBorrow(coinKey, decimals);
820
463
  }
821
464
 
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();
465
+ getMarginPoolBorrowShares(coinKey: string, decimals: number = 6): Promise<string> {
466
+ return this.#marginPoolQueries.getMarginPoolBorrowShares(coinKey, decimals);
467
+ }
830
468
 
831
- tx.add(this.deepBook.poolReferralMultiplier(poolKey, referral));
469
+ getMarginPoolLastUpdateTimestamp(coinKey: string): Promise<number> {
470
+ return this.#marginPoolQueries.getMarginPoolLastUpdateTimestamp(coinKey);
471
+ }
832
472
 
833
- const res = await this.client.devInspectTransactionBlock({
834
- sender: normalizeHaneulAddress(this.#address),
835
- transactionBlock: tx,
836
- });
473
+ getMarginPoolSupplyCap(coinKey: string, decimals: number = 6): Promise<string> {
474
+ return this.#marginPoolQueries.getMarginPoolSupplyCap(coinKey, decimals);
475
+ }
837
476
 
838
- const bytes = res.results![0].returnValues![0][0];
839
- const multiplier = Number(bcs.U64.parse(new Uint8Array(bytes)));
477
+ getMarginPoolMaxUtilizationRate(coinKey: string): Promise<number> {
478
+ return this.#marginPoolQueries.getMarginPoolMaxUtilizationRate(coinKey);
479
+ }
840
480
 
841
- return multiplier / FLOAT_SCALAR;
481
+ getMarginPoolProtocolSpread(coinKey: string): Promise<number> {
482
+ return this.#marginPoolQueries.getMarginPoolProtocolSpread(coinKey);
842
483
  }
843
484
 
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));
485
+ getMarginPoolMinBorrow(coinKey: string, decimals: number = 6): Promise<string> {
486
+ return this.#marginPoolQueries.getMarginPoolMinBorrow(coinKey, decimals);
487
+ }
853
488
 
854
- const res = await this.client.devInspectTransactionBlock({
855
- sender: normalizeHaneulAddress(this.#address),
856
- transactionBlock: tx,
857
- });
489
+ getMarginPoolInterestRate(coinKey: string): Promise<number> {
490
+ return this.#marginPoolQueries.getMarginPoolInterestRate(coinKey);
491
+ }
858
492
 
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
- }
493
+ getUserSupplyShares(
494
+ coinKey: string,
495
+ supplierCapId: string,
496
+ decimals: number = 6,
497
+ ): Promise<string> {
498
+ return this.#marginPoolQueries.getUserSupplyShares(coinKey, supplierCapId, decimals);
869
499
  }
870
500
 
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
- }
501
+ getUserSupplyAmount(
502
+ coinKey: string,
503
+ supplierCapId: string,
504
+ decimals: number = 6,
505
+ ): Promise<string> {
506
+ return this.#marginPoolQueries.getUserSupplyAmount(coinKey, supplierCapId, decimals);
507
+ }
877
508
 
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);
509
+ // === Margin Manager Queries ===
884
510
 
885
- // List of price feed IDs
886
- const priceIDs = [
887
- this.#config.getCoin(coinKey).feed!, // ASSET/USD price ID
888
- ];
511
+ getMarginManagerOwner(marginManagerKey: string): Promise<string> {
512
+ return this.#marginManagerQueries.getMarginManagerOwner(marginManagerKey);
513
+ }
889
514
 
890
- // Fetch price feed update data
891
- const priceUpdateData = await connection.getPriceFeedsUpdateData(priceIDs);
515
+ getMarginManagerDeepbookPool(marginManagerKey: string): Promise<string> {
516
+ return this.#marginManagerQueries.getMarginManagerDeepbookPool(marginManagerKey);
517
+ }
892
518
 
893
- // Initialize Sui Client and Pyth Client
894
- const wormholeStateId = this.#config.pyth.wormholeStateId;
895
- const pythStateId = this.#config.pyth.pythStateId;
519
+ getMarginManagerMarginPoolId(marginManagerKey: string): Promise<string | null> {
520
+ return this.#marginManagerQueries.getMarginManagerMarginPoolId(marginManagerKey);
521
+ }
896
522
 
897
- const client = new HaneulPythClient(this.client, pythStateId, wormholeStateId);
523
+ getMarginManagerBorrowedShares(marginManagerKey: string): Promise<BorrowedShares> {
524
+ return this.#marginManagerQueries.getMarginManagerBorrowedShares(marginManagerKey);
525
+ }
898
526
 
899
- return (await client.updatePriceFeeds(tx, priceUpdateData, priceIDs))[0]; // returns priceInfoObjectIds
527
+ getMarginManagerBorrowedBaseShares(marginManagerKey: string): Promise<string> {
528
+ return this.#marginManagerQueries.getMarginManagerBorrowedBaseShares(marginManagerKey);
900
529
  }
901
530
 
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
- });
531
+ getMarginManagerBorrowedQuoteShares(marginManagerKey: string): Promise<string> {
532
+ return this.#marginManagerQueries.getMarginManagerBorrowedQuoteShares(marginManagerKey);
533
+ }
915
534
 
916
- if (!res.data?.content) {
917
- throw new Error(`Price info object not found for ${coinKey}`);
918
- }
535
+ getMarginManagerHasBaseDebt(marginManagerKey: string): Promise<boolean> {
536
+ return this.#marginManagerQueries.getMarginManagerHasBaseDebt(marginManagerKey);
537
+ }
919
538
 
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
- }
539
+ getMarginManagerBalanceManagerId(marginManagerAddress: string): Promise<string> {
540
+ return this.#marginManagerQueries.getMarginManagerBalanceManagerId(marginManagerAddress);
927
541
  }
928
542
 
929
- // === Margin Pool View Methods ===
543
+ getMarginManagerAssets(
544
+ marginManagerKey: string,
545
+ decimals: number = 6,
546
+ ): Promise<MarginManagerAssets> {
547
+ return this.#marginManagerQueries.getMarginManagerAssets(marginManagerKey, decimals);
548
+ }
930
549
 
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));
550
+ getMarginManagerDebts(
551
+ marginManagerKey: string,
552
+ decimals: number = 6,
553
+ ): Promise<MarginManagerDebts> {
554
+ return this.#marginManagerQueries.getMarginManagerDebts(marginManagerKey, decimals);
555
+ }
939
556
 
940
- const res = await this.client.devInspectTransactionBlock({
941
- sender: normalizeHaneulAddress(this.#address),
942
- transactionBlock: tx,
943
- });
557
+ getMarginManagerState(
558
+ marginManagerKey: string,
559
+ decimals: number = 6,
560
+ ): Promise<MarginManagerState> {
561
+ return this.#marginManagerQueries.getMarginManagerState(marginManagerKey, decimals);
562
+ }
944
563
 
945
- const bytes = res.results![0].returnValues![0][0];
946
- return bcs.Address.parse(new Uint8Array(bytes));
564
+ getMarginManagerStates(
565
+ marginManagers: Record<string, string>,
566
+ decimals: number = 6,
567
+ ): Promise<Record<string, MarginManagerState>> {
568
+ return this.#marginManagerQueries.getMarginManagerStates(marginManagers, decimals);
947
569
  }
948
570
 
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));
571
+ getMarginManagerBaseBalance(marginManagerKey: string, decimals: number = 9): Promise<string> {
572
+ return this.#marginManagerQueries.getMarginManagerBaseBalance(marginManagerKey, decimals);
573
+ }
958
574
 
959
- const res = await this.client.devInspectTransactionBlock({
960
- sender: normalizeHaneulAddress(this.#address),
961
- transactionBlock: tx,
962
- });
575
+ getMarginManagerQuoteBalance(marginManagerKey: string, decimals: number = 9): Promise<string> {
576
+ return this.#marginManagerQueries.getMarginManagerQuoteBalance(marginManagerKey, decimals);
577
+ }
963
578
 
964
- const bytes = res.results![0].returnValues![0][0];
965
- return bcs.bool().parse(new Uint8Array(bytes));
579
+ getMarginManagerDeepBalance(marginManagerKey: string, decimals: number = 6): Promise<string> {
580
+ return this.#marginManagerQueries.getMarginManagerDeepBalance(marginManagerKey, decimals);
966
581
  }
967
582
 
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));
583
+ getMarginManagerBalances(
584
+ marginManagers: Record<string, string>,
585
+ decimals: number = 9,
586
+ ): Promise<Record<string, MarginManagerBalancesResult>> {
587
+ return this.#marginManagerQueries.getMarginManagerBalances(marginManagers, decimals);
588
+ }
977
589
 
978
- const res = await this.client.devInspectTransactionBlock({
979
- sender: normalizeHaneulAddress(this.#address),
980
- transactionBlock: tx,
981
- });
590
+ // === TPSL Queries ===
982
591
 
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);
592
+ getConditionalOrderIds(marginManagerKey: string): Promise<string[]> {
593
+ return this.#tpslQueries.getConditionalOrderIds(marginManagerKey);
987
594
  }
988
595
 
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
- });
596
+ getLowestTriggerAbovePrice(marginManagerKey: string): Promise<bigint> {
597
+ return this.#tpslQueries.getLowestTriggerAbovePrice(marginManagerKey);
598
+ }
1003
599
 
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);
600
+ getHighestTriggerBelowPrice(marginManagerKey: string): Promise<bigint> {
601
+ return this.#tpslQueries.getHighestTriggerBelowPrice(marginManagerKey);
1008
602
  }
1009
603
 
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));
604
+ // === Registry Queries ===
1019
605
 
1020
- const res = await this.client.devInspectTransactionBlock({
1021
- sender: normalizeHaneulAddress(this.#address),
1022
- transactionBlock: tx,
1023
- });
606
+ isPoolEnabledForMargin(poolKey: string): Promise<boolean> {
607
+ return this.#registryQueries.isPoolEnabledForMargin(poolKey);
608
+ }
1024
609
 
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);
610
+ getMarginManagerIdsForOwner(owner: string): Promise<string[]> {
611
+ return this.#registryQueries.getMarginManagerIdsForOwner(owner);
1029
612
  }
1030
613
 
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));
614
+ getBaseMarginPoolId(poolKey: string): Promise<string> {
615
+ return this.#registryQueries.getBaseMarginPoolId(poolKey);
616
+ }
1040
617
 
1041
- const res = await this.client.devInspectTransactionBlock({
1042
- sender: normalizeHaneulAddress(this.#address),
1043
- transactionBlock: tx,
1044
- });
618
+ getQuoteMarginPoolId(poolKey: string): Promise<string> {
619
+ return this.#registryQueries.getQuoteMarginPoolId(poolKey);
620
+ }
1045
621
 
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);
622
+ getMinWithdrawRiskRatio(poolKey: string): Promise<number> {
623
+ return this.#registryQueries.getMinWithdrawRiskRatio(poolKey);
1050
624
  }
1051
625
 
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));
626
+ getMinBorrowRiskRatio(poolKey: string): Promise<number> {
627
+ return this.#registryQueries.getMinBorrowRiskRatio(poolKey);
628
+ }
1060
629
 
1061
- const res = await this.client.devInspectTransactionBlock({
1062
- sender: normalizeHaneulAddress(this.#address),
1063
- transactionBlock: tx,
1064
- });
630
+ getLiquidationRiskRatio(poolKey: string): Promise<number> {
631
+ return this.#registryQueries.getLiquidationRiskRatio(poolKey);
632
+ }
1065
633
 
1066
- const bytes = res.results![0].returnValues![0][0];
1067
- return Number(bcs.U64.parse(new Uint8Array(bytes)));
634
+ getTargetLiquidationRiskRatio(poolKey: string): Promise<number> {
635
+ return this.#registryQueries.getTargetLiquidationRiskRatio(poolKey);
1068
636
  }
1069
637
 
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));
638
+ getUserLiquidationReward(poolKey: string): Promise<number> {
639
+ return this.#registryQueries.getUserLiquidationReward(poolKey);
640
+ }
1079
641
 
1080
- const res = await this.client.devInspectTransactionBlock({
1081
- sender: normalizeHaneulAddress(this.#address),
1082
- transactionBlock: tx,
1083
- });
642
+ getPoolLiquidationReward(poolKey: string): Promise<number> {
643
+ return this.#registryQueries.getPoolLiquidationReward(poolKey);
644
+ }
1084
645
 
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);
646
+ getAllowedMaintainers(): Promise<string[]> {
647
+ return this.#registryQueries.getAllowedMaintainers();
1089
648
  }
1090
649
 
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));
650
+ getAllowedPauseCaps(): Promise<string[]> {
651
+ return this.#registryQueries.getAllowedPauseCaps();
652
+ }
1099
653
 
1100
- const res = await this.client.devInspectTransactionBlock({
1101
- sender: normalizeHaneulAddress(this.#address),
1102
- transactionBlock: tx,
1103
- });
654
+ // === Synchronous Utilities ===
1104
655
 
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
- }
656
+ decodeOrderId(encodedOrderId: bigint): DecodedOrderId {
657
+ const isBid = encodedOrderId >> 127n === 0n;
658
+ const price = Number((encodedOrderId >> 64n) & ((1n << 63n) - 1n));
659
+ const orderId = Number(encodedOrderId & ((1n << 64n) - 1n));
2448
660
 
2449
- return `${integerPart}.${trimmed}`;
661
+ return { isBid, price, orderId };
2450
662
  }
2451
663
  }