@clober/v2-sdk 0.0.10 → 0.0.11-1.dev

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 (391) hide show
  1. package/README.md +12 -4
  2. package/dist/cjs/abis/core/book-manager-abi.js +112 -0
  3. package/dist/cjs/abis/core/book-manager-abi.js.map +1 -0
  4. package/dist/cjs/abis/core/book-viewer-abi.js +137 -5
  5. package/dist/cjs/abis/core/book-viewer-abi.js.map +1 -1
  6. package/dist/cjs/abis/core/controller-abi.js +1 -6
  7. package/dist/cjs/abis/core/controller-abi.js.map +1 -1
  8. package/dist/cjs/abis/governance/election-governor-abi.js +838 -0
  9. package/dist/cjs/abis/governance/election-governor-abi.js.map +1 -0
  10. package/dist/cjs/abis/governance/keepers-registry-abi.js +546 -0
  11. package/dist/cjs/abis/governance/keepers-registry-abi.js.map +1 -0
  12. package/dist/cjs/abis/governance/vclob-abi.js +743 -0
  13. package/dist/cjs/abis/governance/vclob-abi.js.map +1 -0
  14. package/dist/cjs/abis/rebalancer/minter-abi.js +262 -0
  15. package/dist/cjs/abis/rebalancer/minter-abi.js.map +1 -0
  16. package/dist/cjs/abis/rebalancer/mock-swap-abi.js +95 -0
  17. package/dist/cjs/abis/rebalancer/mock-swap-abi.js.map +1 -0
  18. package/dist/cjs/abis/rebalancer/operator-abi.js +401 -0
  19. package/dist/cjs/abis/rebalancer/operator-abi.js.map +1 -0
  20. package/dist/cjs/abis/rebalancer/rebalancer-abi.js +1326 -0
  21. package/dist/cjs/abis/rebalancer/rebalancer-abi.js.map +1 -0
  22. package/dist/cjs/abis/rebalancer/strategy-abi.js +895 -0
  23. package/dist/cjs/abis/rebalancer/strategy-abi.js.map +1 -0
  24. package/dist/cjs/apis/chart-logs.js +30 -13
  25. package/dist/cjs/apis/chart-logs.js.map +1 -1
  26. package/dist/cjs/apis/market.js +45 -22
  27. package/dist/cjs/apis/market.js.map +1 -1
  28. package/dist/cjs/apis/odos.js +100 -0
  29. package/dist/cjs/apis/odos.js.map +1 -0
  30. package/dist/cjs/apis/open-order.js +76 -39
  31. package/dist/cjs/apis/open-order.js.map +1 -1
  32. package/dist/cjs/apis/pool.js +96 -0
  33. package/dist/cjs/apis/pool.js.map +1 -0
  34. package/dist/cjs/apis/strategy.js +53 -0
  35. package/dist/cjs/apis/strategy.js.map +1 -0
  36. package/dist/cjs/apis/vclob.js +47 -0
  37. package/dist/cjs/apis/vclob.js.map +1 -0
  38. package/dist/cjs/approval.js +83 -26
  39. package/dist/cjs/approval.js.map +1 -1
  40. package/dist/cjs/call.js +787 -125
  41. package/dist/cjs/call.js.map +1 -1
  42. package/dist/cjs/constants/addresses.js +104 -1
  43. package/dist/cjs/constants/addresses.js.map +1 -1
  44. package/dist/cjs/constants/bera-bartio-chain.js +30 -0
  45. package/dist/cjs/constants/bera-bartio-chain.js.map +1 -0
  46. package/dist/cjs/constants/chain.js +29 -2
  47. package/dist/cjs/constants/chain.js.map +1 -1
  48. package/dist/cjs/constants/currency.js +99 -3
  49. package/dist/cjs/constants/currency.js.map +1 -1
  50. package/dist/cjs/constants/fee.js +23 -2
  51. package/dist/cjs/constants/fee.js.map +1 -1
  52. package/dist/cjs/constants/mitosis-testnet-chain.js +30 -0
  53. package/dist/cjs/constants/mitosis-testnet-chain.js.map +1 -0
  54. package/dist/cjs/constants/monad-testnet-chain.js +40 -0
  55. package/dist/cjs/constants/monad-testnet-chain.js.map +1 -0
  56. package/dist/cjs/constants/permit.js +14 -0
  57. package/dist/cjs/constants/permit.js.map +1 -0
  58. package/dist/cjs/constants/price.js +2 -1
  59. package/dist/cjs/constants/price.js.map +1 -1
  60. package/dist/cjs/constants/sonic-mainnet-chain.js +30 -0
  61. package/dist/cjs/constants/sonic-mainnet-chain.js.map +1 -0
  62. package/dist/cjs/constants/subgraph.js +38 -0
  63. package/dist/cjs/constants/subgraph.js.map +1 -0
  64. package/dist/cjs/constants/test-chain.js +50 -0
  65. package/dist/cjs/constants/test-chain.js.map +1 -0
  66. package/dist/cjs/constants/tick.js +6 -0
  67. package/dist/cjs/constants/tick.js.map +1 -0
  68. package/dist/cjs/index.js +1 -1
  69. package/dist/cjs/index.js.map +1 -1
  70. package/dist/cjs/model/book.js +62 -35
  71. package/dist/cjs/model/book.js.map +1 -1
  72. package/dist/cjs/model/market.js +61 -26
  73. package/dist/cjs/model/market.js.map +1 -1
  74. package/dist/cjs/model/pool.js +240 -0
  75. package/dist/cjs/model/pool.js.map +1 -0
  76. package/dist/cjs/model/vclob.js +3 -0
  77. package/dist/cjs/model/vclob.js.map +1 -0
  78. package/dist/cjs/type.js +8 -1
  79. package/dist/cjs/type.js.map +1 -1
  80. package/dist/cjs/utils/allowance.js +39 -0
  81. package/dist/cjs/utils/allowance.js.map +1 -0
  82. package/dist/cjs/utils/approval.js +2 -3
  83. package/dist/cjs/utils/approval.js.map +1 -1
  84. package/dist/cjs/utils/bigint.js +5 -1
  85. package/dist/cjs/utils/bigint.js.map +1 -1
  86. package/dist/cjs/utils/book-id.js +7 -7
  87. package/dist/cjs/utils/book-id.js.map +1 -1
  88. package/dist/cjs/utils/build-transaction.js +3 -4
  89. package/dist/cjs/utils/build-transaction.js.map +1 -1
  90. package/dist/cjs/utils/currency.js +61 -27
  91. package/dist/cjs/utils/currency.js.map +1 -1
  92. package/dist/cjs/utils/market.js +1 -1
  93. package/dist/cjs/utils/market.js.map +1 -1
  94. package/dist/cjs/utils/math.js +3 -1
  95. package/dist/cjs/utils/math.js.map +1 -1
  96. package/dist/cjs/utils/open.js +35 -25
  97. package/dist/cjs/utils/open.js.map +1 -1
  98. package/dist/cjs/utils/order.js +68 -126
  99. package/dist/cjs/utils/order.js.map +1 -1
  100. package/dist/cjs/utils/pool-key.js +17 -0
  101. package/dist/cjs/utils/pool-key.js.map +1 -0
  102. package/dist/cjs/utils/pool.js +88 -0
  103. package/dist/cjs/utils/pool.js.map +1 -0
  104. package/dist/cjs/utils/prices.js +40 -5
  105. package/dist/cjs/utils/prices.js.map +1 -1
  106. package/dist/cjs/utils/tick.js +12 -1
  107. package/dist/cjs/utils/tick.js.map +1 -1
  108. package/dist/cjs/utils/time-series.js +31 -0
  109. package/dist/cjs/utils/time-series.js.map +1 -0
  110. package/dist/cjs/utils/unit-size.js +48 -0
  111. package/dist/cjs/utils/unit-size.js.map +1 -0
  112. package/dist/cjs/utils.js +18 -0
  113. package/dist/cjs/utils.js.map +1 -0
  114. package/dist/cjs/view.js +459 -44
  115. package/dist/cjs/view.js.map +1 -1
  116. package/dist/esm/abis/core/book-manager-abi.js +109 -0
  117. package/dist/esm/abis/core/book-manager-abi.js.map +1 -0
  118. package/dist/esm/abis/core/book-viewer-abi.js +137 -5
  119. package/dist/esm/abis/core/book-viewer-abi.js.map +1 -1
  120. package/dist/esm/abis/core/controller-abi.js +1 -6
  121. package/dist/esm/abis/core/controller-abi.js.map +1 -1
  122. package/dist/esm/abis/governance/election-governor-abi.js +835 -0
  123. package/dist/esm/abis/governance/election-governor-abi.js.map +1 -0
  124. package/dist/esm/abis/governance/keepers-registry-abi.js +543 -0
  125. package/dist/esm/abis/governance/keepers-registry-abi.js.map +1 -0
  126. package/dist/esm/abis/governance/vclob-abi.js +740 -0
  127. package/dist/esm/abis/governance/vclob-abi.js.map +1 -0
  128. package/dist/esm/abis/rebalancer/minter-abi.js +259 -0
  129. package/dist/esm/abis/rebalancer/minter-abi.js.map +1 -0
  130. package/dist/esm/abis/rebalancer/mock-swap-abi.js +92 -0
  131. package/dist/esm/abis/rebalancer/mock-swap-abi.js.map +1 -0
  132. package/dist/esm/abis/rebalancer/operator-abi.js +398 -0
  133. package/dist/esm/abis/rebalancer/operator-abi.js.map +1 -0
  134. package/dist/esm/abis/rebalancer/rebalancer-abi.js +1323 -0
  135. package/dist/esm/abis/rebalancer/rebalancer-abi.js.map +1 -0
  136. package/dist/esm/abis/rebalancer/strategy-abi.js +892 -0
  137. package/dist/esm/abis/rebalancer/strategy-abi.js.map +1 -0
  138. package/dist/esm/apis/chart-logs.js +29 -12
  139. package/dist/esm/apis/chart-logs.js.map +1 -1
  140. package/dist/esm/apis/market.js +47 -24
  141. package/dist/esm/apis/market.js.map +1 -1
  142. package/dist/esm/apis/odos.js +94 -0
  143. package/dist/esm/apis/odos.js.map +1 -0
  144. package/dist/esm/apis/open-order.js +78 -40
  145. package/dist/esm/apis/open-order.js.map +1 -1
  146. package/dist/esm/apis/pool.js +91 -0
  147. package/dist/esm/apis/pool.js.map +1 -0
  148. package/dist/esm/apis/strategy.js +48 -0
  149. package/dist/esm/apis/strategy.js.map +1 -0
  150. package/dist/esm/apis/vclob.js +43 -0
  151. package/dist/esm/apis/vclob.js.map +1 -0
  152. package/dist/esm/approval.js +107 -25
  153. package/dist/esm/approval.js.map +1 -1
  154. package/dist/esm/call.js +818 -166
  155. package/dist/esm/call.js.map +1 -1
  156. package/dist/esm/constants/addresses.js +105 -2
  157. package/dist/esm/constants/addresses.js.map +1 -1
  158. package/dist/esm/constants/bera-bartio-chain.js +27 -0
  159. package/dist/esm/constants/bera-bartio-chain.js.map +1 -0
  160. package/dist/esm/constants/chain.js +28 -2
  161. package/dist/esm/constants/chain.js.map +1 -1
  162. package/dist/esm/constants/currency.js +100 -2
  163. package/dist/esm/constants/currency.js.map +1 -1
  164. package/dist/esm/constants/fee.js +23 -2
  165. package/dist/esm/constants/fee.js.map +1 -1
  166. package/dist/esm/constants/mitosis-testnet-chain.js +27 -0
  167. package/dist/esm/constants/mitosis-testnet-chain.js.map +1 -0
  168. package/dist/esm/constants/monad-testnet-chain.js +37 -0
  169. package/dist/esm/constants/monad-testnet-chain.js.map +1 -0
  170. package/dist/esm/constants/permit.js +11 -0
  171. package/dist/esm/constants/permit.js.map +1 -0
  172. package/dist/esm/constants/price.js +1 -0
  173. package/dist/esm/constants/price.js.map +1 -1
  174. package/dist/esm/constants/sonic-mainnet-chain.js +27 -0
  175. package/dist/esm/constants/sonic-mainnet-chain.js.map +1 -0
  176. package/dist/esm/constants/subgraph.js +34 -0
  177. package/dist/esm/constants/subgraph.js.map +1 -0
  178. package/dist/esm/constants/test-chain.js +47 -0
  179. package/dist/esm/constants/test-chain.js.map +1 -0
  180. package/dist/esm/constants/tick.js +3 -0
  181. package/dist/esm/constants/tick.js.map +1 -0
  182. package/dist/esm/index.js +1 -1
  183. package/dist/esm/index.js.map +1 -1
  184. package/dist/esm/model/book.js +62 -35
  185. package/dist/esm/model/book.js.map +1 -1
  186. package/dist/esm/model/market.js +63 -28
  187. package/dist/esm/model/market.js.map +1 -1
  188. package/dist/esm/model/pool.js +237 -0
  189. package/dist/esm/model/pool.js.map +1 -0
  190. package/dist/esm/model/vclob.js +2 -0
  191. package/dist/esm/model/vclob.js.map +1 -0
  192. package/dist/esm/type.js +7 -0
  193. package/dist/esm/type.js.map +1 -1
  194. package/dist/esm/utils/allowance.js +35 -0
  195. package/dist/esm/utils/allowance.js.map +1 -0
  196. package/dist/esm/utils/approval.js +2 -3
  197. package/dist/esm/utils/approval.js.map +1 -1
  198. package/dist/esm/utils/bigint.js +2 -0
  199. package/dist/esm/utils/bigint.js.map +1 -1
  200. package/dist/esm/utils/book-id.js +7 -7
  201. package/dist/esm/utils/book-id.js.map +1 -1
  202. package/dist/esm/utils/build-transaction.js +3 -4
  203. package/dist/esm/utils/build-transaction.js.map +1 -1
  204. package/dist/esm/utils/currency.js +59 -25
  205. package/dist/esm/utils/currency.js.map +1 -1
  206. package/dist/esm/utils/market.js +1 -1
  207. package/dist/esm/utils/market.js.map +1 -1
  208. package/dist/esm/utils/math.js +1 -0
  209. package/dist/esm/utils/math.js.map +1 -1
  210. package/dist/esm/utils/open.js +33 -23
  211. package/dist/esm/utils/open.js.map +1 -1
  212. package/dist/esm/utils/order.js +67 -125
  213. package/dist/esm/utils/order.js.map +1 -1
  214. package/dist/esm/utils/pool-key.js +12 -0
  215. package/dist/esm/utils/pool-key.js.map +1 -0
  216. package/dist/esm/utils/pool.js +84 -0
  217. package/dist/esm/utils/pool.js.map +1 -0
  218. package/dist/esm/utils/prices.js +39 -5
  219. package/dist/esm/utils/prices.js.map +1 -1
  220. package/dist/esm/utils/tick.js +11 -1
  221. package/dist/esm/utils/tick.js.map +1 -1
  222. package/dist/esm/utils/time-series.js +27 -0
  223. package/dist/esm/utils/time-series.js.map +1 -0
  224. package/dist/esm/utils/unit-size.js +44 -0
  225. package/dist/esm/utils/unit-size.js.map +1 -0
  226. package/dist/esm/utils.js +5 -0
  227. package/dist/esm/utils.js.map +1 -0
  228. package/dist/esm/view.js +516 -61
  229. package/dist/esm/view.js.map +1 -1
  230. package/dist/tsconfig.build.tsbuildinfo +1 -1
  231. package/dist/types/abis/core/book-manager-abi.d.ts +82 -0
  232. package/dist/types/abis/core/book-manager-abi.d.ts.map +1 -0
  233. package/dist/types/abis/core/book-viewer-abi.d.ts +107 -5
  234. package/dist/types/abis/core/book-viewer-abi.d.ts.map +1 -1
  235. package/dist/types/abis/core/controller-abi.d.ts +1 -5
  236. package/dist/types/abis/core/controller-abi.d.ts.map +1 -1
  237. package/dist/types/abis/governance/election-governor-abi.d.ts +648 -0
  238. package/dist/types/abis/governance/election-governor-abi.d.ts.map +1 -0
  239. package/dist/types/abis/governance/keepers-registry-abi.d.ts +417 -0
  240. package/dist/types/abis/governance/keepers-registry-abi.d.ts.map +1 -0
  241. package/dist/types/abis/governance/vclob-abi.d.ts +568 -0
  242. package/dist/types/abis/governance/vclob-abi.d.ts.map +1 -0
  243. package/dist/types/abis/rebalancer/minter-abi.d.ts +198 -0
  244. package/dist/types/abis/rebalancer/minter-abi.d.ts.map +1 -0
  245. package/dist/types/abis/rebalancer/mock-swap-abi.d.ts +70 -0
  246. package/dist/types/abis/rebalancer/mock-swap-abi.d.ts.map +1 -0
  247. package/dist/types/abis/rebalancer/operator-abi.d.ts +308 -0
  248. package/dist/types/abis/rebalancer/operator-abi.d.ts.map +1 -0
  249. package/dist/types/abis/rebalancer/rebalancer-abi.d.ts +1023 -0
  250. package/dist/types/abis/rebalancer/rebalancer-abi.d.ts.map +1 -0
  251. package/dist/types/abis/rebalancer/strategy-abi.d.ts +690 -0
  252. package/dist/types/abis/rebalancer/strategy-abi.d.ts.map +1 -0
  253. package/dist/types/apis/chart-logs.d.ts +3 -0
  254. package/dist/types/apis/chart-logs.d.ts.map +1 -1
  255. package/dist/types/apis/market.d.ts +2 -1
  256. package/dist/types/apis/market.d.ts.map +1 -1
  257. package/dist/types/apis/odos.d.ts +28 -0
  258. package/dist/types/apis/odos.d.ts.map +1 -0
  259. package/dist/types/apis/open-order.d.ts +4 -2
  260. package/dist/types/apis/open-order.d.ts.map +1 -1
  261. package/dist/types/apis/pool.d.ts +11 -0
  262. package/dist/types/apis/pool.d.ts.map +1 -0
  263. package/dist/types/apis/strategy.d.ts +6 -0
  264. package/dist/types/apis/strategy.d.ts.map +1 -0
  265. package/dist/types/apis/vclob.d.ts +5 -0
  266. package/dist/types/apis/vclob.d.ts.map +1 -0
  267. package/dist/types/approval.d.ts +37 -3
  268. package/dist/types/approval.d.ts.map +1 -1
  269. package/dist/types/call.d.ts +275 -59
  270. package/dist/types/call.d.ts.map +1 -1
  271. package/dist/types/constants/addresses.d.ts +7 -0
  272. package/dist/types/constants/addresses.d.ts.map +1 -1
  273. package/dist/types/constants/bera-bartio-chain.d.ts +33 -0
  274. package/dist/types/constants/bera-bartio-chain.d.ts.map +1 -0
  275. package/dist/types/constants/chain.d.ts +10 -2
  276. package/dist/types/constants/chain.d.ts.map +1 -1
  277. package/dist/types/constants/currency.d.ts +9 -0
  278. package/dist/types/constants/currency.d.ts.map +1 -1
  279. package/dist/types/constants/fee.d.ts +7 -2
  280. package/dist/types/constants/fee.d.ts.map +1 -1
  281. package/dist/types/constants/mitosis-testnet-chain.d.ts +33 -0
  282. package/dist/types/constants/mitosis-testnet-chain.d.ts.map +1 -0
  283. package/dist/types/constants/monad-testnet-chain.d.ts +37 -0
  284. package/dist/types/constants/monad-testnet-chain.d.ts.map +1 -0
  285. package/dist/types/constants/permit.d.ts +10 -0
  286. package/dist/types/constants/permit.d.ts.map +1 -0
  287. package/dist/types/constants/price.d.ts +1 -0
  288. package/dist/types/constants/price.d.ts.map +1 -1
  289. package/dist/types/constants/sonic-mainnet-chain.d.ts +33 -0
  290. package/dist/types/constants/sonic-mainnet-chain.d.ts.map +1 -0
  291. package/dist/types/constants/subgraph.d.ts +5 -0
  292. package/dist/types/constants/subgraph.d.ts.map +1 -0
  293. package/dist/types/constants/test-chain.d.ts +4 -0
  294. package/dist/types/constants/test-chain.d.ts.map +1 -0
  295. package/dist/types/constants/tick.d.ts +3 -0
  296. package/dist/types/constants/tick.d.ts.map +1 -0
  297. package/dist/types/index.d.ts +1 -1
  298. package/dist/types/index.d.ts.map +1 -1
  299. package/dist/types/model/book.d.ts +25 -33
  300. package/dist/types/model/book.d.ts.map +1 -1
  301. package/dist/types/model/currency.d.ts +7 -0
  302. package/dist/types/model/currency.d.ts.map +1 -1
  303. package/dist/types/model/depth.d.ts +4 -3
  304. package/dist/types/model/depth.d.ts.map +1 -1
  305. package/dist/types/model/market.d.ts +24 -13
  306. package/dist/types/model/market.d.ts.map +1 -1
  307. package/dist/types/model/open-order.d.ts +20 -27
  308. package/dist/types/model/open-order.d.ts.map +1 -1
  309. package/dist/types/model/pool.d.ts +77 -0
  310. package/dist/types/model/pool.d.ts.map +1 -0
  311. package/dist/types/model/vclob.d.ts +7 -0
  312. package/dist/types/model/vclob.d.ts.map +1 -0
  313. package/dist/types/type.d.ts +141 -6
  314. package/dist/types/type.d.ts.map +1 -1
  315. package/dist/types/utils/allowance.d.ts +3 -0
  316. package/dist/types/utils/allowance.d.ts.map +1 -0
  317. package/dist/types/utils/approval.d.ts +2 -1
  318. package/dist/types/utils/approval.d.ts.map +1 -1
  319. package/dist/types/utils/bigint.d.ts +2 -0
  320. package/dist/types/utils/bigint.d.ts.map +1 -1
  321. package/dist/types/utils/book-id.d.ts +2 -1
  322. package/dist/types/utils/book-id.d.ts.map +1 -1
  323. package/dist/types/utils/build-transaction.d.ts +3 -3
  324. package/dist/types/utils/build-transaction.d.ts.map +1 -1
  325. package/dist/types/utils/currency.d.ts +3 -2
  326. package/dist/types/utils/currency.d.ts.map +1 -1
  327. package/dist/types/utils/math.d.ts +1 -0
  328. package/dist/types/utils/math.d.ts.map +1 -1
  329. package/dist/types/utils/open.d.ts +2 -1
  330. package/dist/types/utils/open.d.ts.map +1 -1
  331. package/dist/types/utils/order.d.ts +4 -11
  332. package/dist/types/utils/order.d.ts.map +1 -1
  333. package/dist/types/utils/pool-key.d.ts +3 -0
  334. package/dist/types/utils/pool-key.d.ts.map +1 -0
  335. package/dist/types/utils/pool.d.ts +11 -0
  336. package/dist/types/utils/pool.d.ts.map +1 -0
  337. package/dist/types/utils/prices.d.ts +13 -2
  338. package/dist/types/utils/prices.d.ts.map +1 -1
  339. package/dist/types/utils/tick.d.ts +1 -0
  340. package/dist/types/utils/tick.d.ts.map +1 -1
  341. package/dist/types/utils/time-series.d.ts +4 -0
  342. package/dist/types/utils/time-series.d.ts.map +1 -0
  343. package/dist/types/utils/unit-size.d.ts +5 -0
  344. package/dist/types/utils/unit-size.d.ts.map +1 -0
  345. package/dist/types/utils.d.ts +5 -0
  346. package/dist/types/utils.d.ts.map +1 -0
  347. package/dist/types/view.d.ts +247 -30
  348. package/dist/types/view.d.ts.map +1 -1
  349. package/package.json +3 -2
  350. package/dist/cjs/abis/core/params-abi.js +0 -62
  351. package/dist/cjs/abis/core/params-abi.js.map +0 -1
  352. package/dist/cjs/apis/subgraph.js +0 -26
  353. package/dist/cjs/apis/subgraph.js.map +0 -1
  354. package/dist/cjs/constants/client.js +0 -14
  355. package/dist/cjs/constants/client.js.map +0 -1
  356. package/dist/cjs/constants/subgraph-url.js +0 -8
  357. package/dist/cjs/constants/subgraph-url.js.map +0 -1
  358. package/dist/cjs/signature.js +0 -146
  359. package/dist/cjs/signature.js.map +0 -1
  360. package/dist/cjs/utils/decorator.js +0 -13
  361. package/dist/cjs/utils/decorator.js.map +0 -1
  362. package/dist/cjs/utils/unit.js +0 -34
  363. package/dist/cjs/utils/unit.js.map +0 -1
  364. package/dist/esm/abis/core/params-abi.js +0 -59
  365. package/dist/esm/abis/core/params-abi.js.map +0 -1
  366. package/dist/esm/apis/subgraph.js +0 -22
  367. package/dist/esm/apis/subgraph.js.map +0 -1
  368. package/dist/esm/constants/client.js +0 -10
  369. package/dist/esm/constants/client.js.map +0 -1
  370. package/dist/esm/constants/subgraph-url.js +0 -5
  371. package/dist/esm/constants/subgraph-url.js.map +0 -1
  372. package/dist/esm/signature.js +0 -170
  373. package/dist/esm/signature.js.map +0 -1
  374. package/dist/esm/utils/decorator.js +0 -9
  375. package/dist/esm/utils/decorator.js.map +0 -1
  376. package/dist/esm/utils/unit.js +0 -30
  377. package/dist/esm/utils/unit.js.map +0 -1
  378. package/dist/types/abis/core/params-abi.d.ts +0 -21
  379. package/dist/types/abis/core/params-abi.d.ts.map +0 -1
  380. package/dist/types/apis/subgraph.d.ts +0 -3
  381. package/dist/types/apis/subgraph.d.ts.map +0 -1
  382. package/dist/types/constants/client.d.ts +0 -5
  383. package/dist/types/constants/client.d.ts.map +0 -1
  384. package/dist/types/constants/subgraph-url.d.ts +0 -5
  385. package/dist/types/constants/subgraph-url.d.ts.map +0 -1
  386. package/dist/types/signature.d.ts +0 -38
  387. package/dist/types/signature.d.ts.map +0 -1
  388. package/dist/types/utils/decorator.d.ts +0 -6
  389. package/dist/types/utils/decorator.d.ts.map +0 -1
  390. package/dist/types/utils/unit.d.ts +0 -4
  391. package/dist/types/utils/unit.d.ts.map +0 -1
