@haneullabs/deepbook-v3 0.1.0 → 1.0.11

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