@waterx/sdk 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +204 -0
  3. package/dist/src/client.d.ts +109 -0
  4. package/dist/src/client.js +197 -0
  5. package/dist/src/config.d.ts +229 -0
  6. package/dist/src/config.js +107 -0
  7. package/dist/src/constants.d.ts +64 -0
  8. package/dist/src/constants.js +71 -0
  9. package/dist/src/fetch.d.ts +144 -0
  10. package/dist/src/fetch.js +419 -0
  11. package/dist/src/generated/bucket_v2_framework/account.d.ts +107 -0
  12. package/dist/src/generated/bucket_v2_framework/account.js +129 -0
  13. package/dist/src/generated/bucket_v2_framework/deps/std/type_name.d.ts +17 -0
  14. package/dist/src/generated/bucket_v2_framework/deps/std/type_name.js +19 -0
  15. package/dist/src/generated/bucket_v2_framework/deps/sui/balance.d.ts +12 -0
  16. package/dist/src/generated/bucket_v2_framework/deps/sui/balance.js +14 -0
  17. package/dist/src/generated/bucket_v2_framework/deps/sui/vec_map.d.ts +36 -0
  18. package/dist/src/generated/bucket_v2_framework/deps/sui/vec_map.js +27 -0
  19. package/dist/src/generated/bucket_v2_framework/deps/sui/vec_set.d.ts +16 -0
  20. package/dist/src/generated/bucket_v2_framework/deps/sui/vec_set.js +19 -0
  21. package/dist/src/generated/bucket_v2_framework/double.d.ts +384 -0
  22. package/dist/src/generated/bucket_v2_framework/double.js +466 -0
  23. package/dist/src/generated/bucket_v2_framework/float.d.ts +364 -0
  24. package/dist/src/generated/bucket_v2_framework/float.js +440 -0
  25. package/dist/src/generated/bucket_v2_framework/liability.d.ts +197 -0
  26. package/dist/src/generated/bucket_v2_framework/liability.js +205 -0
  27. package/dist/src/generated/bucket_v2_framework/linked_table.d.ts +384 -0
  28. package/dist/src/generated/bucket_v2_framework/linked_table.js +382 -0
  29. package/dist/src/generated/bucket_v2_framework/sheet.d.ts +424 -0
  30. package/dist/src/generated/bucket_v2_framework/sheet.js +344 -0
  31. package/dist/src/generated/native_custody/custody_vault.d.ts +572 -0
  32. package/dist/src/generated/native_custody/custody_vault.js +483 -0
  33. package/dist/src/generated/native_custody/deps/bucket_v2_framework/float.d.ts +8 -0
  34. package/dist/src/generated/native_custody/deps/bucket_v2_framework/float.js +10 -0
  35. package/dist/src/generated/native_custody/deps/bucket_v2_framework/liability.d.ts +11 -0
  36. package/dist/src/generated/native_custody/deps/bucket_v2_framework/liability.js +13 -0
  37. package/dist/src/generated/native_custody/deps/bucket_v2_framework/sheet.d.ts +49 -0
  38. package/dist/src/generated/native_custody/deps/bucket_v2_framework/sheet.js +18 -0
  39. package/dist/src/generated/native_custody/deps/std/type_name.d.ts +17 -0
  40. package/dist/src/generated/native_custody/deps/std/type_name.js +19 -0
  41. package/dist/src/generated/native_custody/deps/sui/balance.d.ts +12 -0
  42. package/dist/src/generated/native_custody/deps/sui/balance.js +14 -0
  43. package/dist/src/generated/native_custody/deps/sui/vec_map.d.ts +36 -0
  44. package/dist/src/generated/native_custody/deps/sui/vec_map.js +27 -0
  45. package/dist/src/generated/native_custody/deps/sui/vec_set.d.ts +16 -0
  46. package/dist/src/generated/native_custody/deps/sui/vec_set.js +19 -0
  47. package/dist/src/generated/native_custody/events.d.ts +36 -0
  48. package/dist/src/generated/native_custody/events.js +36 -0
  49. package/dist/src/generated/pyth_sponsor_rule/deps/sui/balance.d.ts +12 -0
  50. package/dist/src/generated/pyth_sponsor_rule/deps/sui/balance.js +14 -0
  51. package/dist/src/generated/pyth_sponsor_rule/pyth_sponsor_rule.d.ts +68 -0
  52. package/dist/src/generated/pyth_sponsor_rule/pyth_sponsor_rule.js +74 -0
  53. package/dist/src/generated/utils/index.d.ts +30 -0
  54. package/dist/src/generated/utils/index.js +157 -0
  55. package/dist/src/generated/waterx_account/account.d.ts +1818 -0
  56. package/dist/src/generated/waterx_account/account.js +1723 -0
  57. package/dist/src/generated/waterx_account/deps/bucket_v2_framework/liability.d.ts +11 -0
  58. package/dist/src/generated/waterx_account/deps/bucket_v2_framework/liability.js +13 -0
  59. package/dist/src/generated/waterx_account/deps/bucket_v2_framework/sheet.d.ts +49 -0
  60. package/dist/src/generated/waterx_account/deps/bucket_v2_framework/sheet.js +18 -0
  61. package/dist/src/generated/waterx_account/deps/std/type_name.d.ts +17 -0
  62. package/dist/src/generated/waterx_account/deps/std/type_name.js +19 -0
  63. package/dist/src/generated/waterx_account/deps/sui/balance.d.ts +12 -0
  64. package/dist/src/generated/waterx_account/deps/sui/balance.js +14 -0
  65. package/dist/src/generated/waterx_account/deps/sui/object_table.d.ts +17 -0
  66. package/dist/src/generated/waterx_account/deps/sui/object_table.js +19 -0
  67. package/dist/src/generated/waterx_account/deps/sui/table.d.ts +29 -0
  68. package/dist/src/generated/waterx_account/deps/sui/table.js +31 -0
  69. package/dist/src/generated/waterx_account/deps/sui/vec_map.d.ts +36 -0
  70. package/dist/src/generated/waterx_account/deps/sui/vec_map.js +27 -0
  71. package/dist/src/generated/waterx_account/deps/sui/vec_set.d.ts +16 -0
  72. package/dist/src/generated/waterx_account/deps/sui/vec_set.js +19 -0
  73. package/dist/src/generated/waterx_account/direct_rule.d.ts +77 -0
  74. package/dist/src/generated/waterx_account/direct_rule.js +78 -0
  75. package/dist/src/generated/waterx_account/events.d.ts +180 -0
  76. package/dist/src/generated/waterx_account/events.js +156 -0
  77. package/dist/src/generated/waterx_account/version.d.ts +10 -0
  78. package/dist/src/generated/waterx_account/version.js +8 -0
  79. package/dist/src/generated/waterx_credit/credit_registry.d.ts +708 -0
  80. package/dist/src/generated/waterx_credit/credit_registry.js +658 -0
  81. package/dist/src/generated/waterx_credit/deps/std/type_name.d.ts +17 -0
  82. package/dist/src/generated/waterx_credit/deps/std/type_name.js +19 -0
  83. package/dist/src/generated/waterx_credit/deps/sui/table.d.ts +29 -0
  84. package/dist/src/generated/waterx_credit/deps/sui/table.js +31 -0
  85. package/dist/src/generated/waterx_credit/deps/sui/vec_map.d.ts +36 -0
  86. package/dist/src/generated/waterx_credit/deps/sui/vec_map.js +27 -0
  87. package/dist/src/generated/waterx_credit/deps/sui/vec_set.d.ts +16 -0
  88. package/dist/src/generated/waterx_credit/deps/sui/vec_set.js +19 -0
  89. package/dist/src/generated/waterx_credit/limited_supply.d.ts +107 -0
  90. package/dist/src/generated/waterx_credit/limited_supply.js +131 -0
  91. package/dist/src/generated/waterx_oracle/aggregator.d.ts +211 -0
  92. package/dist/src/generated/waterx_oracle/aggregator.js +213 -0
  93. package/dist/src/generated/waterx_oracle/collector.d.ts +119 -0
  94. package/dist/src/generated/waterx_oracle/collector.js +105 -0
  95. package/dist/src/generated/waterx_oracle/deps/bucket_v2_framework/float.d.ts +8 -0
  96. package/dist/src/generated/waterx_oracle/deps/bucket_v2_framework/float.js +10 -0
  97. package/dist/src/generated/waterx_oracle/deps/std/type_name.d.ts +17 -0
  98. package/dist/src/generated/waterx_oracle/deps/std/type_name.js +19 -0
  99. package/dist/src/generated/waterx_oracle/deps/sui/vec_map.d.ts +36 -0
  100. package/dist/src/generated/waterx_oracle/deps/sui/vec_map.js +27 -0
  101. package/dist/src/generated/waterx_oracle/deps/sui/vec_set.d.ts +16 -0
  102. package/dist/src/generated/waterx_oracle/deps/sui/vec_set.js +19 -0
  103. package/dist/src/generated/waterx_oracle/oracle.d.ts +298 -0
  104. package/dist/src/generated/waterx_oracle/oracle.js +323 -0
  105. package/dist/src/generated/waterx_oracle/version.d.ts +10 -0
  106. package/dist/src/generated/waterx_oracle/version.js +8 -0
  107. package/dist/src/generated/waterx_perp/account_data.d.ts +269 -0
  108. package/dist/src/generated/waterx_perp/account_data.js +284 -0
  109. package/dist/src/generated/waterx_perp/admin.d.ts +19 -0
  110. package/dist/src/generated/waterx_perp/admin.js +22 -0
  111. package/dist/src/generated/waterx_perp/deps/bucket_v2_framework/double.d.ts +8 -0
  112. package/dist/src/generated/waterx_perp/deps/bucket_v2_framework/double.js +10 -0
  113. package/dist/src/generated/waterx_perp/deps/bucket_v2_framework/float.d.ts +8 -0
  114. package/dist/src/generated/waterx_perp/deps/bucket_v2_framework/float.js +10 -0
  115. package/dist/src/generated/waterx_perp/deps/bucket_v2_framework/liability.d.ts +11 -0
  116. package/dist/src/generated/waterx_perp/deps/bucket_v2_framework/liability.js +13 -0
  117. package/dist/src/generated/waterx_perp/deps/bucket_v2_framework/linked_table.d.ts +8 -0
  118. package/dist/src/generated/waterx_perp/deps/bucket_v2_framework/linked_table.js +18 -0
  119. package/dist/src/generated/waterx_perp/deps/bucket_v2_framework/sheet.d.ts +49 -0
  120. package/dist/src/generated/waterx_perp/deps/bucket_v2_framework/sheet.js +18 -0
  121. package/dist/src/generated/waterx_perp/deps/std/type_name.d.ts +17 -0
  122. package/dist/src/generated/waterx_perp/deps/std/type_name.js +19 -0
  123. package/dist/src/generated/waterx_perp/deps/sui/balance.d.ts +15 -0
  124. package/dist/src/generated/waterx_perp/deps/sui/balance.js +17 -0
  125. package/dist/src/generated/waterx_perp/deps/sui/coin.d.ts +14 -0
  126. package/dist/src/generated/waterx_perp/deps/sui/coin.js +15 -0
  127. package/dist/src/generated/waterx_perp/deps/sui/vec_map.d.ts +36 -0
  128. package/dist/src/generated/waterx_perp/deps/sui/vec_map.js +27 -0
  129. package/dist/src/generated/waterx_perp/deps/sui/vec_set.d.ts +16 -0
  130. package/dist/src/generated/waterx_perp/deps/sui/vec_set.js +19 -0
  131. package/dist/src/generated/waterx_perp/events.d.ts +1283 -0
  132. package/dist/src/generated/waterx_perp/events.js +1018 -0
  133. package/dist/src/generated/waterx_perp/global_config.d.ts +775 -0
  134. package/dist/src/generated/waterx_perp/global_config.js +836 -0
  135. package/dist/src/generated/waterx_perp/keyed_big_vector.d.ts +553 -0
  136. package/dist/src/generated/waterx_perp/keyed_big_vector.js +554 -0
  137. package/dist/src/generated/waterx_perp/lp_pool.d.ts +1648 -0
  138. package/dist/src/generated/waterx_perp/lp_pool.js +1521 -0
  139. package/dist/src/generated/waterx_perp/market_config.d.ts +715 -0
  140. package/dist/src/generated/waterx_perp/market_config.js +780 -0
  141. package/dist/src/generated/waterx_perp/math.d.ts +63 -0
  142. package/dist/src/generated/waterx_perp/math.js +64 -0
  143. package/dist/src/generated/waterx_perp/memo.d.ts +251 -0
  144. package/dist/src/generated/waterx_perp/memo.js +323 -0
  145. package/dist/src/generated/waterx_perp/order_book.d.ts +290 -0
  146. package/dist/src/generated/waterx_perp/order_book.js +329 -0
  147. package/dist/src/generated/waterx_perp/position.d.ts +1005 -0
  148. package/dist/src/generated/waterx_perp/position.js +1103 -0
  149. package/dist/src/generated/waterx_perp/request.d.ts +544 -0
  150. package/dist/src/generated/waterx_perp/request.js +541 -0
  151. package/dist/src/generated/waterx_perp/response.d.ts +247 -0
  152. package/dist/src/generated/waterx_perp/response.js +280 -0
  153. package/dist/src/generated/waterx_perp/trading.d.ts +2821 -0
  154. package/dist/src/generated/waterx_perp/trading.js +2372 -0
  155. package/dist/src/generated/waterx_perp/version.d.ts +10 -0
  156. package/dist/src/generated/waterx_perp/version.js +8 -0
  157. package/dist/src/generated/waterx_perp/witness.d.ts +18 -0
  158. package/dist/src/generated/waterx_perp/witness.js +21 -0
  159. package/dist/src/generated/waterx_perp_view/deps/std/type_name.d.ts +17 -0
  160. package/dist/src/generated/waterx_perp_view/deps/std/type_name.js +19 -0
  161. package/dist/src/generated/waterx_perp_view/view.d.ts +447 -0
  162. package/dist/src/generated/waterx_perp_view/view.js +414 -0
  163. package/dist/src/generated/waterx_pyth_rule/deps/sui/vec_map.d.ts +36 -0
  164. package/dist/src/generated/waterx_pyth_rule/deps/sui/vec_map.js +27 -0
  165. package/dist/src/generated/waterx_pyth_rule/pyth_rule.d.ts +90 -0
  166. package/dist/src/generated/waterx_pyth_rule/pyth_rule.js +72 -0
  167. package/dist/src/generated/waterx_referral/deps/sui/table.d.ts +29 -0
  168. package/dist/src/generated/waterx_referral/deps/sui/table.js +31 -0
  169. package/dist/src/generated/waterx_referral/deps/sui/vec_set.d.ts +16 -0
  170. package/dist/src/generated/waterx_referral/deps/sui/vec_set.js +19 -0
  171. package/dist/src/generated/waterx_referral/referral_table.d.ts +171 -0
  172. package/dist/src/generated/waterx_referral/referral_table.js +192 -0
  173. package/dist/src/generated/waterx_staking/deps/bucket_v2_framework/double.d.ts +8 -0
  174. package/dist/src/generated/waterx_staking/deps/bucket_v2_framework/double.js +10 -0
  175. package/dist/src/generated/waterx_staking/deps/sui/balance.d.ts +12 -0
  176. package/dist/src/generated/waterx_staking/deps/sui/balance.js +14 -0
  177. package/dist/src/generated/waterx_staking/deps/sui/table.d.ts +29 -0
  178. package/dist/src/generated/waterx_staking/deps/sui/table.js +31 -0
  179. package/dist/src/generated/waterx_staking/deps/sui/vec_set.d.ts +16 -0
  180. package/dist/src/generated/waterx_staking/deps/sui/vec_set.js +19 -0
  181. package/dist/src/generated/waterx_staking/waterx_staking.d.ts +746 -0
  182. package/dist/src/generated/waterx_staking/waterx_staking.js +731 -0
  183. package/dist/src/generated/waterx_staking/witness.d.ts +16 -0
  184. package/dist/src/generated/waterx_staking/witness.js +18 -0
  185. package/dist/src/generated/withdrawal_queue/deps/bucket_v2_framework/linked_table.d.ts +8 -0
  186. package/dist/src/generated/withdrawal_queue/deps/bucket_v2_framework/linked_table.js +18 -0
  187. package/dist/src/generated/withdrawal_queue/deps/std/type_name.d.ts +17 -0
  188. package/dist/src/generated/withdrawal_queue/deps/std/type_name.js +19 -0
  189. package/dist/src/generated/withdrawal_queue/deps/sui/balance.d.ts +12 -0
  190. package/dist/src/generated/withdrawal_queue/deps/sui/balance.js +14 -0
  191. package/dist/src/generated/withdrawal_queue/deps/sui/vec_set.d.ts +16 -0
  192. package/dist/src/generated/withdrawal_queue/deps/sui/vec_set.js +19 -0
  193. package/dist/src/generated/withdrawal_queue/withdrawal_queue.d.ts +483 -0
  194. package/dist/src/generated/withdrawal_queue/withdrawal_queue.js +480 -0
  195. package/dist/src/generated/wlp/wlp.d.ts +28 -0
  196. package/dist/src/generated/wlp/wlp.js +32 -0
  197. package/dist/src/generated/wormhole_bridge/deps/sui/table.d.ts +29 -0
  198. package/dist/src/generated/wormhole_bridge/deps/sui/table.js +31 -0
  199. package/dist/src/generated/wormhole_bridge/deps/sui/vec_map.d.ts +36 -0
  200. package/dist/src/generated/wormhole_bridge/deps/sui/vec_map.js +27 -0
  201. package/dist/src/generated/wormhole_bridge/deps/sui/vec_set.d.ts +16 -0
  202. package/dist/src/generated/wormhole_bridge/deps/sui/vec_set.js +19 -0
  203. package/dist/src/generated/wormhole_bridge/deps/wormhole_sdk/consumed_vaas.d.ts +12 -0
  204. package/dist/src/generated/wormhole_bridge/deps/wormhole_sdk/consumed_vaas.js +9 -0
  205. package/dist/src/generated/wormhole_bridge/deps/wormhole_sdk/emitter.d.ts +14 -0
  206. package/dist/src/generated/wormhole_bridge/deps/wormhole_sdk/emitter.js +16 -0
  207. package/dist/src/generated/wormhole_bridge/deps/wormhole_sdk/set.d.ts +16 -0
  208. package/dist/src/generated/wormhole_bridge/deps/wormhole_sdk/set.js +15 -0
  209. package/dist/src/generated/wormhole_bridge/events.d.ts +32 -0
  210. package/dist/src/generated/wormhole_bridge/events.js +28 -0
  211. package/dist/src/generated/wormhole_bridge/wormhole_bridge.d.ts +498 -0
  212. package/dist/src/generated/wormhole_bridge/wormhole_bridge.js +494 -0
  213. package/dist/src/index.d.ts +28 -0
  214. package/dist/src/index.js +34 -0
  215. package/dist/src/tx-builders.d.ts +242 -0
  216. package/dist/src/tx-builders.js +320 -0
  217. package/dist/src/user/account.d.ts +129 -0
  218. package/dist/src/user/account.js +166 -0
  219. package/dist/src/user/credit.d.ts +135 -0
  220. package/dist/src/user/credit.js +255 -0
  221. package/dist/src/user/custody.d.ts +71 -0
  222. package/dist/src/user/custody.js +112 -0
  223. package/dist/src/user/index.d.ts +8 -0
  224. package/dist/src/user/index.js +8 -0
  225. package/dist/src/user/order.d.ts +89 -0
  226. package/dist/src/user/order.js +134 -0
  227. package/dist/src/user/referral.d.ts +21 -0
  228. package/dist/src/user/referral.js +41 -0
  229. package/dist/src/user/staking.d.ts +54 -0
  230. package/dist/src/user/staking.js +109 -0
  231. package/dist/src/user/trading.d.ts +119 -0
  232. package/dist/src/user/trading.js +262 -0
  233. package/dist/src/user/wlp.d.ts +58 -0
  234. package/dist/src/user/wlp.js +99 -0
  235. package/dist/src/utils/account-request.d.ts +9 -0
  236. package/dist/src/utils/account-request.js +17 -0
  237. package/dist/src/utils/config.d.ts +11 -0
  238. package/dist/src/utils/config.js +15 -0
  239. package/dist/src/utils/math.d.ts +201 -0
  240. package/dist/src/utils/math.js +343 -0
  241. package/dist/src/utils/pyth.d.ts +89 -0
  242. package/dist/src/utils/pyth.js +316 -0
  243. package/dist/src/utils/wormhole.d.ts +86 -0
  244. package/dist/src/utils/wormhole.js +154 -0
  245. package/package.json +66 -0
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Convert a human-readable USD price to the raw 1e9-scaled `u128` value
3
+ * that on-chain `Float`-typed parameters expect.
4
+ */
5
+ export declare function rawPrice(usd: number | string): bigint;
6
+ /** Notional value in USD: sizeInAsset × price. */
7
+ export declare function calcNotional(sizeInAsset: number, price: number): number;
8
+ /** Trading fee in USD: notional × feeRate. */
9
+ export declare function calcFee(sizeUsd: number, feeRate: number): number;
10
+ /** Unrealized perp Pnl in USD (before fees). */
11
+ export declare function calcUnrealizedPnl(isLong: boolean, entryPrice: number, spotPrice: number, sizeInAsset: number): number;
12
+ /** Position leverage = notional / collateralUsd. Returns Infinity when collateral is zero. */
13
+ export declare function calcLeverage(sizeUsd: number, collateralUsd: number): number;
14
+ /**
15
+ * Estimated liquidation price.
16
+ *
17
+ * Matches `calculate_est_liq_price` in `waterx_perp_view/sources/view.move`:
18
+ * maintenance = maintenanceMarginRate × (size × spotPrice) ← uses current notional
19
+ * ratio = (collateralUsd − totalFeesUsd − maintenance) / (size × avgPrice)
20
+ * long: liq = avgPrice × (1 − ratio)
21
+ * short: liq = avgPrice × (1 + ratio)
22
+ *
23
+ * Returns 0 when the position is already liquidatable or has no size.
24
+ *
25
+ * @param totalFeesUsd Sum of all accrued fees in USD: borrow + trading + net funding.
26
+ */
27
+ export declare function calcEstLiqPrice(params: {
28
+ isLong: boolean;
29
+ avgPrice: number;
30
+ sizeInAsset: number;
31
+ collateralUsd: number;
32
+ maintenanceMarginRate: number;
33
+ spotPrice: number;
34
+ totalFeesUsd: number;
35
+ }): number;
36
+ /**
37
+ * Impact fee rate for an order (as a fraction, not bps).
38
+ *
39
+ * Matches `calculate_impact_fee` in `trading.move`. Returns 0 when the order
40
+ * reduces LP risk (new LP exposure ≤ original). Caller adds this to the base
41
+ * trading fee rate to get the total fee rate.
42
+ *
43
+ * @param longOi Current long open interest in base tokens.
44
+ * @param shortOi Current short open interest in base tokens.
45
+ * @param orderIsLong Direction of the order.
46
+ * @param orderSize Size of the order in base tokens.
47
+ * @param executionPrice Execution price (USD per base token).
48
+ * @param maxImpactFee Max impact fee rate (e.g. 0.0003).
49
+ * @param allocatedLpExposureBps Bps of pool TVL allocated as LP exposure cap.
50
+ * @param poolTvlUsd Total pool TVL in USD.
51
+ * @param curvature Impact fee curve curvature exponent (default 1).
52
+ * @param scale Impact fee curve scale (default 1).
53
+ */
54
+ export declare function calcImpactFeeRate(params: {
55
+ longOi: number;
56
+ shortOi: number;
57
+ orderIsLong: boolean;
58
+ orderSize: number;
59
+ executionPrice: number;
60
+ maxImpactFee: number;
61
+ allocatedLpExposureBps: number;
62
+ poolTvlUsd: number;
63
+ curvature?: number;
64
+ scale?: number;
65
+ }): number;
66
+ /** Total trading fee rate = base fee + impact fee. */
67
+ export declare function calcTotalTradingFeeRate(baseFeeRate: number, impactFeeRate: number): number;
68
+ /**
69
+ * Per-interval funding rate for a market.
70
+ *
71
+ * Matches `calculate_funding_rate` in `market_config.move`.
72
+ * OI values must be in USD (multiply raw OI by base price before calling).
73
+ *
74
+ * @returns `{ sign, rate }` where sign=true means longs pay shorts.
75
+ */
76
+ export declare function calcFundingRate(longOiUsd: number, shortOiUsd: number, basicRate: number, tvlUsd: number): {
77
+ sign: boolean;
78
+ rate: number;
79
+ };
80
+ /**
81
+ * Funding fee in USD for a position over a period.
82
+ *
83
+ * Simplified from `calculate_funding_fee` in `position.move` for off-chain estimation.
84
+ * For exact on-chain accounting use the Double-precision index from `position.move`.
85
+ *
86
+ * @param sizeInAsset Position size in base tokens.
87
+ * @param deltaIndexUsdPerAsset Change in cumulative funding index (USD per base token).
88
+ * @param positionIsLong Position direction.
89
+ * @param fundingSignIsLong True if the current funding interval charges longs.
90
+ */
91
+ export declare function calcFundingFeeUsd(sizeInAsset: number, deltaIndexUsdPerAsset: number, positionIsLong: boolean, fundingSignIsLong: boolean): number;
92
+ /**
93
+ * Decode raw Double-precision cumulative funding index delta into USD per base token.
94
+ *
95
+ * Raw index values from on-chain use Double scale (1e18). This converts them to
96
+ * human-readable form (USD per base token) so they can be passed to `calcFundingFeeUsd`.
97
+ */
98
+ export declare function decodeFundingIndexDelta(rawDelta: bigint): number;
99
+ /**
100
+ * Per-interval borrow rate using the 3-slope utilization curve.
101
+ *
102
+ * Matches `calculate_borrow_rate` in `lp_pool.move`.
103
+ * Rates are Float values (e.g. 0.000001 per interval).
104
+ */
105
+ export declare function calcBorrowRate(utilizationBps: number, rate0: number, rate1: number, rate2: number, threshold0Bps: number, threshold1Bps: number): number;
106
+ /**
107
+ * Time-weighted borrow rate accrual for a given elapsed period.
108
+ *
109
+ * Matches `calculate_borrow_rate_accrual` in `lp_pool.move`.
110
+ * `elapsedMs / intervalMs` gives the number of completed intervals.
111
+ */
112
+ export declare function calcBorrowRateAccrual(borrowRate: number, elapsedMs: number, intervalMs: number): number;
113
+ /**
114
+ * Unrealized borrow fee delta for a position (in raw collateral token units).
115
+ *
116
+ * Matches `calculate_borrow_fee` in `position.move`.
117
+ * Returns 0 when cumulative rate has not advanced past the entry index.
118
+ *
119
+ * @param borrowReserveAmount Position's borrow reserve in raw collateral units.
120
+ * @param cumulativeBorrowRate Current cumulative borrow rate (Float).
121
+ * @param entryBorrowIndex Cumulative borrow rate at position entry (Float).
122
+ */
123
+ export declare function calcPositionBorrowFee(borrowReserveAmount: number, cumulativeBorrowRate: number, entryBorrowIndex: number): number;
124
+ /** Token utilization in bps: reservedAmount / liquidityAmount × BPS_SCALE. */
125
+ export declare function calcTokenUtilizationBps(reservedAmount: number, liquidityAmount: number): number;
126
+ /**
127
+ * Annualize a per-interval funding rate.
128
+ *
129
+ * @param rate Per-interval funding rate (e.g. from `calcFundingRate`).
130
+ * @param intervalMs Funding interval in milliseconds (e.g. 3_600_000 for 1H).
131
+ */
132
+ export declare function annualizeFundingRate(rate: number, intervalMs: number): number;
133
+ /**
134
+ * Annualized APY from a NAV ratio over a given number of days.
135
+ *
136
+ * Compounds `ratio` (WLP price now / WLP price past) to a 365-day return.
137
+ * Returns 0 when the result is not finite (e.g. ratio ≤ 0 or days = 0).
138
+ *
139
+ * @param ratio Current NAV divided by past NAV (e.g. 1.05 for 5% growth).
140
+ * @param days Number of days elapsed between the two NAV samples.
141
+ */
142
+ export declare function annualizedApyFromRatio(ratio: number, days: number): number;
143
+ /**
144
+ * Convert a continuously-compounded incentive APR to APY.
145
+ *
146
+ * Rewards stream via `flow_rate` (continuous compounding), so APY = e^APR − 1.
147
+ * Returns 0 when the result is not finite.
148
+ *
149
+ * @param apr Time-weighted incentive APR as a decimal fraction (e.g. 0.12 for 12%).
150
+ */
151
+ export declare function calcWlpIncentiveApy(apr: number): number;
152
+ /**
153
+ * WLP share price in USD.
154
+ *
155
+ * @param tvlUsd Total pool TVL in USD (AUM equity).
156
+ * @param totalSupply Total WLP supply (in raw LP token units).
157
+ * @param lpDecimals WLP token decimals (6).
158
+ */
159
+ export declare function calcWlpPrice(tvlUsd: number, totalSupply: number, lpDecimals: number): number;
160
+ /**
161
+ * WLP tokens minted for a deposit (post-fee net deposit).
162
+ *
163
+ * Matches the LP-amount formula in `mint_wlp_with_pricing_tvl` in `lp_pool.move`.
164
+ * Pass `netDepositUsd` (after the dynamic mint fee is deducted).
165
+ * Bootstrap path (totalSupply === 0): lpAmount = netDepositUsd × 10^lpDecimals.
166
+ *
167
+ * @param netDepositUsd Deposit value in USD after dynamic mint fee.
168
+ * @param tvlUsd Pool TVL in USD at pricing time.
169
+ * @param totalSupply Current total WLP supply in raw units.
170
+ * @param lpDecimals WLP token decimals (6).
171
+ */
172
+ export declare function calcWlpMintOut(netDepositUsd: number, tvlUsd: number, totalSupply: number, lpDecimals: number): number;
173
+ /**
174
+ * Raw token amount redeemable for a given LP amount (before burn fee).
175
+ *
176
+ * Matches the settlement formula in `settle_redeem_with_pricing_tvl` in `lp_pool.move`.
177
+ * Apply `calcDynamicFeeBps` separately to get the net output.
178
+ *
179
+ * @param lpAmount LP tokens being redeemed (raw units).
180
+ * @param tvlUsd Pool TVL in USD at pricing time.
181
+ * @param totalSupply Current total WLP supply in raw units.
182
+ * @param tokenPriceUsd Oracle price of the output token.
183
+ * @param tokenDecimals Output token decimals.
184
+ */
185
+ export declare function calcWlpRedeemOut(lpAmount: number, tvlUsd: number, totalSupply: number, tokenPriceUsd: number, tokenDecimals: number): number;
186
+ /**
187
+ * Dynamic mint/burn fee in bps based on weight deviation.
188
+ *
189
+ * Matches `calculate_dynamic_fee` in `lp_pool.move`. Returns `baseFeeBps` when
190
+ * the operation moves the token closer to (or does not worsen) its target weight.
191
+ * Adds an additional fee proportional to the average deviation when it moves
192
+ * further away.
193
+ *
194
+ * @param tokenValueUsd Current USD value of this token in the pool.
195
+ * @param tvlUsd Total pool TVL in USD.
196
+ * @param operationValueUsd USD value of the deposit or withdrawal.
197
+ * @param targetWeightBps Target allocation weight for this token (bps).
198
+ * @param baseFeeBps Base mint/burn fee (bps).
199
+ * @param isDeposit True for mint, false for redeem.
200
+ */
201
+ export declare function calcDynamicFeeBps(tokenValueUsd: number, tvlUsd: number, operationValueUsd: number, targetWeightBps: number, baseFeeBps: number, isDeposit: boolean): number;
@@ -0,0 +1,343 @@
1
+ import { BPS_SCALE, DOUBLE_SCALE, FLOAT_SCALE, MS_PER_YEAR } from "../constants.js";
2
+ // ======== On-chain encoding ========
3
+ /**
4
+ * Convert a human-readable USD price to the raw 1e9-scaled `u128` value
5
+ * that on-chain `Float`-typed parameters expect.
6
+ */
7
+ export function rawPrice(usd) {
8
+ const n = typeof usd === "string" ? Number(usd) : usd;
9
+ if (!Number.isFinite(n))
10
+ throw new Error(`Invalid USD price: ${usd}`);
11
+ return BigInt(Math.round(n * Number(FLOAT_SCALE)));
12
+ }
13
+ // ======== Basic position math ========
14
+ /** Notional value in USD: sizeInAsset × price. */
15
+ export function calcNotional(sizeInAsset, price) {
16
+ return sizeInAsset * price;
17
+ }
18
+ /** Trading fee in USD: notional × feeRate. */
19
+ export function calcFee(sizeUsd, feeRate) {
20
+ return sizeUsd * feeRate;
21
+ }
22
+ /** Unrealized perp Pnl in USD (before fees). */
23
+ export function calcUnrealizedPnl(isLong, entryPrice, spotPrice, sizeInAsset) {
24
+ return (isLong ? 1 : -1) * sizeInAsset * (spotPrice - entryPrice);
25
+ }
26
+ /** Position leverage = notional / collateralUsd. Returns Infinity when collateral is zero. */
27
+ export function calcLeverage(sizeUsd, collateralUsd) {
28
+ if (collateralUsd === 0)
29
+ return Infinity;
30
+ return sizeUsd / collateralUsd;
31
+ }
32
+ /**
33
+ * Estimated liquidation price.
34
+ *
35
+ * Matches `calculate_est_liq_price` in `waterx_perp_view/sources/view.move`:
36
+ * maintenance = maintenanceMarginRate × (size × spotPrice) ← uses current notional
37
+ * ratio = (collateralUsd − totalFeesUsd − maintenance) / (size × avgPrice)
38
+ * long: liq = avgPrice × (1 − ratio)
39
+ * short: liq = avgPrice × (1 + ratio)
40
+ *
41
+ * Returns 0 when the position is already liquidatable or has no size.
42
+ *
43
+ * @param totalFeesUsd Sum of all accrued fees in USD: borrow + trading + net funding.
44
+ */
45
+ export function calcEstLiqPrice(params) {
46
+ const { isLong, avgPrice, sizeInAsset, collateralUsd, maintenanceMarginRate, spotPrice, totalFeesUsd, } = params;
47
+ if (sizeInAsset === 0)
48
+ return 0;
49
+ const entryNotional = sizeInAsset * avgPrice;
50
+ const maintenance = maintenanceMarginRate * sizeInAsset * spotPrice;
51
+ const marginRemaining = collateralUsd - totalFeesUsd - maintenance;
52
+ if (marginRemaining <= 0 || entryNotional === 0)
53
+ return 0;
54
+ const ratio = marginRemaining / entryNotional;
55
+ if (isLong) {
56
+ if (ratio >= 1)
57
+ return 0;
58
+ return avgPrice * (1 - ratio);
59
+ }
60
+ return avgPrice * (1 + ratio);
61
+ }
62
+ // ======== Impact fee ========
63
+ /**
64
+ * Cost integral used by the impact fee curve (internal helper).
65
+ * Matches `impact_fee_cost_usd` in `trading.move`.
66
+ */
67
+ function impactFeeCostUsd(maxImpactFee, allocatedExposureUsd, exposureUsd, curvature, scale) {
68
+ if (exposureUsd === 0)
69
+ return 0;
70
+ const scaledRatio = Math.min(1, exposureUsd / (allocatedExposureUsd * scale));
71
+ return exposureUsd * Math.pow(scaledRatio, curvature) * maxImpactFee;
72
+ }
73
+ /**
74
+ * Impact fee rate for an order (as a fraction, not bps).
75
+ *
76
+ * Matches `calculate_impact_fee` in `trading.move`. Returns 0 when the order
77
+ * reduces LP risk (new LP exposure ≤ original). Caller adds this to the base
78
+ * trading fee rate to get the total fee rate.
79
+ *
80
+ * @param longOi Current long open interest in base tokens.
81
+ * @param shortOi Current short open interest in base tokens.
82
+ * @param orderIsLong Direction of the order.
83
+ * @param orderSize Size of the order in base tokens.
84
+ * @param executionPrice Execution price (USD per base token).
85
+ * @param maxImpactFee Max impact fee rate (e.g. 0.0003).
86
+ * @param allocatedLpExposureBps Bps of pool TVL allocated as LP exposure cap.
87
+ * @param poolTvlUsd Total pool TVL in USD.
88
+ * @param curvature Impact fee curve curvature exponent (default 1).
89
+ * @param scale Impact fee curve scale (default 1).
90
+ */
91
+ export function calcImpactFeeRate(params) {
92
+ const { longOi, shortOi, orderIsLong, orderSize, executionPrice, maxImpactFee, allocatedLpExposureBps, poolTvlUsd, curvature = 1, scale = 1, } = params;
93
+ if (maxImpactFee === 0 || orderSize === 0)
94
+ return 0;
95
+ const lpOriginalSide = longOi > shortOi ? false : true;
96
+ const lpOriginalSize = Math.abs(longOi - shortOi);
97
+ const lpNewSize = lpOriginalSide === orderIsLong
98
+ ? lpOriginalSize > orderSize
99
+ ? lpOriginalSize - orderSize
100
+ : orderSize - lpOriginalSize
101
+ : lpOriginalSize + orderSize;
102
+ if (lpNewSize <= lpOriginalSize)
103
+ return 0;
104
+ if (allocatedLpExposureBps === 0 || poolTvlUsd === 0)
105
+ return 0;
106
+ const allocatedExposureUsd = (poolTvlUsd * allocatedLpExposureBps) / Number(BPS_SCALE);
107
+ if (allocatedExposureUsd === 0)
108
+ return 0;
109
+ const originalExposureUsd = lpOriginalSize * executionPrice;
110
+ const newExposureUsd = lpNewSize * executionPrice;
111
+ if (newExposureUsd <= originalExposureUsd)
112
+ return 0;
113
+ const orderNotionalUsd = orderSize * executionPrice;
114
+ if (orderNotionalUsd === 0)
115
+ return 0;
116
+ const originalCost = impactFeeCostUsd(maxImpactFee, allocatedExposureUsd, originalExposureUsd, curvature, scale);
117
+ const newCost = impactFeeCostUsd(maxImpactFee, allocatedExposureUsd, newExposureUsd, curvature, scale);
118
+ return (newCost - originalCost) / orderNotionalUsd;
119
+ }
120
+ /** Total trading fee rate = base fee + impact fee. */
121
+ export function calcTotalTradingFeeRate(baseFeeRate, impactFeeRate) {
122
+ return baseFeeRate + impactFeeRate;
123
+ }
124
+ // ======== Funding rate ========
125
+ /**
126
+ * Per-interval funding rate for a market.
127
+ *
128
+ * Matches `calculate_funding_rate` in `market_config.move`.
129
+ * OI values must be in USD (multiply raw OI by base price before calling).
130
+ *
131
+ * @returns `{ sign, rate }` where sign=true means longs pay shorts.
132
+ */
133
+ export function calcFundingRate(longOiUsd, shortOiUsd, basicRate, tvlUsd) {
134
+ if ((longOiUsd === 0 && shortOiUsd === 0) || tvlUsd === 0)
135
+ return { sign: true, rate: 0 };
136
+ if (longOiUsd >= shortOiUsd) {
137
+ return { sign: true, rate: (basicRate * (longOiUsd - shortOiUsd)) / tvlUsd };
138
+ }
139
+ return { sign: false, rate: (basicRate * (shortOiUsd - longOiUsd)) / tvlUsd };
140
+ }
141
+ /**
142
+ * Funding fee in USD for a position over a period.
143
+ *
144
+ * Simplified from `calculate_funding_fee` in `position.move` for off-chain estimation.
145
+ * For exact on-chain accounting use the Double-precision index from `position.move`.
146
+ *
147
+ * @param sizeInAsset Position size in base tokens.
148
+ * @param deltaIndexUsdPerAsset Change in cumulative funding index (USD per base token).
149
+ * @param positionIsLong Position direction.
150
+ * @param fundingSignIsLong True if the current funding interval charges longs.
151
+ */
152
+ export function calcFundingFeeUsd(sizeInAsset, deltaIndexUsdPerAsset, positionIsLong, fundingSignIsLong) {
153
+ const fee = sizeInAsset * Math.abs(deltaIndexUsdPerAsset);
154
+ const shouldPay = positionIsLong ? fundingSignIsLong : !fundingSignIsLong;
155
+ return shouldPay ? fee : -fee; // positive = cost to position, negative = receipt
156
+ }
157
+ /**
158
+ * Decode raw Double-precision cumulative funding index delta into USD per base token.
159
+ *
160
+ * Raw index values from on-chain use Double scale (1e18). This converts them to
161
+ * human-readable form (USD per base token) so they can be passed to `calcFundingFeeUsd`.
162
+ */
163
+ export function decodeFundingIndexDelta(rawDelta) {
164
+ return Number((rawDelta * FLOAT_SCALE) / DOUBLE_SCALE) / Number(FLOAT_SCALE);
165
+ }
166
+ // ======== Borrow rate ========
167
+ /**
168
+ * Per-interval borrow rate using the 3-slope utilization curve.
169
+ *
170
+ * Matches `calculate_borrow_rate` in `lp_pool.move`.
171
+ * Rates are Float values (e.g. 0.000001 per interval).
172
+ */
173
+ export function calcBorrowRate(utilizationBps, rate0, rate1, rate2, threshold0Bps, threshold1Bps) {
174
+ if (utilizationBps <= threshold0Bps)
175
+ return rate0;
176
+ if (utilizationBps <= threshold1Bps) {
177
+ if (threshold1Bps === threshold0Bps)
178
+ return rate1;
179
+ return (rate0 + ((rate1 - rate0) * (utilizationBps - threshold0Bps)) / (threshold1Bps - threshold0Bps));
180
+ }
181
+ const remaining = Number(BPS_SCALE) - threshold1Bps;
182
+ if (remaining === 0)
183
+ return rate2;
184
+ return rate1 + ((rate2 - rate1) * (utilizationBps - threshold1Bps)) / remaining;
185
+ }
186
+ /**
187
+ * Time-weighted borrow rate accrual for a given elapsed period.
188
+ *
189
+ * Matches `calculate_borrow_rate_accrual` in `lp_pool.move`.
190
+ * `elapsedMs / intervalMs` gives the number of completed intervals.
191
+ */
192
+ export function calcBorrowRateAccrual(borrowRate, elapsedMs, intervalMs) {
193
+ if (borrowRate === 0 || elapsedMs === 0 || intervalMs === 0)
194
+ return 0;
195
+ return (borrowRate * elapsedMs) / intervalMs;
196
+ }
197
+ /**
198
+ * Unrealized borrow fee delta for a position (in raw collateral token units).
199
+ *
200
+ * Matches `calculate_borrow_fee` in `position.move`.
201
+ * Returns 0 when cumulative rate has not advanced past the entry index.
202
+ *
203
+ * @param borrowReserveAmount Position's borrow reserve in raw collateral units.
204
+ * @param cumulativeBorrowRate Current cumulative borrow rate (Float).
205
+ * @param entryBorrowIndex Cumulative borrow rate at position entry (Float).
206
+ */
207
+ export function calcPositionBorrowFee(borrowReserveAmount, cumulativeBorrowRate, entryBorrowIndex) {
208
+ if (cumulativeBorrowRate <= entryBorrowIndex)
209
+ return 0;
210
+ return (cumulativeBorrowRate - entryBorrowIndex) * borrowReserveAmount;
211
+ }
212
+ /** Token utilization in bps: reservedAmount / liquidityAmount × BPS_SCALE. */
213
+ export function calcTokenUtilizationBps(reservedAmount, liquidityAmount) {
214
+ if (liquidityAmount === 0)
215
+ return 0;
216
+ return Math.floor((reservedAmount / liquidityAmount) * Number(BPS_SCALE));
217
+ }
218
+ // ======== Funding annualization ========
219
+ /**
220
+ * Annualize a per-interval funding rate.
221
+ *
222
+ * @param rate Per-interval funding rate (e.g. from `calcFundingRate`).
223
+ * @param intervalMs Funding interval in milliseconds (e.g. 3_600_000 for 1H).
224
+ */
225
+ export function annualizeFundingRate(rate, intervalMs) {
226
+ if (intervalMs === 0)
227
+ return 0;
228
+ return rate * (MS_PER_YEAR / intervalMs);
229
+ }
230
+ // ======== WLP APY ========
231
+ /**
232
+ * Annualized APY from a NAV ratio over a given number of days.
233
+ *
234
+ * Compounds `ratio` (WLP price now / WLP price past) to a 365-day return.
235
+ * Returns 0 when the result is not finite (e.g. ratio ≤ 0 or days = 0).
236
+ *
237
+ * @param ratio Current NAV divided by past NAV (e.g. 1.05 for 5% growth).
238
+ * @param days Number of days elapsed between the two NAV samples.
239
+ */
240
+ export function annualizedApyFromRatio(ratio, days) {
241
+ if (days === 0 || ratio <= 0)
242
+ return 0;
243
+ const apy = Math.pow(ratio, 365 / days) - 1;
244
+ return Number.isFinite(apy) ? apy : 0;
245
+ }
246
+ /**
247
+ * Convert a continuously-compounded incentive APR to APY.
248
+ *
249
+ * Rewards stream via `flow_rate` (continuous compounding), so APY = e^APR − 1.
250
+ * Returns 0 when the result is not finite.
251
+ *
252
+ * @param apr Time-weighted incentive APR as a decimal fraction (e.g. 0.12 for 12%).
253
+ */
254
+ export function calcWlpIncentiveApy(apr) {
255
+ const apy = Math.expm1(apr);
256
+ return Number.isFinite(apy) ? apy : 0;
257
+ }
258
+ // ======== WLP ========
259
+ /**
260
+ * WLP share price in USD.
261
+ *
262
+ * @param tvlUsd Total pool TVL in USD (AUM equity).
263
+ * @param totalSupply Total WLP supply (in raw LP token units).
264
+ * @param lpDecimals WLP token decimals (6).
265
+ */
266
+ export function calcWlpPrice(tvlUsd, totalSupply, lpDecimals) {
267
+ if (totalSupply === 0)
268
+ return 0;
269
+ return (tvlUsd * Math.pow(10, lpDecimals)) / totalSupply;
270
+ }
271
+ /**
272
+ * WLP tokens minted for a deposit (post-fee net deposit).
273
+ *
274
+ * Matches the LP-amount formula in `mint_wlp_with_pricing_tvl` in `lp_pool.move`.
275
+ * Pass `netDepositUsd` (after the dynamic mint fee is deducted).
276
+ * Bootstrap path (totalSupply === 0): lpAmount = netDepositUsd × 10^lpDecimals.
277
+ *
278
+ * @param netDepositUsd Deposit value in USD after dynamic mint fee.
279
+ * @param tvlUsd Pool TVL in USD at pricing time.
280
+ * @param totalSupply Current total WLP supply in raw units.
281
+ * @param lpDecimals WLP token decimals (6).
282
+ */
283
+ export function calcWlpMintOut(netDepositUsd, tvlUsd, totalSupply, lpDecimals) {
284
+ const scale = Math.pow(10, lpDecimals);
285
+ if (totalSupply === 0 || tvlUsd === 0)
286
+ return Math.floor(netDepositUsd * scale);
287
+ return Math.floor((netDepositUsd * totalSupply) / tvlUsd);
288
+ }
289
+ /**
290
+ * Raw token amount redeemable for a given LP amount (before burn fee).
291
+ *
292
+ * Matches the settlement formula in `settle_redeem_with_pricing_tvl` in `lp_pool.move`.
293
+ * Apply `calcDynamicFeeBps` separately to get the net output.
294
+ *
295
+ * @param lpAmount LP tokens being redeemed (raw units).
296
+ * @param tvlUsd Pool TVL in USD at pricing time.
297
+ * @param totalSupply Current total WLP supply in raw units.
298
+ * @param tokenPriceUsd Oracle price of the output token.
299
+ * @param tokenDecimals Output token decimals.
300
+ */
301
+ export function calcWlpRedeemOut(lpAmount, tvlUsd, totalSupply, tokenPriceUsd, tokenDecimals) {
302
+ if (totalSupply === 0 || tokenPriceUsd === 0)
303
+ return 0;
304
+ const burnValueUsd = (tvlUsd * lpAmount) / totalSupply;
305
+ return Math.floor((burnValueUsd / tokenPriceUsd) * Math.pow(10, tokenDecimals));
306
+ }
307
+ /**
308
+ * Dynamic mint/burn fee in bps based on weight deviation.
309
+ *
310
+ * Matches `calculate_dynamic_fee` in `lp_pool.move`. Returns `baseFeeBps` when
311
+ * the operation moves the token closer to (or does not worsen) its target weight.
312
+ * Adds an additional fee proportional to the average deviation when it moves
313
+ * further away.
314
+ *
315
+ * @param tokenValueUsd Current USD value of this token in the pool.
316
+ * @param tvlUsd Total pool TVL in USD.
317
+ * @param operationValueUsd USD value of the deposit or withdrawal.
318
+ * @param targetWeightBps Target allocation weight for this token (bps).
319
+ * @param baseFeeBps Base mint/burn fee (bps).
320
+ * @param isDeposit True for mint, false for redeem.
321
+ */
322
+ export function calcDynamicFeeBps(tokenValueUsd, tvlUsd, operationValueUsd, targetWeightBps, baseFeeBps, isDeposit) {
323
+ if (tvlUsd === 0 || operationValueUsd === 0 || targetWeightBps === 0)
324
+ return baseFeeBps;
325
+ const targetValue = (tvlUsd * targetWeightBps) / Number(BPS_SCALE);
326
+ const originalDiff = Math.abs(tokenValueUsd - targetValue);
327
+ const newTokenValue = isDeposit
328
+ ? tokenValueUsd + operationValueUsd
329
+ : Math.max(0, tokenValueUsd - operationValueUsd);
330
+ const newTvl = isDeposit ? tvlUsd + operationValueUsd : Math.max(0, tvlUsd - operationValueUsd);
331
+ if (newTvl === 0)
332
+ return baseFeeBps;
333
+ const newTargetValue = (newTvl * targetWeightBps) / Number(BPS_SCALE);
334
+ const newDiff = Math.abs(newTokenValue - newTargetValue);
335
+ if (newDiff <= originalDiff)
336
+ return baseFeeBps;
337
+ const avgDiff = (originalDiff + newDiff) / 2;
338
+ const avgTargetValue = (targetValue + newTargetValue) / 2;
339
+ if (avgTargetValue === 0)
340
+ return baseFeeBps;
341
+ const additional = Math.floor((avgDiff / avgTargetValue) * baseFeeBps);
342
+ return baseFeeBps + additional;
343
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Pyth price feed integration for the WaterX v3 oracle (ticker-based).
3
+ *
4
+ * Hermes REST fetches price update VAAs; on-chain a single PTB:
5
+ * 1. wormhole::vaa::parse_and_verify
6
+ * 2. pyth::create_authenticated_price_infos_using_accumulator
7
+ * 3. pyth::update_single_price_feed (one per feed)
8
+ * 4. for each ticker: oracle::new_collector(symbol) → pyth_rule::feed → oracle::aggregate
9
+ *
10
+ * No type parameters on `feed` / `aggregate` anymore — the oracle is one
11
+ * shared object keyed by ticker. `pyth_rule::feed` looks up the on-chain
12
+ * `PriceInfoObject` ID by ticker via the `pyth_rule::Config` identifier map.
13
+ */
14
+ import type { Transaction, TransactionArgument } from "@mysten/sui/transactions";
15
+ import type { WaterXClient } from "../client.ts";
16
+ type PriceTableInfo = {
17
+ id: string;
18
+ fieldType: string;
19
+ };
20
+ type PythStateInfo = {
21
+ packageId: string;
22
+ baseUpdateFee: bigint;
23
+ };
24
+ export declare class PythCache {
25
+ pythStateInfo?: PythStateInfo;
26
+ wormholePackageId?: string;
27
+ priceTableInfo?: PriceTableInfo;
28
+ priceFeedObjectIdCache: Map<string, string | undefined>;
29
+ }
30
+ export declare function fetchPriceFeedsUpdateData(endpoint: string, priceIds: string[]): Promise<Uint8Array[]>;
31
+ /**
32
+ * Append the on-chain Pyth update PTB block. Returns `PriceInfoObject` IDs
33
+ * (one per `feedIds`, same order). After this you can call
34
+ * `pyth_rule::feed` per ticker against the matching `PriceInfoObject`.
35
+ *
36
+ * If `sponsorFund` is provided, the per-feed update fee comes from the
37
+ * sponsor pool (`pyth_sponsor_rule::split`) instead of `tx.gas`.
38
+ */
39
+ export declare function buildPythPriceUpdateCalls(tx: Transaction, client: WaterXClient, updates: Uint8Array[], feedIds: string[], cache?: PythCache, sponsorFund?: {
40
+ fund: TransactionArgument;
41
+ packageId: string;
42
+ }): Promise<string[]>;
43
+ /** All-in-one: fetch from Hermes, append update calls. Returns PriceInfoObject IDs. */
44
+ export declare function updatePythPrices(tx: Transaction, client: WaterXClient, feedIds: string[], cache?: PythCache, sponsorFund?: {
45
+ fund: TransactionArgument;
46
+ packageId: string;
47
+ }): Promise<string[]>;
48
+ /**
49
+ * For a given ticker, build the collector → feed → aggregate chain that
50
+ * refreshes the on-chain `Oracle` aggregator for that ticker.
51
+ *
52
+ * Caller must have first called `buildPythPriceUpdateCalls` /
53
+ * `updatePythPrices` so the corresponding `PriceInfoObject` is fresh.
54
+ */
55
+ export declare function aggregateTickerWithPyth(tx: Transaction, client: WaterXClient, args: {
56
+ ticker: string;
57
+ priceInfoObjectId: string;
58
+ }): void;
59
+ /**
60
+ * Refresh multiple tickers via Pyth in one PTB. Updates Pyth on-chain
61
+ * first (one accumulator), then runs the collector → feed → aggregate
62
+ * cycle for each ticker.
63
+ */
64
+ export declare function refreshOraclePrices(tx: Transaction, client: WaterXClient, tickers: string[], opts?: {
65
+ cache?: PythCache;
66
+ sponsorFund?: {
67
+ fund: TransactionArgument;
68
+ packageId: string;
69
+ };
70
+ }): Promise<void>;
71
+ /**
72
+ * Opens a `Fund` hot potato from the shared PythSponsor pool. Pass the
73
+ * returned `{ fund, packageId }` straight to `refreshOraclePrices` as
74
+ * `sponsorFund`, then `reimbursePythSponsor` once the TradingRequest is
75
+ * built to attach the `PythSponsorRule` witness and return leftover
76
+ * balance.
77
+ */
78
+ export declare function openPythSponsorFund(tx: Transaction, client: WaterXClient): {
79
+ fund: TransactionArgument;
80
+ packageId: string;
81
+ };
82
+ /**
83
+ * Consumes the `Fund` hot potato from `openPythSponsorFund`, returns any
84
+ * leftover SUI to the sponsor pool, and attaches the `PythSponsorRule`
85
+ * witness to the given `TradingRequest<C_TOKEN>` so `trading::execute`
86
+ * can satisfy a checklist that includes `PythSponsorRule`.
87
+ */
88
+ export declare function reimbursePythSponsor(tx: Transaction, client: WaterXClient, fund: TransactionArgument, tradingRequest: TransactionArgument, collateralType: string): void;
89
+ export {};