package/dist/esm/call.js CHANGED
@@ -1,46 +1,64 @@
1
- import { formatUnits, isAddressEqual, parseUnits, zeroAddress, zeroHash, } from 'viem';
1
+ import { createPublicClient, formatUnits, getAddress, http, isAddressEqual, parseUnits, zeroAddress, zeroHash, } from 'viem';
2
2
  import { CHAIN_MAP } from './constants/chain';
3
- import { calculateUnit } from './utils/unit';
3
+ import { calculateUnitSize } from './utils/unit-size';
4
4
  import { CONTROLLER_ABI } from './abis/core/controller-abi';
5
5
  import { getDeadlineTimestampInSeconds } from './utils/time';
6
6
  import { buildTransaction } from './utils/build-transaction';
7
7
  import { CONTRACT_ADDRESSES } from './constants/addresses';
8
8
  import { MAKER_DEFAULT_POLICY, TAKER_DEFAULT_POLICY } from './constants/fee';
9
9
  import { fetchMarket } from './apis/market';
10
- import { parsePrice } from './utils/prices';
11
- import { fromPrice, invertPrice } from './utils/tick';
12
- import { getExpectedInput, getExpectedOutput } from './view';
10
+ import { convertHumanReadablePriceToRawPrice, formatPrice, parsePrice, } from './utils/prices';
11
+ import { invertTick, toPrice } from './utils/tick';
12
+ import { getExpectedInput, getExpectedOutput, getQuoteToken } from './view';
13
13
  import { toBookId } from './utils/book-id';
14
14
  import { fetchIsApprovedForAll } from './utils/approval';
15
- import { decorator } from './utils/decorator';
16
- import { fetchOrders } from './utils/order';
17
- import { quoteToBase } from './utils/decimals';
15
+ import { fetchOnChainOrders } from './utils/order';
18
16
  import { applyPercent } from './utils/bigint';
17
+ import { fetchPool } from './apis/pool';
18
+ import { REBALANCER_ABI } from './abis/rebalancer/rebalancer-abi';
19
+ import { getExpectedMintResult, getIdealDelta } from './utils/pool';
20
+ import { fetchCallData, fetchQuote } from './apis/odos';
21
+ import { MINTER_ABI } from './abis/rebalancer/minter-abi';
22
+ import { emptyERC20PermitParams } from './constants/permit';
23
+ import { abs } from './utils/math';
24
+ import { toBytes32 } from './utils/pool-key';
25
+ import { OPERATOR_ABI } from './abis/rebalancer/operator-abi';
26
+ import { STRATEGY_ABI } from './abis/rebalancer/strategy-abi';
27
+ import { ELECTION_GOVERNOR_ABI } from './abis/governance/election-governor-abi';
28
+ import { VCLOB_ABI } from './abis/governance/vclob-abi';
19
29
  /**
20
30
  * Build a transaction to open a market.
21
31
  *
22
32
  * @param chainId The chain ID of the blockchain.
33
+ * @param userAddress The address of the user.
23
34
  * @param inputToken The address of the input token.
24
35
  * @param outputToken The address of the output token.
25
- * @param options
26
- * @param options.rpcUrl The RPC URL of the blockchain.
36
+ * @param options {@link DefaultWriteContractOptions} options.
27
37
  * @returns A Promise resolving to a transaction object. If the market is already open, returns undefined.
28
38
  * @example
29
39
  * import { openMarket } from '@clober/v2-sdk'
30
40
  *
31
41
  * const transaction = await openMarket({
32
42
  * chainId: 421614,
43
+ * userAddress: '0xF8c1869Ecd4df136693C45EcE1b67f85B6bDaE69',
33
44
  * inputToken: '0x00bfd44e79fb7f6dd5887a9426c8ef85a0cd23e0',
34
45
  * outputToken: '0x0000000000000000000000000000000000000000'
35
46
  * })
36
47
  */
37
- export const openMarket = decorator(async ({ chainId, inputToken, outputToken, options, }) => {
38
- const market = await fetchMarket(chainId, [inputToken, outputToken]);
48
+ export const openMarket = async ({ chainId, userAddress, inputToken, outputToken, options, }) => {
49
+ const publicClient = createPublicClient({
50
+ chain: CHAIN_MAP[chainId],
51
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
52
+ });
53
+ const market = await fetchMarket(publicClient, chainId, [inputToken, outputToken], !!(options && options.useSubgraph));
39
54
  const isBid = isAddressEqual(market.quote.address, inputToken);
40
- if ((isBid && !market.bidBookOpen) || (!isBid && !market.askBookOpen)) {
41
- const unit = await calculateUnit(chainId, isBid ? market.quote : market.base);
42
- return buildTransaction(chainId, {
55
+ if ((isBid && !market.bidBook.isOpened) ||
56
+ (!isBid && !market.askBook.isOpened)) {
57
+ const unitSize = await calculateUnitSize(publicClient, chainId, isBid ? market.quote : market.base);
58
+ return buildTransaction(publicClient, {
59
+ chain: CHAIN_MAP[chainId],
43
60
  address: CONTRACT_ADDRESSES[chainId].Controller,
61
+ account: userAddress,
44
62
  abi: CONTROLLER_ABI,
45
63
  functionName: 'open',
46
64
  args: [
@@ -48,11 +66,11 @@ export const openMarket = decorator(async ({ chainId, inputToken, outputToken, o
48
66
  {
49
67
  key: {
50
68
  base: outputToken,
51
- unit,
69
+ unitSize,
52
70
  quote: inputToken,
53
- makerPolicy: MAKER_DEFAULT_POLICY.value,
71
+ makerPolicy: MAKER_DEFAULT_POLICY[chainId].value,
54
72
  hooks: zeroAddress,
55
- takerPolicy: TAKER_DEFAULT_POLICY.value,
73
+ takerPolicy: TAKER_DEFAULT_POLICY[chainId].value,
56
74
  },
57
75
  hookData: zeroHash,
58
76
  },
@@ -62,7 +80,7 @@ export const openMarket = decorator(async ({ chainId, inputToken, outputToken, o
62
80
  }, options?.gasLimit);
63
81
  }
64
82
  return undefined;
65
- });
83
+ };
66
84
  /**
67
85
  * Places a limit order on the specified chain for trading tokens.
68
86
  *
@@ -72,23 +90,21 @@ export const openMarket = decorator(async ({ chainId, inputToken, outputToken, o
72
90
  * @param {`0x${string}`} outputToken The address of the token to be received as output.
73
91
  * @param {string} amount The amount of input tokens for the order.
74
92
  * @param {string} price The price at which the order should be executed.
75
- * @param {Object} [options] Optional parameters for the limit order.
76
- * @param {PermitSignature} [options.signature] The permit signature for token approval.
93
+ * @param options {@link DefaultWriteContractOptions} options.
94
+ * @param {erc20PermitParam} [options.erc20PermitParam] The permit signature for token approval.
77
95
  * @param {boolean} [options.postOnly] A boolean indicating whether the order is only to be made not taken.
78
- * @param {string} [options.rpcUrl] The RPC URL of the blockchain.
79
- * @returns {Promise<{ transaction: Transaction, result: { make: CurrencyFlow, take: CurrencyFlow } }>}
96
+ * @param {bigint} [options.makeTick] The tick for the make order.
97
+ * @param {bigint} [options.takeLimitTick] The tick for the take order.
98
+ * @param {boolean} [options.roundingUpMakeBid] A boolean indicating whether to round up the make bid.
99
+ * @param {boolean} [options.roundingDownMakeAsk] A boolean indicating whether to round down the make ask.
100
+ * @param {boolean} [options.roundingDownTakenBid] A boolean indicating whether to round down the taken bid.
101
+ * @param {boolean} [options.roundingUpTakenAsk] A boolean indicating whether to round up the taken ask.
102
+ * @returns {Promise<{ transaction: Transaction, result: { make: CurrencyFlow, take: CurrencyFlow, spent: CurrencyFlow }>}
80
103
  * Promise resolving to the transaction object representing the limit order with the result of the order.
81
104
  * @example
82
- * import { signERC20Permit, limitOrder } from '@clober/v2-sdk'
105
+ * import { limitOrder } from '@clober/v2-sdk'
83
106
  * import { privateKeyToAccount } from 'viem/accounts'
84
107
  *
85
- * const signature = await signERC20Permit({
86
- * chainId: 421614,
87
- * walletClient,
88
- * token: '0x00bfd44e79fb7f6dd5887a9426c8ef85a0cd23e0',
89
- * amount: '100.123'
90
- * })
91
- *
92
108
  * const { transaction } = await limitOrder({
93
109
  * chainId: 421614,
94
110
  * userAddress: '0xF8c1869Ecd4df136693C45EcE1b67f85B6bDaE69
@@ -96,7 +112,6 @@ export const openMarket = decorator(async ({ chainId, inputToken, outputToken, o
96
112
  * outputToken: '0x0000000000000000000000000000000000000000',
97
113
  * amount: '100.123', // 100.123 USDC
98
114
  * price: '4000.01', // price at 4000.01 (ETH/USDC)
99
- * options: { signature }
100
115
  * })
101
116
  *
102
117
  * @example
@@ -111,13 +126,24 @@ export const openMarket = decorator(async ({ chainId, inputToken, outputToken, o
111
126
  * price: '4000.01', // price at 4000.01 (ETH/USDC)
112
127
  * })
113
128
  */
114
- export const limitOrder = decorator(async ({ chainId, userAddress, inputToken, outputToken, amount, price, options, }) => {
115
- const market = await fetchMarket(chainId, [inputToken, outputToken]);
129
+ export const limitOrder = async ({ chainId, userAddress, inputToken, outputToken, amount, price, options, }) => {
130
+ const [roundingUpMakeBid, roundingDownMakeAsk, roundingDownTakenBid, roundingUpTakenAsk,] = [
131
+ options?.roundingUpMakeBid ? options.roundingUpMakeBid : false,
132
+ options?.roundingDownMakeAsk ? options.roundingDownMakeAsk : false,
133
+ options?.roundingDownTakenBid ? options.roundingDownTakenBid : false,
134
+ options?.roundingUpTakenAsk ? options.roundingUpTakenAsk : false,
135
+ ];
136
+ const publicClient = createPublicClient({
137
+ chain: CHAIN_MAP[chainId],
138
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
139
+ });
140
+ const market = await fetchMarket(publicClient, chainId, [inputToken, outputToken], !!(options && options.useSubgraph));
116
141
  const isBid = isAddressEqual(market.quote.address, inputToken);
117
142
  const [inputCurrency, outputCurrency] = isBid
118
143
  ? [market.quote, market.base]
119
144
  : [market.base, market.quote];
120
- if ((isBid && !market.bidBookOpen) || (!isBid && !market.askBookOpen)) {
145
+ if ((isBid && !market.bidBook.isOpened) ||
146
+ (!isBid && !market.askBook.isOpened)) {
121
147
  throw new Error(`
122
148
  Open the market before placing a limit order.
123
149
  import { openMarket } from '@clober/v2-sdk'
@@ -129,12 +155,11 @@ export const limitOrder = decorator(async ({ chainId, userAddress, inputToken, o
129
155
  })
130
156
  `);
131
157
  }
132
- const rawPrice = parsePrice(Number(price), market.quote.decimals, market.base.decimals);
133
- const tick = isBid ? fromPrice(rawPrice) : fromPrice(invertPrice(rawPrice));
158
+ const { roundingDownTick, roundingUpTick } = parsePrice(Number(price), market.quote.decimals, market.base.decimals);
134
159
  const tokensToSettle = [inputToken, outputToken].filter((address) => !isAddressEqual(address, zeroAddress));
135
160
  const quoteAmount = parseUnits(amount, inputCurrency.decimals);
136
- const [unit, { spendAmount, bookId }] = await Promise.all([
137
- calculateUnit(chainId, inputCurrency),
161
+ const [unitSize, { takenAmount, spentAmount, bookId, events }] = await Promise.all([
162
+ calculateUnitSize(publicClient, chainId, inputCurrency),
138
163
  getExpectedOutput({
139
164
  chainId,
140
165
  inputToken,
@@ -147,24 +172,21 @@ export const limitOrder = decorator(async ({ chainId, userAddress, inputToken, o
147
172
  }),
148
173
  ]);
149
174
  const isETH = isAddressEqual(inputToken, zeroAddress);
150
- const permitParamsList = options?.signature && !isETH
151
- ? [
152
- {
153
- token: inputToken,
154
- permitAmount: quoteAmount,
155
- signature: options.signature,
156
- },
157
- ]
158
- : [];
159
175
  const makeParam = {
160
- id: toBookId(inputToken, outputToken, unit),
161
- tick: Number(tick),
176
+ id: toBookId(chainId, inputToken, outputToken, unitSize),
177
+ tick: options?.makeTick
178
+ ? Number(options.makeTick)
179
+ : Number(isBid
180
+ ? roundingUpMakeBid
181
+ ? roundingUpTick
182
+ : roundingDownTick
183
+ : invertTick(roundingDownMakeAsk ? roundingDownTick : roundingUpTick)),
162
184
  quoteAmount,
163
185
  hookData: zeroHash,
164
186
  };
165
- if (options?.postOnly === true || spendAmount === '0') {
187
+ if (options?.postOnly === true || spentAmount === '0') {
166
188
  return {
167
- transaction: await buildTransaction(chainId, {
189
+ transaction: await buildTransaction(publicClient, {
168
190
  chain: CHAIN_MAP[chainId],
169
191
  account: userAddress,
170
192
  address: CONTRACT_ADDRESSES[chainId].Controller,
@@ -173,7 +195,7 @@ export const limitOrder = decorator(async ({ chainId, userAddress, inputToken, o
173
195
  args: [
174
196
  [makeParam],
175
197
  tokensToSettle,
176
- permitParamsList,
198
+ options?.erc20PermitParam ? [options.erc20PermitParam] : [],
177
199
  getDeadlineTimestampInSeconds(),
178
200
  ],
179
201
  value: isETH ? quoteAmount : 0n,
@@ -183,11 +205,21 @@ export const limitOrder = decorator(async ({ chainId, userAddress, inputToken, o
183
205
  amount: formatUnits(quoteAmount, inputCurrency.decimals),
184
206
  currency: inputCurrency,
185
207
  direction: 'in',
208
+ price: formatPrice(isBid
209
+ ? toPrice(BigInt(makeParam.tick))
210
+ : toPrice(invertTick(BigInt(makeParam.tick))), market.quote.decimals, market.base.decimals),
211
+ },
212
+ spent: {
213
+ amount: '0',
214
+ currency: inputCurrency,
215
+ direction: 'in',
216
+ events: [],
186
217
  },
187
- take: {
218
+ taken: {
188
219
  amount: '0',
189
220
  currency: outputCurrency,
190
221
  direction: 'out',
222
+ events: [],
191
223
  },
192
224
  },
193
225
  };
@@ -195,7 +227,7 @@ export const limitOrder = decorator(async ({ chainId, userAddress, inputToken, o
195
227
  else {
196
228
  // take and make
197
229
  return {
198
- transaction: await buildTransaction(chainId, {
230
+ transaction: await buildTransaction(publicClient, {
199
231
  chain: CHAIN_MAP[chainId],
200
232
  account: userAddress,
201
233
  address: CONTRACT_ADDRESSES[chainId].Controller,
@@ -206,7 +238,15 @@ export const limitOrder = decorator(async ({ chainId, userAddress, inputToken, o
206
238
  {
207
239
  takeBookId: bookId,
208
240
  makeBookId: makeParam.id,
209
- limitPrice: isBid ? invertPrice(rawPrice) : rawPrice,
241
+ limitPrice: options?.takeLimitTick
242
+ ? toPrice(options.takeLimitTick)
243
+ : toPrice(isBid
244
+ ? invertTick(roundingUpTakenAsk
245
+ ? roundingUpTick
246
+ : roundingDownTick)
247
+ : roundingDownTakenBid
248
+ ? roundingDownTick
249
+ : roundingUpTick),
210
250
  tick: makeParam.tick,
211
251
  quoteAmount,
212
252
  takeHookData: zeroHash,
@@ -214,30 +254,46 @@ export const limitOrder = decorator(async ({ chainId, userAddress, inputToken, o
214
254
  },
215
255
  ],
216
256
  tokensToSettle,
217
- permitParamsList,
257
+ options?.erc20PermitParam ? [options.erc20PermitParam] : [],
218
258
  getDeadlineTimestampInSeconds(),
219
259
  ],
220
260
  value: isETH ? quoteAmount : 0n,
221
261
  }, options?.gasLimit),
222
262
  result: {
223
263
  make: {
224
- amount: formatUnits(quoteAmount, inputCurrency.decimals),
264
+ amount: formatUnits(quoteAmount - parseUnits(spentAmount, inputCurrency.decimals), inputCurrency.decimals),
225
265
  currency: inputCurrency,
226
266
  direction: 'in',
267
+ price: formatPrice(isBid
268
+ ? toPrice(BigInt(makeParam.tick))
269
+ : toPrice(invertTick(BigInt(makeParam.tick))), market.quote.decimals, market.base.decimals),
227
270
  },
228
- take: {
229
- amount: spendAmount,
271
+ spent: {
272
+ amount: spentAmount,
273
+ currency: inputCurrency,
274
+ direction: 'in',
275
+ events: events.map(({ price, spentAmount }) => ({
276
+ price,
277
+ amount: spentAmount,
278
+ })),
279
+ },
280
+ taken: {
281
+ amount: takenAmount,
230
282
  currency: outputCurrency,
231
283
  direction: 'out',
284
+ events: events.map(({ price, takenAmount }) => ({
285
+ price,
286
+ amount: takenAmount,
287
+ })),
232
288
  },
233
289
  },
234
290
  };
235
291
  }
236
- });
292
+ };
237
293
  /**
238
294
  * Executes a market order on the specified chain for trading tokens.
239
295
  * If only `amountIn` is provided, spend the specified amount of input tokens.
240
- * If `amountIn` and `amountOut` are provided, take the appropriate amount of output tokens with the specified input amount.
296
+ * If only `amountOut` is provided, take the specified amount of output tokens.
241
297
  *
242
298
  * @param {CHAIN_IDS} chainId The chain ID.
243
299
  * @param {`0x${string}`} userAddress The Ethereum address of the user placing the order.
@@ -245,42 +301,46 @@ export const limitOrder = decorator(async ({ chainId, userAddress, inputToken, o
245
301
  * @param {`0x${string}`} outputToken The address of the token to be received as output.
246
302
  * @param {string} amountIn The amount of input tokens for the order to spend.
247
303
  * @param {string} amountOut The amount of output tokens for the order to take.
248
- * @param {Object} [options] Optional parameters for the market order.
249
- * @param {PermitSignature} [options.signature] The permit signature for token approval.
250
- * @param {string} [options.rpcUrl] The RPC URL of the blockchain.
304
+ * @param options {@link DefaultWriteContractOptions} options.
305
+ * @param {erc20PermitParam} [options.erc20PermitParam] The permit signature for token approval.
251
306
  * @param {number} [options.slippage] The maximum slippage percentage allowed for the order.
307
+ * @param {boolean} [options.roundingDownTakenBid] A boolean indicating whether to round down the taken bid.
308
+ * @param {boolean} [options.roundingUpTakenAsk] A boolean indicating whether to round up the taken ask.
252
309
  * if the slippage is not provided, unlimited slippage is allowed.
253
- * @returns {Promise<{ transaction: Transaction, result: { spend: CurrencyFlow, take: CurrencyFlow } }>}
310
+ * @returns {Promise<{ transaction: Transaction, result: { spent: CurrencyFlow, taken: CurrencyFlow } }>}
254
311
  * Promise resolving to the transaction object representing the market order with the result of the order.
255
312
  * @example
256
- * import { signERC20Permit, marketOrder } from '@clober/v2-sdk'
313
+ * import { marketOrder } from '@clober/v2-sdk'
257
314
  * import { privateKeyToAccount } from 'viem/accounts'
258
315
  *
259
- * const signature = await signERC20Permit({
260
- * chainId: 421614,
261
- * walletClient,
262
- * token: '0x00bfd44e79fb7f6dd5887a9426c8ef85a0cd23e0',
263
- * amount: '100.123'
264
- * })
265
- *
266
316
  * const transaction = await marketOrder({
267
317
  * chainId: 421614,
268
318
  * userAddress: '0xF8c1869Ecd4df136693C45EcE1b67f85B6bDaE69
269
319
  * inputToken: '0x00bfd44e79fb7f6dd5887a9426c8ef85a0cd23e0',
270
320
  * outputToken: '0x0000000000000000000000000000000000000000',
271
321
  * amount: '100.123', // 100.123 USDC
272
- * options: { signature }
322
+ * options: { erc20PermitParam }
273
323
  * })
274
324
  *
275
325
  */
276
- export const marketOrder = decorator(async ({ chainId, userAddress, inputToken, outputToken, amountIn, amountOut, options, }) => {
277
- const market = await fetchMarket(chainId, [inputToken, outputToken]);
326
+ export const marketOrder = async ({ chainId, userAddress, inputToken, outputToken, amountIn, amountOut, options, }) => {
327
+ if (!amountIn && !amountOut) {
328
+ throw new Error('Either amountIn or amountOut must be provided');
329
+ }
330
+ else if (amountIn && amountOut) {
331
+ throw new Error('Only one of amountIn or amountOut can be provided');
332
+ }
333
+ const publicClient = createPublicClient({
334
+ chain: CHAIN_MAP[chainId],
335
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
336
+ });
337
+ const market = await fetchMarket(publicClient, chainId, [inputToken, outputToken], !!(options && options.useSubgraph));
278
338
  const isTakingBid = isAddressEqual(market.base.address, inputToken);
279
339
  const [inputCurrency, outputCurrency] = isTakingBid
280
340
  ? [market.base, market.quote]
281
341
  : [market.quote, market.base];
282
- if ((isTakingBid && !market.bidBookOpen) ||
283
- (!isTakingBid && !market.askBookOpen)) {
342
+ if ((isTakingBid && !market.bidBook.isOpened) ||
343
+ (!isTakingBid && !market.askBook.isOpened)) {
284
344
  throw new Error(`
285
345
  Open the market before placing a market order.
286
346
  import { openMarket } from '@clober/v2-sdk'
@@ -295,7 +355,7 @@ export const marketOrder = decorator(async ({ chainId, userAddress, inputToken,
295
355
  const tokensToSettle = [inputToken, outputToken].filter((address) => !isAddressEqual(address, zeroAddress));
296
356
  const isETH = isAddressEqual(inputToken, zeroAddress);
297
357
  if (amountIn && !amountOut) {
298
- const { bookId, takenAmount, spendAmount } = await getExpectedOutput({
358
+ const { bookId, takenAmount, spentAmount, events } = await getExpectedOutput({
299
359
  chainId,
300
360
  inputToken,
301
361
  outputToken,
@@ -307,7 +367,7 @@ export const marketOrder = decorator(async ({ chainId, userAddress, inputToken,
307
367
  });
308
368
  const baseAmount = parseUnits(amountIn, inputCurrency.decimals);
309
369
  return {
310
- transaction: await buildTransaction(chainId, {
370
+ transaction: await buildTransaction(publicClient, {
311
371
  chain: CHAIN_MAP[chainId],
312
372
  account: userAddress,
313
373
  address: CONTRACT_ADDRESSES[chainId].Controller,
@@ -326,35 +386,35 @@ export const marketOrder = decorator(async ({ chainId, userAddress, inputToken,
326
386
  },
327
387
  ],
328
388
  tokensToSettle,
329
- options?.signature && !isETH
330
- ? [
331
- {
332
- token: inputToken,
333
- permitAmount: baseAmount,
334
- signature: options.signature,
335
- },
336
- ]
337
- : [],
389
+ options?.erc20PermitParam ? [options.erc20PermitParam] : [],
338
390
  getDeadlineTimestampInSeconds(),
339
391
  ],
340
392
  value: isETH ? baseAmount : 0n,
341
393
  }, options?.gasLimit),
342
394
  result: {
343
- spend: {
344
- amount: spendAmount,
395
+ spent: {
396
+ amount: spentAmount,
345
397
  currency: inputCurrency,
346
398
  direction: 'in',
399
+ events: events.map(({ price, spentAmount }) => ({
400
+ price,
401
+ amount: spentAmount,
402
+ })),
347
403
  },
348
- take: {
404
+ taken: {
349
405
  amount: takenAmount,
350
406
  currency: outputCurrency,
351
407
  direction: 'out',
408
+ events: events.map(({ price, takenAmount }) => ({
409
+ price,
410
+ amount: takenAmount,
411
+ })),
352
412
  },
353
413
  },
354
414
  };
355
415
  }
356
- else if (amountIn && amountOut) {
357
- const { bookId, spendAmount, takenAmount } = await getExpectedInput({
416
+ else if (!amountIn && amountOut) {
417
+ const { bookId, spentAmount, takenAmount, events } = await getExpectedInput({
358
418
  chainId,
359
419
  inputToken,
360
420
  outputToken,
@@ -365,9 +425,15 @@ export const marketOrder = decorator(async ({ chainId, userAddress, inputToken,
365
425
  },
366
426
  });
367
427
  const quoteAmount = parseUnits(amountOut, outputCurrency.decimals);
368
- const baseAmount = parseUnits(amountIn ?? spendAmount, inputCurrency.decimals);
428
+ const baseAmount = parseUnits(spentAmount, inputCurrency.decimals);
429
+ const maxBaseAmount = options?.erc20PermitParam?.permitAmount ??
430
+ (options?.slippage
431
+ ? applyPercent(baseAmount, 100 + options.slippage)
432
+ : isETH
433
+ ? baseAmount
434
+ : 2n ** 256n - 1n);
369
435
  return {
370
- transaction: await buildTransaction(chainId, {
436
+ transaction: await buildTransaction(publicClient, {
371
437
  chain: CHAIN_MAP[chainId],
372
438
  account: userAddress,
373
439
  address: CONTRACT_ADDRESSES[chainId].Controller,
@@ -379,36 +445,34 @@ export const marketOrder = decorator(async ({ chainId, userAddress, inputToken,
379
445
  id: bookId,
380
446
  limitPrice: 0n,
381
447
  quoteAmount,
382
- maxBaseAmount: options?.slippage
383
- ? applyPercent(baseAmount, 100 + options.slippage)
384
- : 2n ** 256n - 1n,
448
+ maxBaseAmount,
385
449
  hookData: zeroHash,
386
450
  },
387
451
  ],
388
452
  tokensToSettle,
389
- options?.signature && !isETH
390
- ? [
391
- {
392
- token: inputToken,
393
- permitAmount: baseAmount,
394
- signature: options.signature,
395
- },
396
- ]
397
- : [],
453
+ options?.erc20PermitParam ? [options.erc20PermitParam] : [],
398
454
  getDeadlineTimestampInSeconds(),
399
455
  ],
400
- value: isETH ? baseAmount : 0n,
456
+ value: isETH ? maxBaseAmount : 0n,
401
457
  }, options?.gasLimit),
402
458
  result: {
403
- spend: {
404
- amount: spendAmount,
459
+ spent: {
460
+ amount: spentAmount,
405
461
  currency: inputCurrency,
406
462
  direction: 'in',
463
+ events: events.map(({ price, spentAmount }) => ({
464
+ price,
465
+ amount: spentAmount,
466
+ })),
407
467
  },
408
- take: {
468
+ taken: {
409
469
  amount: takenAmount,
410
470
  currency: outputCurrency,
411
471
  direction: 'out',
472
+ events: events.map(({ price, takenAmount }) => ({
473
+ price,
474
+ amount: takenAmount,
475
+ })),
412
476
  },
413
477
  },
414
478
  };
@@ -416,7 +480,7 @@ export const marketOrder = decorator(async ({ chainId, userAddress, inputToken,
416
480
  else {
417
481
  throw new Error('Either amountIn or amountOut must be provided');
418
482
  }
419
- });
483
+ };
420
484
  /**
421
485
  * Claims specified open order for settlement.
422
486
  * [IMPORTANT] Set ApprovalForAll before calling this function.
@@ -424,8 +488,7 @@ export const marketOrder = decorator(async ({ chainId, userAddress, inputToken,
424
488
  * @param {CHAIN_IDS} chainId The chain ID.
425
489
  * @param {`0x${string}`} userAddress The Ethereum address of the user.
426
490
  * @param {string} id An ID representing the open order to be claimed.
427
- * @param {Object} [options] Optional parameters for claiming orders.
428
- * @param {string} [options.rpcUrl] The RPC URL to use for executing the transaction.
491
+ * @param options {@link DefaultWriteContractOptions} options.
429
492
  * @returns {Promise<{ transaction: Transaction, result: CurrencyFlow }>}
430
493
  * Promise resolving to the transaction object representing the claim action with the result of the order.
431
494
  * @throws {Error} Throws an error if no open orders are found for the specified user.
@@ -442,7 +505,7 @@ export const marketOrder = decorator(async ({ chainId, userAddress, inputToken,
442
505
  * id: openOrders.map((order) => order.id)
443
506
  * })
444
507
  */
445
- export const claimOrder = decorator(async ({ chainId, userAddress, id, options, }) => {
508
+ export const claimOrder = async ({ chainId, userAddress, id, options, }) => {
446
509
  const { transaction, result } = await claimOrders({
447
510
  chainId,
448
511
  userAddress,
@@ -453,7 +516,7 @@ export const claimOrder = decorator(async ({ chainId, userAddress, id, options,
453
516
  transaction,
454
517
  result: result[0],
455
518
  };
456
- });
519
+ };
457
520
  /**
458
521
  * Claims specified open orders for settlement.
459
522
  * [IMPORTANT] Set ApprovalForAll before calling this function.
@@ -461,8 +524,7 @@ export const claimOrder = decorator(async ({ chainId, userAddress, id, options,
461
524
  * @param {CHAIN_IDS} chainId The chain ID.
462
525
  * @param {`0x${string}`} userAddress The Ethereum address of the user.
463
526
  * @param {string[]} ids An array of IDs representing the open orders to be claimed.
464
- * @param {Object} [options] Optional parameters for claiming orders.
465
- * @param {string} [options.rpcUrl] The RPC URL to use for executing the transaction.
527
+ * @param options {@link DefaultWriteContractOptions} options.
466
528
  * @returns {Promise<{ transaction: Transaction, result: CurrencyFlow[] }>}
467
529
  * Promise resolving to the transaction object representing the claim action with the result of the orders.
468
530
  * @throws {Error} Throws an error if no open orders are found for the specified user.
@@ -479,8 +541,12 @@ export const claimOrder = decorator(async ({ chainId, userAddress, id, options,
479
541
  * ids: openOrders.map((order) => order.id)
480
542
  * )
481
543
  */
482
- export const claimOrders = decorator(async ({ chainId, userAddress, ids, options, }) => {
483
- const isApprovedForAll = await fetchIsApprovedForAll(chainId, userAddress);
544
+ export const claimOrders = async ({ chainId, userAddress, ids, options, }) => {
545
+ const publicClient = createPublicClient({
546
+ chain: CHAIN_MAP[chainId],
547
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
548
+ });
549
+ const isApprovedForAll = await fetchIsApprovedForAll(publicClient, chainId, userAddress);
484
550
  if (!isApprovedForAll) {
485
551
  throw new Error(`
486
552
  Set ApprovalForAll before calling this function.
@@ -492,22 +558,22 @@ export const claimOrders = decorator(async ({ chainId, userAddress, ids, options
492
558
  })
493
559
  `);
494
560
  }
495
- const orders = (await fetchOrders(chainId, ids.map((id) => BigInt(id)))).filter((order) => isAddressEqual(order.owner, userAddress) && order.claimable > 0n);
561
+ const orders = (await fetchOnChainOrders(publicClient, chainId, ids.map((id) => BigInt(id)), !!(options && options.useSubgraph))).filter((order) => isAddressEqual(order.user, userAddress) && order.claimable.value !== '0');
496
562
  const tokensToSettle = orders
497
- .map((order) => [order.baseCurrency.address, order.quoteCurrency.address])
563
+ .map((order) => [order.inputCurrency.address, order.outputCurrency.address])
498
564
  .flat()
499
565
  .filter((address, index, self) => self.findIndex((c) => isAddressEqual(c, address)) === index)
500
566
  .filter((address) => !isAddressEqual(address, zeroAddress));
501
567
  return {
502
- transaction: await buildTransaction(chainId, {
568
+ transaction: await buildTransaction(publicClient, {
503
569
  chain: CHAIN_MAP[chainId],
504
570
  account: userAddress,
505
571
  address: CONTRACT_ADDRESSES[chainId].Controller,
506
572
  abi: CONTROLLER_ABI,
507
573
  functionName: 'claim',
508
574
  args: [
509
- orders.map(({ orderId }) => ({
510
- id: orderId,
575
+ orders.map(({ id }) => ({
576
+ id,
511
577
  hookData: zeroHash,
512
578
  })),
513
579
  tokensToSettle,
@@ -515,24 +581,16 @@ export const claimOrders = decorator(async ({ chainId, userAddress, ids, options
515
581
  getDeadlineTimestampInSeconds(),
516
582
  ],
517
583
  }, options?.gasLimit),
518
- result: orders
519
- .map((order) => {
520
- const amount = quoteToBase(order.tick, order.unit * order.claimable, false);
521
- return {
522
- currency: order.baseCurrency,
523
- amount: formatUnits(amount, order.baseCurrency.decimals),
524
- };
525
- })
526
- .reduce((acc, { currency, amount }) => {
584
+ result: orders.reduce((acc, { claimable: { currency, value } }) => {
527
585
  const index = acc.findIndex((c) => isAddressEqual(c.currency.address, currency.address));
528
586
  if (index === -1) {
529
- return [...acc, { currency, amount, direction: 'out' }];
587
+ return [...acc, { currency, amount: value, direction: 'out' }];
530
588
  }
531
- acc[index].amount = (Number(acc[index].amount) + Number(amount)).toString();
589
+ acc[index].amount = (Number(acc[index].amount) + Number(value)).toString();
532
590
  return acc;
533
591
  }, []),
534
592
  };
535
- });
593
+ };
536
594
  /**
537
595
  * Cancels specified open order if the order is not fully filled.
538
596
  * [IMPORTANT] Set ApprovalForAll before calling this function.
@@ -540,8 +598,7 @@ export const claimOrders = decorator(async ({ chainId, userAddress, ids, options
540
598
  * @param {CHAIN_IDS} chainId The chain ID.
541
599
  * @param {`0x${string}`} userAddress The Ethereum address of the user.
542
600
  * @param {string} id An ID representing the open order to be canceled
543
- * @param {Object} [options] Optional parameters for canceling orders.
544
- * @param {string} [options.rpcUrl] The RPC URL to use for executing the transaction.
601
+ * @param options {@link DefaultWriteContractOptions} options.
545
602
  * @returns {Promise<{ transaction: Transaction, result: CurrencyFlow }>}
546
603
  * Promise resolving to the transaction object representing the cancel action with the result of the order.
547
604
  * @throws {Error} Throws an error if no open orders are found for the specified user.
@@ -558,7 +615,7 @@ export const claimOrders = decorator(async ({ chainId, userAddress, ids, options
558
615
  * id: openOrders.map((order) => order.id)
559
616
  * })
560
617
  */
561
- export const cancelOrder = decorator(async ({ chainId, userAddress, id, options, }) => {
618
+ export const cancelOrder = async ({ chainId, userAddress, id, options, }) => {
562
619
  const { transaction, result } = await cancelOrders({
563
620
  chainId,
564
621
  userAddress,
@@ -569,7 +626,7 @@ export const cancelOrder = decorator(async ({ chainId, userAddress, id, options,
569
626
  transaction,
570
627
  result: result[0],
571
628
  };
572
- });
629
+ };
573
630
  /**
574
631
  * Cancels specified open orders if orders are not fully filled.
575
632
  * [IMPORTANT] Set ApprovalForAll before calling this function.
@@ -577,8 +634,7 @@ export const cancelOrder = decorator(async ({ chainId, userAddress, id, options,
577
634
  * @param {CHAIN_IDS} chainId The chain ID.
578
635
  * @param {`0x${string}`} userAddress The Ethereum address of the user.
579
636
  * @param {string[]} ids An array of IDs representing the open orders to be canceled.
580
- * @param {Object} [options] Optional parameters for canceling orders.
581
- * @param {string} [options.rpcUrl] The RPC URL to use for executing the transaction.
637
+ * @param options {@link DefaultWriteContractOptions} options.
582
638
  * @returns {Promise<{ transaction: Transaction, result: CurrencyFlow[] }>
583
639
  * Promise resolving to the transaction object representing the cancel action with the result of the orders.
584
640
  * @throws {Error} Throws an error if no open orders are found for the specified user.
@@ -595,8 +651,12 @@ export const cancelOrder = decorator(async ({ chainId, userAddress, id, options,
595
651
  * ids: openOrders.map((order) => order.id)
596
652
  * })
597
653
  */
598
- export const cancelOrders = decorator(async ({ chainId, userAddress, ids, options, }) => {
599
- const isApprovedForAll = await fetchIsApprovedForAll(chainId, userAddress);
654
+ export const cancelOrders = async ({ chainId, userAddress, ids, options, }) => {
655
+ const publicClient = createPublicClient({
656
+ chain: CHAIN_MAP[chainId],
657
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
658
+ });
659
+ const isApprovedForAll = await fetchIsApprovedForAll(publicClient, chainId, userAddress);
600
660
  if (!isApprovedForAll) {
601
661
  throw new Error(`
602
662
  Set ApprovalForAll before calling this function.
@@ -608,22 +668,22 @@ export const cancelOrders = decorator(async ({ chainId, userAddress, ids, option
608
668
  })
609
669
  `);
610
670
  }
611
- const orders = (await fetchOrders(chainId, ids.map((id) => BigInt(id)))).filter((order) => isAddressEqual(order.owner, userAddress) && order.open > 0n);
671
+ const orders = (await fetchOnChainOrders(publicClient, chainId, ids.map((id) => BigInt(id)), !!(options && options.useSubgraph))).filter((order) => isAddressEqual(order.user, userAddress) && order.cancelable.value !== '0');
612
672
  const tokensToSettle = orders
613
- .map((order) => [order.baseCurrency.address, order.quoteCurrency.address])
673
+ .map((order) => [order.inputCurrency.address, order.outputCurrency.address])
614
674
  .flat()
615
675
  .filter((address, index, self) => self.findIndex((c) => isAddressEqual(c, address)) === index)
616
676
  .filter((address) => !isAddressEqual(address, zeroAddress));
617
677
  return {
618
- transaction: await buildTransaction(chainId, {
678
+ transaction: await buildTransaction(publicClient, {
619
679
  chain: CHAIN_MAP[chainId],
620
680
  account: userAddress,
621
681
  address: CONTRACT_ADDRESSES[chainId].Controller,
622
682
  abi: CONTROLLER_ABI,
623
683
  functionName: 'cancel',
624
684
  args: [
625
- orders.map(({ orderId }) => ({
626
- id: orderId,
685
+ orders.map(({ id }) => ({
686
+ id,
627
687
  leftQuoteAmount: 0n,
628
688
  hookData: zeroHash,
629
689
  })),
@@ -632,24 +692,616 @@ export const cancelOrders = decorator(async ({ chainId, userAddress, ids, option
632
692
  getDeadlineTimestampInSeconds(),
633
693
  ],
634
694
  }, options?.gasLimit),
635
- result: orders
636
- .map((order) => {
637
- const amount = applyPercent(order.unit * order.open, 100 +
638
- (Number(MAKER_DEFAULT_POLICY.rate) * 100) /
639
- Number(MAKER_DEFAULT_POLICY.RATE_PRECISION), 6);
640
- return {
641
- currency: order.quoteCurrency,
642
- amount: formatUnits(amount, order.quoteCurrency.decimals),
643
- };
644
- })
645
- .reduce((acc, { currency, amount }) => {
695
+ result: orders.reduce((acc, { cancelable: { currency, value } }) => {
646
696
  const index = acc.findIndex((c) => isAddressEqual(c.currency.address, currency.address));
647
697
  if (index === -1) {
648
- return [...acc, { currency, amount, direction: 'out' }];
698
+ return [...acc, { currency, amount: value, direction: 'out' }];
649
699
  }
650
- acc[index].amount = (Number(acc[index].amount) + Number(amount)).toString();
700
+ acc[index].amount = (Number(acc[index].amount) + Number(value)).toString();
651
701
  return acc;
652
702
  }, []),
653
703
  };
654
- });
704
+ };
705
+ /**
706
+ * Build a transaction to open a pool,
707
+ *
708
+ * @param chainId The chain ID of the blockchain.
709
+ * @param userAddress The address of the user.
710
+ * @param inputToken The address of the input token.
711
+ * @param outputToken The address of the output token.
712
+ * @param options {@link DefaultWriteContractOptions} options.
713
+ * @returns A Promise resolving to a transaction object. If the market is already open, returns undefined.
714
+ * @example
715
+ * import { openPool } from '@clober/v2-sdk'
716
+ *
717
+ * const transaction = await openPool({
718
+ * chainId: 421614,
719
+ * userAddress: '0xF8c1869Ecd4df136693C45EcE1b67f85B6bDaE69',
720
+ * inputToken: '0x00bfd44e79fb7f6dd5887a9426c8ef85a0cd23e0',
721
+ * outputToken: '0x0000000000000000000000000000000000000000',
722
+ * salt: '0x0000000000000000000000000000000000000000000000000000000000000000',
723
+ * })
724
+ */
725
+ export const openPool = async ({ chainId, userAddress, tokenA, tokenB, salt, options, }) => {
726
+ const publicClient = createPublicClient({
727
+ chain: CHAIN_MAP[chainId],
728
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
729
+ });
730
+ const pool = await fetchPool(publicClient, chainId, [tokenA, tokenB], salt, !!(options && options.useSubgraph));
731
+ if (!pool.isOpened) {
732
+ return buildTransaction(publicClient, {
733
+ chain: CHAIN_MAP[chainId],
734
+ address: CONTRACT_ADDRESSES[chainId].Rebalancer,
735
+ account: userAddress,
736
+ abi: REBALANCER_ABI,
737
+ functionName: 'open',
738
+ args: [
739
+ {
740
+ base: pool.market.bidBook.base.address,
741
+ unitSize: pool.market.bidBook.unitSize,
742
+ quote: pool.market.bidBook.quote.address,
743
+ makerPolicy: MAKER_DEFAULT_POLICY[chainId].value,
744
+ hooks: zeroAddress,
745
+ takerPolicy: TAKER_DEFAULT_POLICY[chainId].value,
746
+ },
747
+ {
748
+ base: pool.market.askBook.base.address,
749
+ unitSize: pool.market.askBook.unitSize,
750
+ quote: pool.market.askBook.quote.address,
751
+ makerPolicy: MAKER_DEFAULT_POLICY[chainId].value,
752
+ hooks: zeroAddress,
753
+ takerPolicy: TAKER_DEFAULT_POLICY[chainId].value,
754
+ },
755
+ toBytes32(salt),
756
+ CONTRACT_ADDRESSES[chainId].Strategy,
757
+ ],
758
+ }, options?.gasLimit);
759
+ }
760
+ return undefined;
761
+ };
762
+ export const addLiquidity = async ({ chainId, userAddress, token0, token1, salt, amount0, amount1, options, }) => {
763
+ const publicClient = createPublicClient({
764
+ chain: CHAIN_MAP[chainId],
765
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
766
+ });
767
+ const pool = await fetchPool(publicClient, chainId, [token0, token1], salt, !!(options && options.useSubgraph));
768
+ if (!pool.isOpened) {
769
+ throw new Error(`
770
+ Open the pool before adding liquidity.
771
+ import { openPool } from '@clober/v2-sdk'
772
+
773
+ const transaction = await openPool({
774
+ chainId: ${chainId},
775
+ tokenA: '${token0}',
776
+ tokenB: '${token1}',
777
+ salt: '0x0000000000000000000000000000000000000000000000000000000000000000',
778
+ })
779
+ `);
780
+ }
781
+ const [amountAOrigin, amountBOrigin] = isAddressEqual(pool.currencyA.address, getAddress(token0))
782
+ ? [
783
+ parseUnits(amount0 ?? '0', pool.currencyA.decimals),
784
+ parseUnits(amount1 ?? '0', pool.currencyB.decimals),
785
+ ]
786
+ : [
787
+ parseUnits(amount1 ?? '0', pool.currencyA.decimals),
788
+ parseUnits(amount0 ?? '0', pool.currencyB.decimals),
789
+ ];
790
+ let [amountA, amountB] = [amountAOrigin, amountBOrigin];
791
+ const tokenAPermitParams = isAddressEqual(pool.currencyA.address, getAddress(token0))
792
+ ? options?.token0PermitParams ?? emptyERC20PermitParams
793
+ : options?.token1PermitParams ?? emptyERC20PermitParams;
794
+ const tokenBPermitParams = isAddressEqual(pool.currencyA.address, getAddress(token0))
795
+ ? options?.token1PermitParams ?? emptyERC20PermitParams
796
+ : options?.token0PermitParams ?? emptyERC20PermitParams;
797
+ let disableSwap = !!(options && options.disableSwap);
798
+ if (pool.totalSupply === 0n ||
799
+ (pool.liquidityA === 0n && pool.liquidityB === 0n)) {
800
+ disableSwap = true;
801
+ }
802
+ const slippageLimitPercent = options?.slippage ?? 2;
803
+ const swapParams = {
804
+ inCurrency: zeroAddress,
805
+ amount: 0n,
806
+ data: '0x',
807
+ };
808
+ if (!disableSwap) {
809
+ const currencyBPerCurrencyA = options?.testnetPrice
810
+ ? isAddressEqual(getQuoteToken({
811
+ chainId,
812
+ token0,
813
+ token1,
814
+ }), pool.currencyA.address)
815
+ ? 1 / Number(options.testnetPrice)
816
+ : Number(options.testnetPrice)
817
+ : undefined;
818
+ const swapAmountA = parseUnits('1', pool.currencyA.decimals);
819
+ const { amountOut: swapAmountB } = await fetchQuote({
820
+ chainId,
821
+ amountIn: swapAmountA,
822
+ tokenIn: pool.currencyA,
823
+ tokenOut: pool.currencyB,
824
+ slippageLimitPercent: 20,
825
+ userAddress: CONTRACT_ADDRESSES[chainId].Minter,
826
+ testnetPrice: currencyBPerCurrencyA,
827
+ });
828
+ const { deltaA, deltaB } = getIdealDelta(amountA, amountB, pool.liquidityA, pool.liquidityB, swapAmountA, swapAmountB);
829
+ if (deltaA < 0n) {
830
+ swapParams.inCurrency = pool.currencyA.address;
831
+ swapParams.amount = -deltaA;
832
+ const { amountOut: actualDeltaB, data: calldata } = await fetchCallData({
833
+ chainId,
834
+ amountIn: swapParams.amount,
835
+ tokenIn: pool.currencyA,
836
+ tokenOut: pool.currencyB,
837
+ slippageLimitPercent,
838
+ userAddress: CONTRACT_ADDRESSES[chainId].Minter,
839
+ testnetPrice: currencyBPerCurrencyA,
840
+ });
841
+ swapParams.data = calldata;
842
+ amountA += deltaA;
843
+ amountB += actualDeltaB;
844
+ }
845
+ else if (deltaB < 0n) {
846
+ swapParams.inCurrency = pool.currencyB.address;
847
+ swapParams.amount = -deltaB;
848
+ const { amountOut: actualDeltaA, data: calldata } = await fetchCallData({
849
+ chainId,
850
+ amountIn: swapParams.amount,
851
+ tokenIn: pool.currencyB,
852
+ tokenOut: pool.currencyA,
853
+ slippageLimitPercent,
854
+ userAddress: CONTRACT_ADDRESSES[chainId].Minter,
855
+ testnetPrice: currencyBPerCurrencyA
856
+ ? 1 / currencyBPerCurrencyA
857
+ : undefined,
858
+ });
859
+ swapParams.data = calldata;
860
+ amountA += actualDeltaA;
861
+ amountB += deltaB;
862
+ }
863
+ }
864
+ const { mintAmount, inAmountA, inAmountB } = getExpectedMintResult(pool.totalSupply, pool.liquidityA, pool.liquidityB, amountA, amountB, pool.currencyA, pool.currencyB);
865
+ if (mintAmount === 0n) {
866
+ return {
867
+ transaction: undefined,
868
+ result: {
869
+ currencyA: {
870
+ currency: pool.currencyA,
871
+ amount: '0',
872
+ direction: 'in',
873
+ },
874
+ currencyB: {
875
+ currency: pool.currencyB,
876
+ amount: '0',
877
+ direction: 'in',
878
+ },
879
+ lpCurrency: {
880
+ currency: pool.currencyLp,
881
+ amount: '0',
882
+ direction: 'out',
883
+ },
884
+ },
885
+ };
886
+ }
887
+ const minMintAmount = applyPercent(mintAmount, 100 - slippageLimitPercent);
888
+ const transaction = await buildTransaction(publicClient, {
889
+ chain: CHAIN_MAP[chainId],
890
+ account: userAddress,
891
+ address: CONTRACT_ADDRESSES[chainId].Minter,
892
+ abi: MINTER_ABI,
893
+ functionName: 'mint',
894
+ args: [
895
+ pool.key,
896
+ amountAOrigin,
897
+ amountBOrigin,
898
+ minMintAmount,
899
+ {
900
+ permitAmount: tokenAPermitParams.permitAmount,
901
+ signature: tokenAPermitParams.signature,
902
+ },
903
+ {
904
+ permitAmount: tokenBPermitParams.permitAmount,
905
+ signature: tokenBPermitParams.signature,
906
+ },
907
+ swapParams,
908
+ ],
909
+ value: isAddressEqual(token0, zeroAddress)
910
+ ? amountAOrigin
911
+ : isAddressEqual(token1, zeroAddress)
912
+ ? amountBOrigin
913
+ : undefined,
914
+ }, options?.gasLimit);
915
+ const currencyARefund = amountA - inAmountA;
916
+ const currencyBRefund = amountB - inAmountB;
917
+ const currencyAResultAmount = amountAOrigin - currencyARefund;
918
+ const currencyBResultAmount = amountBOrigin - currencyBRefund;
919
+ return {
920
+ transaction,
921
+ result: {
922
+ currencyA: {
923
+ currency: pool.currencyA,
924
+ amount: formatUnits(abs(currencyAResultAmount), pool.currencyA.decimals),
925
+ direction: currencyAResultAmount >= 0 ? 'in' : 'out',
926
+ },
927
+ currencyB: {
928
+ currency: pool.currencyB,
929
+ amount: formatUnits(abs(currencyBResultAmount), pool.currencyB.decimals),
930
+ direction: currencyBResultAmount >= 0 ? 'in' : 'out',
931
+ },
932
+ lpCurrency: {
933
+ currency: pool.currencyLp,
934
+ amount: formatUnits(mintAmount, pool.currencyLp.decimals),
935
+ direction: 'out',
936
+ },
937
+ },
938
+ };
939
+ };
940
+ // @dev: Withdraw amount calculation logic is based on the contract code.
941
+ export const removeLiquidity = async ({ chainId, userAddress, token0, token1, salt, amount, options, }) => {
942
+ const publicClient = createPublicClient({
943
+ chain: CHAIN_MAP[chainId],
944
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
945
+ });
946
+ const pool = await fetchPool(publicClient, chainId, [token0, token1], salt, !!(options && options.useSubgraph));
947
+ if (!pool.isOpened) {
948
+ throw new Error(`
949
+ Open the pool before removing liquidity.
950
+ import { openPool } from '@clober/v2-sdk'
951
+
952
+ const transaction = await openPool({
953
+ chainId: ${chainId},
954
+ tokenA: '${token0}',
955
+ tokenB: '${token1}',
956
+ salt: '0x0000000000000000000000000000000000000000000000000000000000000000',
957
+ })
958
+ `);
959
+ }
960
+ const burnAmount = parseUnits(amount, pool.currencyLp.decimals);
961
+ const slippageLimitPercent = options?.slippage ?? 2;
962
+ const withdrawAmountA = (burnAmount * pool.liquidityA) / pool.totalSupply;
963
+ const withdrawAmountB = (burnAmount * pool.liquidityB) / pool.totalSupply;
964
+ const minWithdrawAmountA = applyPercent(withdrawAmountA, 100 - slippageLimitPercent);
965
+ const minWithdrawAmountB = applyPercent(withdrawAmountB, 100 - slippageLimitPercent);
966
+ if (burnAmount === 0n) {
967
+ return {
968
+ transaction: undefined,
969
+ result: {
970
+ currencyA: {
971
+ currency: pool.currencyA,
972
+ amount: '0',
973
+ direction: 'out',
974
+ },
975
+ currencyB: {
976
+ currency: pool.currencyB,
977
+ amount: '0',
978
+ direction: 'out',
979
+ },
980
+ lpCurrency: {
981
+ currency: pool.currencyLp,
982
+ amount: '0',
983
+ direction: 'in',
984
+ },
985
+ },
986
+ };
987
+ }
988
+ const transaction = await buildTransaction(publicClient, {
989
+ chain: CHAIN_MAP[chainId],
990
+ account: userAddress,
991
+ address: CONTRACT_ADDRESSES[chainId].Rebalancer,
992
+ abi: REBALANCER_ABI,
993
+ functionName: 'burn',
994
+ args: [pool.key, burnAmount, minWithdrawAmountA, minWithdrawAmountB],
995
+ }, options?.gasLimit);
996
+ return {
997
+ transaction,
998
+ result: {
999
+ currencyA: {
1000
+ currency: pool.currencyA,
1001
+ amount: formatUnits(withdrawAmountA, pool.currencyA.decimals),
1002
+ direction: 'out',
1003
+ },
1004
+ currencyB: {
1005
+ currency: pool.currencyB,
1006
+ amount: formatUnits(withdrawAmountB, pool.currencyB.decimals),
1007
+ direction: 'out',
1008
+ },
1009
+ lpCurrency: {
1010
+ currency: pool.currencyLp,
1011
+ amount: amount,
1012
+ direction: 'in',
1013
+ },
1014
+ },
1015
+ };
1016
+ };
1017
+ export const refillOrder = async ({ chainId, userAddress, token0, token1, salt, options, }) => {
1018
+ const publicClient = createPublicClient({
1019
+ chain: CHAIN_MAP[chainId],
1020
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
1021
+ });
1022
+ const pool = options?.pool
1023
+ ? options.pool
1024
+ : (await fetchPool(publicClient, chainId, [token0, token1], salt, !!(options && options.useSubgraph))).toJson();
1025
+ if (!pool.isOpened) {
1026
+ throw new Error(`
1027
+ Open the pool before rebalancing pool.
1028
+ import { openPool } from '@clober/v2-sdk'
1029
+
1030
+ const transaction = await openPool({
1031
+ chainId: ${chainId},
1032
+ tokenA: '${token0}',
1033
+ tokenB: '${token1}',
1034
+ salt: '0x0000000000000000000000000000000000000000000000000000000000000000',
1035
+ })
1036
+ `);
1037
+ }
1038
+ return buildTransaction(publicClient, {
1039
+ chain: CHAIN_MAP[chainId],
1040
+ account: userAddress,
1041
+ address: CONTRACT_ADDRESSES[chainId].Rebalancer,
1042
+ abi: REBALANCER_ABI,
1043
+ functionName: 'rebalance',
1044
+ args: [pool.key],
1045
+ }, options?.gasLimit, options?.gasPriceLimit);
1046
+ };
1047
+ export const adjustOrderPrice = async ({ chainId, userAddress, token0, token1, salt, oraclePrice, bidPrice, askPrice, alpha, options, }) => {
1048
+ if (Number(alpha) <= 0 || Number(alpha) > 1) {
1049
+ throw new Error('Alpha value must be in the range (0, 1]');
1050
+ }
1051
+ if (Number(bidPrice) <= 0 || Number(askPrice) <= 0) {
1052
+ throw new Error('Price must be greater than 0');
1053
+ }
1054
+ if (Number(bidPrice) >= Number(askPrice)) {
1055
+ throw new Error('Bid price must be less than ask price');
1056
+ }
1057
+ const publicClient = createPublicClient({
1058
+ chain: CHAIN_MAP[chainId],
1059
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
1060
+ });
1061
+ const pool = options?.pool
1062
+ ? options.pool
1063
+ : (await fetchPool(publicClient, chainId, [token0, token1], salt, !!(options && options.useSubgraph))).toJson();
1064
+ if (!pool.isOpened) {
1065
+ throw new Error(`
1066
+ Open the pool before updating strategy price.
1067
+ import { openPool } from '@clober/v2-sdk'
1068
+
1069
+ const transaction = await openPool({
1070
+ chainId: ${chainId},
1071
+ tokenA: '${token0}',
1072
+ tokenB: '${token1}',
1073
+ salt: '0x0000000000000000000000000000000000000000000000000000000000000000',
1074
+ })
1075
+ `);
1076
+ }
1077
+ const [roundingUpBidPrice, roundingUpAskPrice] = [
1078
+ options?.roundingUpBidPrice ? options.roundingUpBidPrice : false,
1079
+ options?.roundingUpAskPrice ? options.roundingUpAskPrice : false,
1080
+ ];
1081
+ const { roundingDownTick: roundingDownTickA, roundingUpTick: roundingUpTickA, } = parsePrice(Number(bidPrice), pool.currencyA.decimals, pool.currencyB.decimals);
1082
+ const { roundingDownTick: roundingDownTickB, roundingUpTick: roundingUpTickB, } = parsePrice(Number(askPrice), pool.currencyA.decimals, pool.currencyB.decimals);
1083
+ const oracleRawPrice = convertHumanReadablePriceToRawPrice(Number(oraclePrice), pool.currencyA.decimals, pool.currencyB.decimals);
1084
+ const tickA = options?.bidTick
1085
+ ? Number(options.bidTick)
1086
+ : Number(roundingUpBidPrice ? roundingUpTickA : roundingDownTickA);
1087
+ let tickB = options?.askTick
1088
+ ? Number(options.askTick)
1089
+ : Number(invertTick(roundingUpAskPrice ? roundingUpTickB : roundingDownTickB));
1090
+ if (invertTick(BigInt(tickB)) <= BigInt(tickA)) {
1091
+ tickB = Number(invertTick(BigInt(tickA + 1)));
1092
+ }
1093
+ const rateRaw = parseUnits(alpha, 6);
1094
+ return buildTransaction(publicClient, {
1095
+ chain: CHAIN_MAP[chainId],
1096
+ account: userAddress,
1097
+ address: CONTRACT_ADDRESSES[chainId].Operator,
1098
+ abi: OPERATOR_ABI,
1099
+ functionName: 'updatePosition',
1100
+ args: [pool.key, oracleRawPrice, tickA, tickB, rateRaw],
1101
+ }, options?.gasLimit, options?.gasPriceLimit);
1102
+ };
1103
+ export const setStrategyConfig = async ({ chainId, userAddress, token0, token1, salt, config, options, }) => {
1104
+ // validate config
1105
+ if (Number(config.referenceThreshold) < 0 ||
1106
+ Number(config.referenceThreshold) > 1) {
1107
+ throw new Error('Reference threshold must be in the range [0, 1]');
1108
+ }
1109
+ if (Number(config.rebalanceThreshold) < 0 ||
1110
+ Number(config.rebalanceThreshold) > 1) {
1111
+ throw new Error('Rebalance threshold must be in the range [0, 1]');
1112
+ }
1113
+ if (Number(config.priceThresholdA) < 0 ||
1114
+ Number(config.priceThresholdA) > 1 ||
1115
+ Number(config.priceThresholdB) < 0 ||
1116
+ Number(config.priceThresholdB) > 1) {
1117
+ throw new Error('Price threshold must be in the range [0, 1]');
1118
+ }
1119
+ if (Number(config.rateA) < 0 ||
1120
+ Number(config.rateA) > 1 ||
1121
+ Number(config.rateB) < 0 ||
1122
+ Number(config.rateB) > 1) {
1123
+ throw new Error('Rate must be in the range [0, 1]');
1124
+ }
1125
+ if (Number(config.minRateA) < 0 ||
1126
+ Number(config.minRateA) > 1 ||
1127
+ Number(config.minRateB) < 0 ||
1128
+ Number(config.minRateB) > 1) {
1129
+ throw new Error('Min rate must be in the range [0, 1]');
1130
+ }
1131
+ if (Number(config.minRateA) > Number(config.rateA) ||
1132
+ Number(config.minRateB) > Number(config.rateB)) {
1133
+ throw new Error('Min rate must be less or equal to rate');
1134
+ }
1135
+ const publicClient = createPublicClient({
1136
+ chain: CHAIN_MAP[chainId],
1137
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
1138
+ });
1139
+ const pool = await fetchPool(publicClient, chainId, [token0, token1], salt, !!(options && options.useSubgraph));
1140
+ if (!pool.isOpened) {
1141
+ throw new Error(`
1142
+ Open the pool before set strategy config.
1143
+ import { openPool } from '@clober/v2-sdk'
1144
+
1145
+ const transaction = await openPool({
1146
+ chainId: ${chainId},
1147
+ tokenA: '${token0}',
1148
+ tokenB: '${token1}',
1149
+ })
1150
+ `);
1151
+ }
1152
+ const configRaw = {
1153
+ referenceThreshold: parseUnits(config.referenceThreshold, 6),
1154
+ rebalanceThreshold: parseUnits(config.rebalanceThreshold, 6),
1155
+ rateA: parseUnits(config.rateA, 6),
1156
+ rateB: parseUnits(config.rateB, 6),
1157
+ minRateA: parseUnits(config.minRateA, 6),
1158
+ minRateB: parseUnits(config.minRateB, 6),
1159
+ priceThresholdA: parseUnits(config.priceThresholdA, 6),
1160
+ priceThresholdB: parseUnits(config.priceThresholdB, 6),
1161
+ };
1162
+ return buildTransaction(publicClient, {
1163
+ chain: CHAIN_MAP[chainId],
1164
+ account: userAddress,
1165
+ address: CONTRACT_ADDRESSES[chainId].Strategy,
1166
+ abi: STRATEGY_ABI,
1167
+ functionName: 'setConfig',
1168
+ args: [pool.key, configRaw],
1169
+ }, options?.gasLimit);
1170
+ };
1171
+ export const pausePool = async ({ chainId, userAddress, token0, token1, salt, options, }) => {
1172
+ const publicClient = createPublicClient({
1173
+ chain: CHAIN_MAP[chainId],
1174
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
1175
+ });
1176
+ const pool = options?.pool
1177
+ ? options.pool
1178
+ : (await fetchPool(publicClient, chainId, [token0, token1], salt, !!(options && options.useSubgraph))).toJson();
1179
+ if (!pool.isOpened) {
1180
+ throw new Error(`
1181
+ Open the pool before trying pause.
1182
+ import { openPool } from '@clober/v2-sdk'
1183
+
1184
+ const transaction = await openPool({
1185
+ chainId: ${chainId},
1186
+ tokenA: '${token0}',
1187
+ tokenB: '${token1}',
1188
+ salt: '0x0000000000000000000000000000000000000000000000000000000000000000',
1189
+ })
1190
+ `);
1191
+ }
1192
+ if (pool.paused) {
1193
+ return undefined;
1194
+ }
1195
+ return buildTransaction(publicClient, {
1196
+ chain: CHAIN_MAP[chainId],
1197
+ account: userAddress,
1198
+ address: CONTRACT_ADDRESSES[chainId].Operator,
1199
+ abi: OPERATOR_ABI,
1200
+ functionName: 'pause',
1201
+ args: [pool.key],
1202
+ }, options?.gasLimit, options?.gasPriceLimit);
1203
+ };
1204
+ export const resumePool = async ({ chainId, userAddress, token0, token1, salt, options, }) => {
1205
+ const publicClient = createPublicClient({
1206
+ chain: CHAIN_MAP[chainId],
1207
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
1208
+ });
1209
+ const pool = options?.pool
1210
+ ? options.pool
1211
+ : (await fetchPool(publicClient, chainId, [token0, token1], salt, !!(options && options.useSubgraph))).toJson();
1212
+ if (!pool.isOpened) {
1213
+ throw new Error(`
1214
+ Open the pool before trying resume.
1215
+ import { openPool } from '@clober/v2-sdk'
1216
+
1217
+ const transaction = await openPool({
1218
+ chainId: ${chainId},
1219
+ tokenA: '${token0}',
1220
+ tokenB: '${token1}',
1221
+ salt: '0x0000000000000000000000000000000000000000000000000000000000000000',
1222
+ })
1223
+ `);
1224
+ }
1225
+ if (!pool.paused) {
1226
+ return undefined;
1227
+ }
1228
+ return buildTransaction(publicClient, {
1229
+ chain: CHAIN_MAP[chainId],
1230
+ account: userAddress,
1231
+ address: CONTRACT_ADDRESSES[chainId].Strategy,
1232
+ abi: STRATEGY_ABI,
1233
+ functionName: 'unpause',
1234
+ args: [pool.key],
1235
+ }, options?.gasLimit, options?.gasPriceLimit);
1236
+ };
1237
+ export const vote = async ({ chainId, userAddress, candidateAddress, inFavor, options, }) => {
1238
+ const publicClient = createPublicClient({
1239
+ chain: CHAIN_MAP[chainId],
1240
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
1241
+ });
1242
+ return buildTransaction(publicClient, {
1243
+ chain: CHAIN_MAP[chainId],
1244
+ account: userAddress,
1245
+ address: CONTRACT_ADDRESSES[chainId].ElectionGovernor,
1246
+ abi: ELECTION_GOVERNOR_ABI,
1247
+ functionName: 'vote',
1248
+ args: [candidateAddress, inFavor],
1249
+ }, options?.gasLimit, options?.gasPriceLimit);
1250
+ };
1251
+ export const register = async ({ chainId, userAddress, options, }) => {
1252
+ const publicClient = createPublicClient({
1253
+ chain: CHAIN_MAP[chainId],
1254
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
1255
+ });
1256
+ return buildTransaction(publicClient, {
1257
+ chain: CHAIN_MAP[chainId],
1258
+ account: userAddress,
1259
+ address: CONTRACT_ADDRESSES[chainId].ElectionGovernor,
1260
+ abi: ELECTION_GOVERNOR_ABI,
1261
+ functionName: 'register',
1262
+ args: [],
1263
+ }, options?.gasLimit, options?.gasPriceLimit);
1264
+ };
1265
+ export const end = async ({ chainId, userAddress, options, }) => {
1266
+ const publicClient = createPublicClient({
1267
+ chain: CHAIN_MAP[chainId],
1268
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
1269
+ });
1270
+ return buildTransaction(publicClient, {
1271
+ chain: CHAIN_MAP[chainId],
1272
+ account: userAddress,
1273
+ address: CONTRACT_ADDRESSES[chainId].ElectionGovernor,
1274
+ abi: ELECTION_GOVERNOR_ABI,
1275
+ functionName: 'end',
1276
+ args: [],
1277
+ }, options?.gasLimit, options?.gasPriceLimit);
1278
+ };
1279
+ export const mintVCLOB = async ({ chainId, userAddress, amount, options, }) => {
1280
+ const publicClient = createPublicClient({
1281
+ chain: CHAIN_MAP[chainId],
1282
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
1283
+ });
1284
+ return buildTransaction(publicClient, {
1285
+ chain: CHAIN_MAP[chainId],
1286
+ account: userAddress,
1287
+ address: CONTRACT_ADDRESSES[chainId].VoteLockedCloberToken,
1288
+ abi: VCLOB_ABI,
1289
+ functionName: 'mint',
1290
+ args: [amount, userAddress],
1291
+ }, options?.gasLimit, options?.gasPriceLimit);
1292
+ };
1293
+ export const burnVCLOB = async ({ chainId, userAddress, id, options, }) => {
1294
+ const publicClient = createPublicClient({
1295
+ chain: CHAIN_MAP[chainId],
1296
+ transport: options?.rpcUrl ? http(options.rpcUrl) : http(),
1297
+ });
1298
+ return buildTransaction(publicClient, {
1299
+ chain: CHAIN_MAP[chainId],
1300
+ account: userAddress,
1301
+ address: CONTRACT_ADDRESSES[chainId].VoteLockedCloberToken,
1302
+ abi: VCLOB_ABI,
1303
+ functionName: 'burn',
1304
+ args: [Number(id), userAddress],
1305
+ }, options?.gasLimit, options?.gasPriceLimit);
1306
+ };
655
1307
  //# sourceMappingURL=call.js.map