@polyester/sdk 0.36.0-devnet-20261119195411 → 0.36.0-devnet-20261120040128

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 (309) hide show
  1. package/CHANGELOG.md +18 -2
  2. package/dist/client.d.ts +4 -0
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +4 -0
  5. package/dist/client.js.map +1 -1
  6. package/dist/gen/ai/v1/assistant_pb.d.ts +56 -4
  7. package/dist/gen/ai/v1/assistant_pb.d.ts.map +1 -1
  8. package/dist/gen/ai/v1/assistant_pb.js +9 -2
  9. package/dist/gen/ai/v1/assistant_pb.js.map +1 -1
  10. package/dist/gen/alerts/v1/price_alerts_pb.d.ts +1 -1
  11. package/dist/gen/auth/v1/account_scope_pb.d.ts +40 -0
  12. package/dist/gen/auth/v1/account_scope_pb.d.ts.map +1 -0
  13. package/dist/gen/auth/v1/account_scope_pb.js +46 -0
  14. package/dist/gen/auth/v1/account_scope_pb.js.map +1 -0
  15. package/dist/gen/auth/v1/activity_pb.d.ts +1 -1
  16. package/dist/gen/auth/v1/address_book_pb.d.ts +4 -32
  17. package/dist/gen/auth/v1/address_book_pb.d.ts.map +1 -1
  18. package/dist/gen/auth/v1/address_book_pb.js +8 -38
  19. package/dist/gen/auth/v1/address_book_pb.js.map +1 -1
  20. package/dist/gen/auth/v1/api_keys_pb.d.ts +1 -1
  21. package/dist/gen/auth/v1/auth_pb.d.ts +16 -15
  22. package/dist/gen/auth/v1/auth_pb.d.ts.map +1 -1
  23. package/dist/gen/auth/v1/auth_pb.js +16 -15
  24. package/dist/gen/auth/v1/auth_pb.js.map +1 -1
  25. package/dist/gen/auth/v1/connected_apps_pb.d.ts +60 -59
  26. package/dist/gen/auth/v1/connected_apps_pb.d.ts.map +1 -1
  27. package/dist/gen/auth/v1/connected_apps_pb.js +38 -37
  28. package/dist/gen/auth/v1/connected_apps_pb.js.map +1 -1
  29. package/dist/gen/auth/v1/mfa_pb.d.ts +1 -1
  30. package/dist/gen/auth/v1/policies_pb.d.ts +28 -2
  31. package/dist/gen/auth/v1/policies_pb.d.ts.map +1 -1
  32. package/dist/gen/auth/v1/policies_pb.js +27 -1
  33. package/dist/gen/auth/v1/policies_pb.js.map +1 -1
  34. package/dist/gen/auth/v1/profile_pb.d.ts +1 -1
  35. package/dist/gen/auth/v1/resolve_pb.d.ts +1 -1
  36. package/dist/gen/auth/v1/social_verification_pb.d.ts +1 -1
  37. package/dist/gen/auth/v1/subaccounts_pb.d.ts +1 -1
  38. package/dist/gen/auth/v1/subaccounts_pb.js +1 -1
  39. package/dist/gen/chain/analytics/v1/analytics_read_pb.d.ts +1 -1
  40. package/dist/gen/chain/deposit/v1/deposit_pb.d.ts +1 -1
  41. package/dist/gen/chain/guard/v1/guard_signer_pb.d.ts +1 -1
  42. package/dist/gen/chain/lifecycle/v1/lifecycle_read_pb.d.ts +1 -1
  43. package/dist/gen/chain/lifecycle/v1/types_pb.d.ts +1 -1
  44. package/dist/gen/chain/withdraw/v1/auto_withdraw_pb.d.ts +1 -1
  45. package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts +229 -3
  46. package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts.map +1 -1
  47. package/dist/gen/chain/withdraw/v1/withdraw_pb.js +32 -8
  48. package/dist/gen/chain/withdraw/v1/withdraw_pb.js.map +1 -1
  49. package/dist/gen/chain/zipper/v1/reason_pb.d.ts +1 -1
  50. package/dist/gen/chain/zipper/v1/zipper_pb.d.ts +1 -1
  51. package/dist/gen/changelog/v1/changelog_pb.d.ts +17 -5
  52. package/dist/gen/changelog/v1/changelog_pb.d.ts.map +1 -1
  53. package/dist/gen/changelog/v1/changelog_pb.js.map +1 -1
  54. package/dist/gen/checkpoints/v1/checkpoints_pb.d.ts +1 -1
  55. package/dist/gen/claims/v1/claims_pb.d.ts +1 -1
  56. package/dist/gen/fees/v1/fees_pb.d.ts +1 -1
  57. package/dist/gen/index.d.ts +8 -6
  58. package/dist/gen/index.js +28 -26
  59. package/dist/gen/ledger/read/v1/ledger_read_pb.d.ts +1 -1
  60. package/dist/gen/ledger/read/v1/statement_export_pb.d.ts +1 -1
  61. package/dist/gen/marketdata/v1/asset_info_pb.d.ts +1 -1
  62. package/dist/gen/marketdata/v1/heatmap_pb.d.ts +1 -1
  63. package/dist/gen/marketdata/v1/marketdata_pb.d.ts +289 -3
  64. package/dist/gen/marketdata/v1/marketdata_pb.d.ts.map +1 -1
  65. package/dist/gen/marketdata/v1/marketdata_pb.js +115 -2
  66. package/dist/gen/marketdata/v1/marketdata_pb.js.map +1 -1
  67. package/dist/gen/marketoverview/v1/marketoverview_pb.d.ts +1 -1
  68. package/dist/gen/notifications/v1/notifications_pb.d.ts +1 -1
  69. package/dist/gen/orderbook/v1/orderbook_pb.d.ts +1 -1
  70. package/dist/gen/orders/v1/orders_pb.d.ts +79 -26
  71. package/dist/gen/orders/v1/orders_pb.d.ts.map +1 -1
  72. package/dist/gen/orders/v1/orders_pb.js +36 -7
  73. package/dist/gen/orders/v1/orders_pb.js.map +1 -1
  74. package/dist/gen/orders/v1/orders_read_pb.d.ts +36 -2
  75. package/dist/gen/orders/v1/orders_read_pb.d.ts.map +1 -1
  76. package/dist/gen/orders/v1/orders_read_pb.js.map +1 -1
  77. package/dist/gen/polyester/api/v1/request_error_pb.d.ts +1 -1
  78. package/dist/gen/polyester/ratelimit/v1/types_pb.d.ts +1 -1
  79. package/dist/gen/polyester/type/v1/u128_pb.d.ts +1 -1
  80. package/dist/gen/privatews/v1/private_ws_pb.d.ts +1 -1
  81. package/dist/gen/ratelimit/v1/ratelimit_pb.d.ts +1 -1
  82. package/dist/gen/rewards/v1/rewards_pb.d.ts +1 -1
  83. package/dist/gen/strategies/v1/strategies_pb.d.ts +2928 -0
  84. package/dist/gen/strategies/v1/strategies_pb.d.ts.map +1 -0
  85. package/dist/gen/strategies/v1/strategies_pb.js +818 -0
  86. package/dist/gen/strategies/v1/strategies_pb.js.map +1 -0
  87. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.d.ts +39 -18
  88. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.d.ts.map +1 -1
  89. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.js +4 -1
  90. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.js.map +1 -1
  91. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.d.ts +313 -133
  92. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.d.ts.map +1 -1
  93. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.js +31 -26
  94. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.js.map +1 -1
  95. package/dist/gen/swap/quickswap/v1/quickswap_pb.d.ts +29 -14
  96. package/dist/gen/swap/quickswap/v1/quickswap_pb.d.ts.map +1 -1
  97. package/dist/gen/swap/quickswap/v1/quickswap_pb.js +2 -2
  98. package/dist/gen/swap/quickswap/v1/quickswap_pb.js.map +1 -1
  99. package/dist/gen/swap/quickswap/v1/quickswap_referral_pb.d.ts +110 -3
  100. package/dist/gen/swap/quickswap/v1/quickswap_referral_pb.d.ts.map +1 -1
  101. package/dist/gen/swap/quickswap/v1/quickswap_referral_pb.js +23 -3
  102. package/dist/gen/swap/quickswap/v1/quickswap_referral_pb.js.map +1 -1
  103. package/dist/gen/swap/v1/swap_pb.d.ts +1 -1
  104. package/dist/gen/system/v1/system_pb.d.ts +1 -1
  105. package/dist/gen/tradews/v1/trade_ws_pb.d.ts +1 -1
  106. package/dist/gen/transfer/v1/dust_conversion_pb.d.ts +1 -1
  107. package/dist/gen/transfer/v1/internal_transfer_pb.d.ts +4 -3
  108. package/dist/gen/transfer/v1/internal_transfer_pb.d.ts.map +1 -1
  109. package/dist/gen/transfer/v1/internal_transfer_pb.js.map +1 -1
  110. package/dist/gen/triggers/v1/triggers_pb.d.ts +62 -12
  111. package/dist/gen/triggers/v1/triggers_pb.d.ts.map +1 -1
  112. package/dist/gen/triggers/v1/triggers_pb.js +4 -2
  113. package/dist/gen/triggers/v1/triggers_pb.js.map +1 -1
  114. package/dist/gen/vip/v1/vip_pb.d.ts +1 -1
  115. package/dist/index.d.ts +12 -6
  116. package/dist/services/account-activity/account-activity.js +1 -1
  117. package/dist/services/account-activity/account-activity.schemas.d.ts +4 -4
  118. package/dist/services/accounts/accounts.js +1 -1
  119. package/dist/services/accounts/accounts.schemas.js +1 -1
  120. package/dist/services/address-book/address-book.codecs.js +1 -0
  121. package/dist/services/address-book/address-book.codecs.js.map +1 -1
  122. package/dist/services/address-book/address-book.schemas.d.ts +2 -2
  123. package/dist/services/api-keys/api-keys.schemas.d.ts +6 -6
  124. package/dist/services/assistant/assistant-events.schemas.d.ts +135 -37
  125. package/dist/services/assistant/assistant-events.schemas.d.ts.map +1 -1
  126. package/dist/services/assistant/assistant-events.schemas.js +15 -5
  127. package/dist/services/assistant/assistant-events.schemas.js.map +1 -1
  128. package/dist/services/assistant/assistant.codecs.d.ts +5 -2
  129. package/dist/services/assistant/assistant.codecs.d.ts.map +1 -1
  130. package/dist/services/assistant/assistant.codecs.js +10 -2
  131. package/dist/services/assistant/assistant.codecs.js.map +1 -1
  132. package/dist/services/assistant/assistant.js +1 -1
  133. package/dist/services/assistant/assistant.schemas.d.ts +1 -1
  134. package/dist/services/auth/auth.js +1 -1
  135. package/dist/services/auth/auth.js.map +1 -1
  136. package/dist/services/auth/profile/profile.js +1 -1
  137. package/dist/services/auto-withdraw/auto-withdraw.js +1 -1
  138. package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts +9 -9
  139. package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts.map +1 -1
  140. package/dist/services/auto-withdraw/auto-withdraw.schemas.js +5 -12
  141. package/dist/services/auto-withdraw/auto-withdraw.schemas.js.map +1 -1
  142. package/dist/services/candles/candles.js +1 -1
  143. package/dist/services/chain-analytics/chain-analytics.js +1 -1
  144. package/dist/services/changelog/changelog.js +1 -1
  145. package/dist/services/checkpoints/checkpoints.js +1 -1
  146. package/dist/services/checkpoints/checkpoints.schemas.d.ts +1 -1
  147. package/dist/services/claims/claims.js +1 -1
  148. package/dist/services/claims/claims.schemas.d.ts +2 -2
  149. package/dist/services/claims/claims.schemas.js +1 -1
  150. package/dist/services/connected-apps/connected-apps.d.ts +4 -4
  151. package/dist/services/connected-apps/connected-apps.d.ts.map +1 -1
  152. package/dist/services/connected-apps/connected-apps.js +14 -14
  153. package/dist/services/connected-apps/connected-apps.js.map +1 -1
  154. package/dist/services/connected-apps/connected-apps.schemas.d.ts +7 -7
  155. package/dist/services/connected-apps/connected-apps.schemas.d.ts.map +1 -1
  156. package/dist/services/connected-apps/connected-apps.schemas.js +10 -10
  157. package/dist/services/connected-apps/connected-apps.schemas.js.map +1 -1
  158. package/dist/services/connected-apps/connected-apps.types.d.ts +2 -2
  159. package/dist/services/deposit/deposit.js +1 -1
  160. package/dist/services/dust-conversion/dust-conversion.js +1 -1
  161. package/dist/services/dust-conversion/dust-conversion.schemas.d.ts +8 -8
  162. package/dist/services/dust-conversion/dust-conversion.schemas.js +1 -1
  163. package/dist/services/fees/fees.js +1 -1
  164. package/dist/services/guard-signer/guard-signer.js +1 -1
  165. package/dist/services/heatmap/heatmap.js +1 -1
  166. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  167. package/dist/services/internal-transfers/internal-transfers.js +1 -1
  168. package/dist/services/internal-transfers/internal-transfers.schemas.d.ts +6 -6
  169. package/dist/services/lifecycle/lifecycle.js +1 -1
  170. package/dist/services/lifecycle/lifecycle.schemas.d.ts +13 -13
  171. package/dist/services/lifecycle/lifecycle.schemas.js +2 -2
  172. package/dist/services/market-data/market-data.codecs.d.ts +9 -1
  173. package/dist/services/market-data/market-data.codecs.d.ts.map +1 -1
  174. package/dist/services/market-data/market-data.codecs.js +14 -1
  175. package/dist/services/market-data/market-data.codecs.js.map +1 -1
  176. package/dist/services/market-data/market-data.d.ts +9 -1
  177. package/dist/services/market-data/market-data.d.ts.map +1 -1
  178. package/dist/services/market-data/market-data.js +15 -2
  179. package/dist/services/market-data/market-data.js.map +1 -1
  180. package/dist/services/market-data/market-data.schemas.d.ts +40 -2
  181. package/dist/services/market-data/market-data.schemas.d.ts.map +1 -1
  182. package/dist/services/market-data/market-data.schemas.js +43 -8
  183. package/dist/services/market-data/market-data.schemas.js.map +1 -1
  184. package/dist/services/market-data/market-data.types.d.ts +3 -3
  185. package/dist/services/market-overview/market-overview.js +1 -1
  186. package/dist/services/market-overview/market-overview.schemas.js +1 -1
  187. package/dist/services/notifications/notifications.js +1 -1
  188. package/dist/services/notifications/notifications.schemas.d.ts +4 -4
  189. package/dist/services/orderbook/orderbook.js +1 -1
  190. package/dist/services/orders/order-errors.schemas.d.ts +9 -9
  191. package/dist/services/orders/order-errors.schemas.js +1 -1
  192. package/dist/services/orders/orders-batch.schemas.d.ts +97 -97
  193. package/dist/services/orders/orders-batch.schemas.js +1 -1
  194. package/dist/services/orders/orders-input.schemas.d.ts +16 -16
  195. package/dist/services/orders/orders-input.schemas.js +1 -1
  196. package/dist/services/orders/orders-modify.schemas.js +1 -1
  197. package/dist/services/orders/orders-output.schemas.d.ts +14 -14
  198. package/dist/services/orders/orders-output.schemas.d.ts.map +1 -1
  199. package/dist/services/orders/orders-output.schemas.js +1 -1
  200. package/dist/services/orders/orders-output.schemas.js.map +1 -1
  201. package/dist/services/orders/orders-risk.schemas.js +2 -2
  202. package/dist/services/orders/orders.d.ts +5 -0
  203. package/dist/services/orders/orders.d.ts.map +1 -1
  204. package/dist/services/orders/orders.js +7 -2
  205. package/dist/services/orders/orders.js.map +1 -1
  206. package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts +15 -15
  207. package/dist/services/policies/shared.codecs.js +12 -3
  208. package/dist/services/policies/shared.codecs.js.map +1 -1
  209. package/dist/services/policies/shared.d.ts +1 -1
  210. package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.d.ts +3 -3
  211. package/dist/services/price-alerts/price-alerts.js +1 -1
  212. package/dist/services/rate-limits/rate-limits.js +1 -1
  213. package/dist/services/rewards/rewards.js +1 -1
  214. package/dist/services/rewards/rewards.schemas.d.ts +4 -4
  215. package/dist/services/social-verification/social-verification.js +1 -1
  216. package/dist/services/social-verification/social-verification.schemas.js +1 -1
  217. package/dist/services/statement-exports/statement-exports.js +1 -1
  218. package/dist/services/statement-exports/statement-exports.schemas.d.ts +6 -6
  219. package/dist/services/strategies/service.d.ts +8 -0
  220. package/dist/services/strategies/service.d.ts.map +1 -0
  221. package/dist/services/strategies/service.js +9 -0
  222. package/dist/services/strategies/service.js.map +1 -0
  223. package/dist/services/strategies/strategies.codecs.d.ts +15 -0
  224. package/dist/services/strategies/strategies.codecs.d.ts.map +1 -0
  225. package/dist/services/strategies/strategies.codecs.js +50 -0
  226. package/dist/services/strategies/strategies.codecs.js.map +1 -0
  227. package/dist/services/strategies/strategies.d.ts +75 -0
  228. package/dist/services/strategies/strategies.d.ts.map +1 -0
  229. package/dist/services/strategies/strategies.js +135 -0
  230. package/dist/services/strategies/strategies.js.map +1 -0
  231. package/dist/services/strategies/strategies.schemas.d.ts +568 -0
  232. package/dist/services/strategies/strategies.schemas.d.ts.map +1 -0
  233. package/dist/services/strategies/strategies.schemas.js +408 -0
  234. package/dist/services/strategies/strategies.schemas.js.map +1 -0
  235. package/dist/services/strategies/strategies.types.d.ts +3 -0
  236. package/dist/services/subaccounts/subaccounts.schemas.d.ts +19 -19
  237. package/dist/services/swap/service.d.ts +8 -0
  238. package/dist/services/swap/service.d.ts.map +1 -0
  239. package/dist/services/swap/service.js +9 -0
  240. package/dist/services/swap/service.js.map +1 -0
  241. package/dist/services/swap/swap.codecs.d.ts +19 -0
  242. package/dist/services/swap/swap.codecs.d.ts.map +1 -0
  243. package/dist/services/swap/swap.codecs.js +39 -0
  244. package/dist/services/swap/swap.codecs.js.map +1 -0
  245. package/dist/services/swap/swap.d.ts +51 -0
  246. package/dist/services/swap/swap.d.ts.map +1 -0
  247. package/dist/services/swap/swap.js +71 -0
  248. package/dist/services/swap/swap.js.map +1 -0
  249. package/dist/services/swap/swap.schemas.d.ts +520 -0
  250. package/dist/services/swap/swap.schemas.d.ts.map +1 -0
  251. package/dist/services/swap/swap.schemas.js +213 -0
  252. package/dist/services/swap/swap.schemas.js.map +1 -0
  253. package/dist/services/swap/swap.types.d.ts +3 -0
  254. package/dist/services/system/system.js +1 -1
  255. package/dist/services/trades/trades.js +1 -1
  256. package/dist/services/trades/trades.schemas.d.ts +1 -1
  257. package/dist/services/trading-withdraws/trading-withdraws.d.ts +29 -2
  258. package/dist/services/trading-withdraws/trading-withdraws.d.ts.map +1 -1
  259. package/dist/services/trading-withdraws/trading-withdraws.js +75 -12
  260. package/dist/services/trading-withdraws/trading-withdraws.js.map +1 -1
  261. package/dist/services/trading-withdraws/trading-withdraws.schemas.d.ts +85 -1
  262. package/dist/services/trading-withdraws/trading-withdraws.schemas.d.ts.map +1 -1
  263. package/dist/services/trading-withdraws/trading-withdraws.schemas.js +57 -2
  264. package/dist/services/trading-withdraws/trading-withdraws.schemas.js.map +1 -1
  265. package/dist/services/trading-withdraws/trading-withdraws.types.d.ts +3 -3
  266. package/dist/services/trading-withdraws/wallet-message.js +30 -2
  267. package/dist/services/trading-withdraws/wallet-message.js.map +1 -1
  268. package/dist/services/triggers/trigger-child-order.schemas.js +2 -2
  269. package/dist/services/triggers/trigger-input.schemas.d.ts +2 -2
  270. package/dist/services/triggers/trigger-input.schemas.js +2 -2
  271. package/dist/services/triggers/triggers-output.schemas.d.ts +53 -53
  272. package/dist/services/triggers/triggers.js +1 -1
  273. package/dist/services/vip/vip.js +1 -1
  274. package/dist/services/vip/vip.schemas.d.ts +3 -3
  275. package/dist/services/vip/vip.schemas.js +1 -1
  276. package/dist/services/zipper/zipper.js +1 -1
  277. package/dist/services/zipper/zipper.schemas.js +1 -1
  278. package/dist/shared/connect-error-mapping.d.ts.map +1 -1
  279. package/dist/shared/connect-error-mapping.js +6 -0
  280. package/dist/shared/connect-error-mapping.js.map +1 -1
  281. package/dist/shared/decimal-surface.d.ts.map +1 -1
  282. package/dist/shared/decimal-surface.js +11 -1
  283. package/dist/shared/decimal-surface.js.map +1 -1
  284. package/dist/shared/error-detail.d.ts +37 -2
  285. package/dist/shared/error-detail.d.ts.map +1 -1
  286. package/dist/shared/error-detail.js +2 -0
  287. package/dist/shared/error-detail.js.map +1 -1
  288. package/dist/shared/error-details/alerts.js +1 -1
  289. package/dist/shared/error-details/assistant.js +1 -1
  290. package/dist/shared/error-details/auth.js +1 -1
  291. package/dist/shared/error-details/claims.js +1 -1
  292. package/dist/shared/error-details/internal-transfer.js +1 -1
  293. package/dist/shared/error-details/ledger.js +1 -1
  294. package/dist/shared/error-details/market-overview.js +1 -1
  295. package/dist/shared/error-details/notifications.js +1 -1
  296. package/dist/shared/error-details/orders.js +1 -1
  297. package/dist/shared/error-details/profile.js +1 -1
  298. package/dist/shared/error-details/rate-limit.js +1 -1
  299. package/dist/shared/error-details/strategies.js +36 -0
  300. package/dist/shared/error-details/strategies.js.map +1 -0
  301. package/dist/shared/error-details/swap.js +22 -0
  302. package/dist/shared/error-details/swap.js.map +1 -0
  303. package/dist/shared/error-details/withdraw.js +1 -1
  304. package/dist/shared/rate-limit.schemas.d.ts +1 -1
  305. package/dist/shared/rate-limit.schemas.js +1 -1
  306. package/dist/wired-services.d.ts.map +1 -1
  307. package/dist/wired-services.js +23 -19
  308. package/dist/wired-services.js.map +1 -1
  309. package/package.json +1 -1
@@ -0,0 +1,213 @@
1
+ import { removeUndefined } from "../../utils/remove-undefined.js";
2
+ import { formatId } from "../../utils/base58-id.js";
3
+ import { OptionalPublicIdSchema, OptionalTimestampMsSchema, PublicIdSchema, U128Schema, idInputSchema } from "../../shared/schemas.js";
4
+ import { enumLabel, enumLabelSchema } from "../../shared/proto-enum-codec.js";
5
+ import { fromU128, toU128 } from "../../utils/u128.js";
6
+ import { decimalInputToE18, scaledToDecimalOutput } from "../../shared/decimal-surface.js";
7
+ import { msToTimestamp } from "../../utils/timestamp.js";
8
+ import { PositiveUint32InputSchema } from "../shared.js";
9
+ import { AccountScopeInputEntries, accountScopeToSubaccountId } from "../../shared/account-scope.js";
10
+ import { SwapOrderStatusCodec, SwapReasonCodec, SwapSideCodec, SwapStatusCodec } from "./swap.codecs.js";
11
+ import * as v from "valibot";
12
+ //#region src/services/swap/swap.schemas.ts
13
+ const IdempotencyKeySchema = v.pipe(v.string(), v.minLength(1));
14
+ /** Positive decimal string → wire U128 in 18-decimal units. */
15
+ function e18AmountInputSchema(field) {
16
+ return v.pipe(v.string(), v.transform((value) => decimalInputToE18(field, value)), v.check((scaled) => scaled > 0n, `${field} must be greater than 0`), v.transform(toU128));
17
+ }
18
+ const SwapTermsInputEntries = {
19
+ /** Defaults to the active subaccount, else the root account (or an API key's bound subaccount). */
20
+ ...AccountScopeInputEntries,
21
+ /** Unified asset ID spent, as in balances and internal transfers. */
22
+ sourceAssetId: PositiveUint32InputSchema,
23
+ /** Unified asset ID received. */
24
+ destinationAssetId: PositiveUint32InputSchema,
25
+ /**
26
+ * Source amount to spend, as a decimal string (up to 18 decimal places). Only whole order
27
+ * steps of the market trade; the rest stays on the account.
28
+ */
29
+ amount: e18AmountInputSchema("amount")
30
+ };
31
+ function toTerms({ account, sourceAssetId, destinationAssetId, amount }) {
32
+ return removeUndefined({
33
+ subaccountId: accountScopeToSubaccountId(account),
34
+ sourceAssetId,
35
+ destinationAssetId,
36
+ amount: {
37
+ case: "amountE18",
38
+ value: amount
39
+ }
40
+ });
41
+ }
42
+ const QuoteSwapInputSchema = v.pipe(v.strictObject({
43
+ ...SwapTermsInputEntries,
44
+ /** Accepted shortfall from the expected output, in basis points (1 to 1000). */
45
+ maxSlippageBps: PositiveUint32InputSchema
46
+ }), v.transform(({ maxSlippageBps, ...terms }) => ({
47
+ terms: toTerms(terms),
48
+ maxSlippageBps
49
+ })));
50
+ const CreateSwapInputSchema = v.pipe(v.strictObject({
51
+ ...SwapTermsInputEntries,
52
+ /**
53
+ * Minimum destination amount after fees for the whole amount, as a decimal string;
54
+ * usually the quote's `minAmountOut`.
55
+ */
56
+ minAmountOut: e18AmountInputSchema("minAmountOut"),
57
+ /** The accepted quote's `expiresAt` (epoch ms). Refused with `QUOTE_EXPIRED` after it. */
58
+ quoteExpiresAt: v.pipe(v.number(), v.safeInteger(), v.gtValue(0)),
59
+ /**
60
+ * Caller-chosen key, unique per caller. The same key and request return the same swap;
61
+ * the same key with a different request is `IDEMPOTENCY_CONFLICT`.
62
+ */
63
+ idempotencyKey: IdempotencyKeySchema
64
+ }), v.transform(({ minAmountOut, quoteExpiresAt, idempotencyKey, ...terms }) => ({
65
+ idempotencyKey,
66
+ terms: toTerms(terms),
67
+ minAmountOutE18: minAmountOut,
68
+ quoteExpiresAt: msToTimestamp(quoteExpiresAt)
69
+ })));
70
+ const GetSwapInputSchema = v.pipe(v.union([v.strictObject({ swapId: idInputSchema("swapId") }), v.strictObject({ idempotencyKey: IdempotencyKeySchema })]), v.transform((input) => ({ selector: "swapId" in input ? {
71
+ case: "swapId",
72
+ value: input.swapId
73
+ } : {
74
+ case: "idempotencyKey",
75
+ value: input.idempotencyKey
76
+ } })));
77
+ /** Wire `*_e18` U128 → exact decimal string; an unset amount is `"0"`. */
78
+ function e18ToDecimal(value) {
79
+ return scaledToDecimalOutput(fromU128(value), 18);
80
+ }
81
+ const AmountE18Schema = v.optional(U128Schema);
82
+ /** Root account is `null`. */
83
+ const SubaccountIdOutputSchema = v.pipe(OptionalPublicIdSchema, v.transform((id) => id ?? null));
84
+ const SwapQuoteLegSchema = v.pipe(v.object({
85
+ symbolId: v.number(),
86
+ side: enumLabelSchema(SwapSideCodec.protoToOutput),
87
+ averagePrice: v.string(),
88
+ priceImpactBps: v.number(),
89
+ takerFeeRatePercent: v.string(),
90
+ feeE18: AmountE18Schema,
91
+ feeAssetId: v.number()
92
+ }), v.transform(({ feeE18, ...leg }) => ({
93
+ symbolId: leg.symbolId,
94
+ side: leg.side,
95
+ /** Estimated average fill price, quote per base, for display. */
96
+ averagePrice: leg.averagePrice,
97
+ /** Distance of `averagePrice` from the best price, in bps, rounded up. */
98
+ priceImpactBps: leg.priceImpactBps,
99
+ /** The account's spot taker fee rate in percent, e.g. `"0.1"`. */
100
+ takerFeeRatePercent: leg.takerFeeRatePercent,
101
+ /** Estimated fee, in `feeAssetId` (the asset the leg receives). */
102
+ fee: e18ToDecimal(feeE18),
103
+ feeAssetId: leg.feeAssetId
104
+ })));
105
+ const SwapTermsOutputSchema = v.object({
106
+ subaccountId: v.bigint(),
107
+ sourceAssetId: v.number(),
108
+ destinationAssetId: v.number(),
109
+ amount: v.object({
110
+ case: v.literal("amountE18"),
111
+ value: U128Schema
112
+ })
113
+ });
114
+ const SwapQuoteSchema = v.pipe(v.object({
115
+ terms: SwapTermsOutputSchema,
116
+ legs: v.array(SwapQuoteLegSchema),
117
+ expectedAmountOutE18: AmountE18Schema,
118
+ minAmountOutE18: AmountE18Schema,
119
+ quotedAt: OptionalTimestampMsSchema,
120
+ expiresAt: OptionalTimestampMsSchema
121
+ }), v.transform((quote) => ({
122
+ /** Subaccount the quote is for; `null` for the root account. */
123
+ subaccountId: quote.terms.subaccountId === 0n ? null : formatId(quote.terms.subaccountId),
124
+ sourceAssetId: quote.terms.sourceAssetId,
125
+ destinationAssetId: quote.terms.destinationAssetId,
126
+ /** Source amount quoted. */
127
+ amount: e18ToDecimal(quote.terms.amount.value),
128
+ /** Markets the swap trades on, in order; a direct swap has one. */
129
+ legs: quote.legs,
130
+ /** Estimated destination amount after fees at current depth. */
131
+ expectedAmountOut: e18ToDecimal(quote.expectedAmountOutE18),
132
+ /** Destination amount after fees at the requested slippage; pass to `create`. */
133
+ minAmountOut: e18ToDecimal(quote.minAmountOutE18),
134
+ quotedAt: quote.quotedAt ?? null,
135
+ /** 30 seconds after `quotedAt`; pass to `create` as `quoteExpiresAt`. */
136
+ expiresAt: quote.expiresAt ?? null
137
+ })));
138
+ const SwapOrderSchema = v.pipe(v.object({
139
+ orderId: v.bigint(),
140
+ symbolId: v.number(),
141
+ side: enumLabelSchema(SwapSideCodec.protoToOutput),
142
+ leg: v.number(),
143
+ status: enumLabelSchema(SwapOrderStatusCodec.protoToOutput),
144
+ limitPriceTicks: v.bigint(),
145
+ spentE18: AmountE18Schema,
146
+ receivedE18: AmountE18Schema,
147
+ feeE18: AmountE18Schema
148
+ }), v.transform((order) => ({
149
+ /** Spot order ID once the market accepted it; `null` before. */
150
+ orderId: order.orderId === 0n ? null : formatId(order.orderId),
151
+ symbolId: order.symbolId,
152
+ side: order.side,
153
+ /** Zero-based position of the order's market in the route. */
154
+ leg: order.leg,
155
+ status: order.status,
156
+ /** IOC limit price, quote per base: the worst price that nets the minimum rate. */
157
+ limitPrice: scaledToDecimalOutput(order.limitPriceTicks, 9),
158
+ /** Spent in settled fills, fees in the spent asset included. */
159
+ spent: e18ToDecimal(order.spentE18),
160
+ /** Received in settled fills, after fees. */
161
+ received: e18ToDecimal(order.receivedE18),
162
+ /** Fee on settled fills, in the asset the order receives. */
163
+ fee: e18ToDecimal(order.feeE18)
164
+ })));
165
+ const SwapSchema = v.pipe(v.object({
166
+ swapId: PublicIdSchema,
167
+ idempotencyKey: v.string(),
168
+ subaccountId: SubaccountIdOutputSchema,
169
+ sourceAssetId: v.number(),
170
+ destinationAssetId: v.number(),
171
+ amountE18: AmountE18Schema,
172
+ minAmountOutE18: AmountE18Schema,
173
+ status: enumLabelSchema(SwapStatusCodec.protoToOutput),
174
+ reason: v.number(),
175
+ isTerminal: v.boolean(),
176
+ executedAmountE18: AmountE18Schema,
177
+ unspentAmountE18: AmountE18Schema,
178
+ receivedAmountE18: AmountE18Schema,
179
+ feeE18: AmountE18Schema,
180
+ orders: v.array(SwapOrderSchema),
181
+ createdAt: OptionalTimestampMsSchema
182
+ }), v.transform((swap) => ({
183
+ swapId: swap.swapId,
184
+ idempotencyKey: swap.idempotencyKey,
185
+ /** Subaccount funding the swap; `null` for the root account. */
186
+ subaccountId: swap.subaccountId,
187
+ sourceAssetId: swap.sourceAssetId,
188
+ destinationAssetId: swap.destinationAssetId,
189
+ /** Source amount requested. */
190
+ amount: e18ToDecimal(swap.amountE18),
191
+ /** Minimum destination amount after fees for the whole amount. */
192
+ minAmountOut: e18ToDecimal(swap.minAmountOutE18),
193
+ status: swap.status,
194
+ /** Why a `partially_completed` or `failed` swap did not trade everything; null otherwise. */
195
+ reason: swap.reason === 0 ? null : enumLabel(SwapReasonCodec.protoToOutput, swap.reason),
196
+ /** True once `status` is `completed`, `partially_completed` or `failed`; stop polling. */
197
+ isTerminal: swap.isTerminal,
198
+ /** Source spent in settled fills. */
199
+ executedAmount: e18ToDecimal(swap.executedAmountE18),
200
+ /** Source not spent; it never left the account. Final once `isTerminal`. */
201
+ unspentAmount: e18ToDecimal(swap.unspentAmountE18),
202
+ /** Destination received after fees. */
203
+ receivedAmount: e18ToDecimal(swap.receivedAmountE18),
204
+ /** Total fee, in the destination asset. */
205
+ fee: e18ToDecimal(swap.feeE18),
206
+ /** Spot orders, in placement order. */
207
+ orders: swap.orders,
208
+ createdAt: swap.createdAt ?? null
209
+ })));
210
+ //#endregion
211
+ export { CreateSwapInputSchema, GetSwapInputSchema, QuoteSwapInputSchema, SwapOrderSchema, SwapQuoteLegSchema, SwapQuoteSchema, SwapSchema };
212
+
213
+ //# sourceMappingURL=swap.schemas.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"swap.schemas.js","names":[],"sources":["../../../src/services/swap/swap.schemas.ts"],"sourcesContent":["import type { MessageInitShape } from \"@bufbuild/protobuf\";\nimport * as v from \"valibot\";\nimport type * as Proto from \"../../gen/swap/v1/swap_pb.js\";\nimport { PRICE_SCALE } from \"../../catalogs/readers.js\";\nimport {\n AccountScopeInputEntries,\n accountScopeToSubaccountId,\n type AccountScope,\n} from \"../../shared/account-scope.js\";\nimport {\n E18_SCALE,\n decimalInputToE18,\n scaledToDecimalOutput,\n} from \"../../shared/decimal-surface.js\";\nimport { enumLabel, enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport {\n idInputSchema,\n OptionalPublicIdSchema,\n OptionalTimestampMsSchema,\n PublicIdSchema,\n U128Schema,\n} from \"../../shared/schemas.js\";\nimport { formatId } from \"../../utils/base58-id.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport { msToTimestamp } from \"../../utils/timestamp.js\";\nimport { fromU128, toU128, type U128Value } from \"../../utils/u128.js\";\nimport { PositiveUint32InputSchema } from \"../shared.js\";\nimport {\n SwapOrderStatusCodec,\n SwapReasonCodec,\n SwapSideCodec,\n SwapStatusCodec,\n} from \"./swap.codecs.js\";\n\n// Sent exactly as given: trimming would make \" k \" and \"k\" the same idempotency key.\nconst IdempotencyKeySchema = v.pipe(v.string(), v.minLength(1));\n\n/** Positive decimal string → wire U128 in 18-decimal units. */\nfunction e18AmountInputSchema(field: string) {\n return v.pipe(\n v.string(),\n v.transform((value) => decimalInputToE18(field, value)),\n v.check((scaled) => scaled > 0n, `${field} must be greater than 0`),\n v.transform(toU128),\n );\n}\n\nconst SwapTermsInputEntries = {\n /** Defaults to the active subaccount, else the root account (or an API key's bound subaccount). */\n ...AccountScopeInputEntries,\n /** Unified asset ID spent, as in balances and internal transfers. */\n sourceAssetId: PositiveUint32InputSchema,\n /** Unified asset ID received. */\n destinationAssetId: PositiveUint32InputSchema,\n /**\n * Source amount to spend, as a decimal string (up to 18 decimal places). Only whole order\n * steps of the market trade; the rest stays on the account.\n */\n amount: e18AmountInputSchema(\"amount\"),\n};\n\ntype SwapTermsInput = {\n account?: AccountScope;\n sourceAssetId: number;\n destinationAssetId: number;\n amount: U128Value;\n};\n\nfunction toTerms({ account, sourceAssetId, destinationAssetId, amount }: SwapTermsInput) {\n return removeUndefined({\n subaccountId: accountScopeToSubaccountId(account),\n sourceAssetId,\n destinationAssetId,\n amount: { case: \"amountE18\" as const, value: amount },\n }) satisfies MessageInitShape<typeof Proto.SwapTermsSchema>;\n}\n\nexport const QuoteSwapInputSchema = v.pipe(\n v.strictObject({\n ...SwapTermsInputEntries,\n /** Accepted shortfall from the expected output, in basis points (1 to 1000). */\n maxSlippageBps: PositiveUint32InputSchema,\n }),\n v.transform(\n ({ maxSlippageBps, ...terms }) =>\n ({\n terms: toTerms(terms),\n maxSlippageBps,\n }) satisfies MessageInitShape<typeof Proto.QuoteSwapRequestSchema>,\n ),\n);\n\nexport type QuoteSwapInput = v.InferInput<typeof QuoteSwapInputSchema>;\n\nexport const CreateSwapInputSchema = v.pipe(\n v.strictObject({\n ...SwapTermsInputEntries,\n /**\n * Minimum destination amount after fees for the whole amount, as a decimal string;\n * usually the quote's `minAmountOut`.\n */\n minAmountOut: e18AmountInputSchema(\"minAmountOut\"),\n /** The accepted quote's `expiresAt` (epoch ms). Refused with `QUOTE_EXPIRED` after it. */\n quoteExpiresAt: v.pipe(v.number(), v.safeInteger(), v.gtValue(0)),\n /**\n * Caller-chosen key, unique per caller. The same key and request return the same swap;\n * the same key with a different request is `IDEMPOTENCY_CONFLICT`.\n */\n idempotencyKey: IdempotencyKeySchema,\n }),\n v.transform(\n ({ minAmountOut, quoteExpiresAt, idempotencyKey, ...terms }) =>\n ({\n idempotencyKey,\n terms: toTerms(terms),\n minAmountOutE18: minAmountOut,\n quoteExpiresAt: msToTimestamp(quoteExpiresAt),\n }) satisfies MessageInitShape<typeof Proto.CreateSwapRequestSchema>,\n ),\n);\n\nexport type CreateSwapInput = v.InferInput<typeof CreateSwapInputSchema>;\n\nexport const GetSwapInputSchema = v.pipe(\n v.union([\n v.strictObject({ swapId: idInputSchema(\"swapId\") }),\n v.strictObject({ idempotencyKey: IdempotencyKeySchema }),\n ]),\n v.transform(\n (input) =>\n ({\n selector:\n \"swapId\" in input\n ? { case: \"swapId\", value: input.swapId }\n : { case: \"idempotencyKey\", value: input.idempotencyKey },\n }) satisfies MessageInitShape<typeof Proto.GetSwapRequestSchema>,\n ),\n);\n\n/** Select a swap by `swapId`, or by the `idempotencyKey` it was created with. */\nexport type GetSwapInput = v.InferInput<typeof GetSwapInputSchema>;\n\n/** Wire `*_e18` U128 → exact decimal string; an unset amount is `\"0\"`. */\nfunction e18ToDecimal(value: U128Value | undefined): string {\n return scaledToDecimalOutput(fromU128(value), E18_SCALE);\n}\n\nconst AmountE18Schema = v.optional(U128Schema);\n\n/** Root account is `null`. */\nconst SubaccountIdOutputSchema = v.pipe(\n OptionalPublicIdSchema,\n v.transform((id) => id ?? null),\n);\n\nexport const SwapQuoteLegSchema = v.pipe(\n v.object({\n symbolId: v.number(),\n side: enumLabelSchema(SwapSideCodec.protoToOutput),\n averagePrice: v.string(),\n priceImpactBps: v.number(),\n takerFeeRatePercent: v.string(),\n feeE18: AmountE18Schema,\n feeAssetId: v.number(),\n }),\n v.transform(({ feeE18, ...leg }) => ({\n symbolId: leg.symbolId,\n side: leg.side,\n /** Estimated average fill price, quote per base, for display. */\n averagePrice: leg.averagePrice,\n /** Distance of `averagePrice` from the best price, in bps, rounded up. */\n priceImpactBps: leg.priceImpactBps,\n /** The account's spot taker fee rate in percent, e.g. `\"0.1\"`. */\n takerFeeRatePercent: leg.takerFeeRatePercent,\n /** Estimated fee, in `feeAssetId` (the asset the leg receives). */\n fee: e18ToDecimal(feeE18),\n feeAssetId: leg.feeAssetId,\n })),\n);\n\nexport type SwapQuoteLeg = v.InferOutput<typeof SwapQuoteLegSchema>;\n\nconst SwapTermsOutputSchema = v.object({\n subaccountId: v.bigint(),\n sourceAssetId: v.number(),\n destinationAssetId: v.number(),\n amount: v.object({ case: v.literal(\"amountE18\"), value: U128Schema }),\n});\n\nexport const SwapQuoteSchema = v.pipe(\n v.object({\n terms: SwapTermsOutputSchema,\n legs: v.array(SwapQuoteLegSchema),\n expectedAmountOutE18: AmountE18Schema,\n minAmountOutE18: AmountE18Schema,\n quotedAt: OptionalTimestampMsSchema,\n expiresAt: OptionalTimestampMsSchema,\n }),\n v.transform((quote) => ({\n /** Subaccount the quote is for; `null` for the root account. */\n subaccountId: quote.terms.subaccountId === 0n ? null : formatId(quote.terms.subaccountId),\n sourceAssetId: quote.terms.sourceAssetId,\n destinationAssetId: quote.terms.destinationAssetId,\n /** Source amount quoted. */\n amount: e18ToDecimal(quote.terms.amount.value),\n /** Markets the swap trades on, in order; a direct swap has one. */\n legs: quote.legs,\n /** Estimated destination amount after fees at current depth. */\n expectedAmountOut: e18ToDecimal(quote.expectedAmountOutE18),\n /** Destination amount after fees at the requested slippage; pass to `create`. */\n minAmountOut: e18ToDecimal(quote.minAmountOutE18),\n quotedAt: quote.quotedAt ?? null,\n /** 30 seconds after `quotedAt`; pass to `create` as `quoteExpiresAt`. */\n expiresAt: quote.expiresAt ?? null,\n })),\n);\n\n/** An estimate from current order-book depth. Reserves nothing; only `minAmountOut` binds. */\nexport type SwapQuote = v.InferOutput<typeof SwapQuoteSchema>;\n\nexport const SwapOrderSchema = v.pipe(\n v.object({\n orderId: v.bigint(),\n symbolId: v.number(),\n side: enumLabelSchema(SwapSideCodec.protoToOutput),\n leg: v.number(),\n status: enumLabelSchema(SwapOrderStatusCodec.protoToOutput),\n limitPriceTicks: v.bigint(),\n spentE18: AmountE18Schema,\n receivedE18: AmountE18Schema,\n feeE18: AmountE18Schema,\n }),\n v.transform((order) => ({\n /** Spot order ID once the market accepted it; `null` before. */\n orderId: order.orderId === 0n ? null : formatId(order.orderId),\n symbolId: order.symbolId,\n side: order.side,\n /** Zero-based position of the order's market in the route. */\n leg: order.leg,\n status: order.status,\n /** IOC limit price, quote per base: the worst price that nets the minimum rate. */\n limitPrice: scaledToDecimalOutput(order.limitPriceTicks, PRICE_SCALE),\n /** Spent in settled fills, fees in the spent asset included. */\n spent: e18ToDecimal(order.spentE18),\n /** Received in settled fills, after fees. */\n received: e18ToDecimal(order.receivedE18),\n /** Fee on settled fills, in the asset the order receives. */\n fee: e18ToDecimal(order.feeE18),\n })),\n);\n\nexport type SwapOrder = v.InferOutput<typeof SwapOrderSchema>;\n\nexport const SwapSchema = v.pipe(\n v.object({\n swapId: PublicIdSchema,\n idempotencyKey: v.string(),\n subaccountId: SubaccountIdOutputSchema,\n sourceAssetId: v.number(),\n destinationAssetId: v.number(),\n amountE18: AmountE18Schema,\n minAmountOutE18: AmountE18Schema,\n status: enumLabelSchema(SwapStatusCodec.protoToOutput),\n reason: v.number(),\n isTerminal: v.boolean(),\n executedAmountE18: AmountE18Schema,\n unspentAmountE18: AmountE18Schema,\n receivedAmountE18: AmountE18Schema,\n feeE18: AmountE18Schema,\n orders: v.array(SwapOrderSchema),\n createdAt: OptionalTimestampMsSchema,\n }),\n v.transform((swap) => ({\n swapId: swap.swapId,\n idempotencyKey: swap.idempotencyKey,\n /** Subaccount funding the swap; `null` for the root account. */\n subaccountId: swap.subaccountId,\n sourceAssetId: swap.sourceAssetId,\n destinationAssetId: swap.destinationAssetId,\n /** Source amount requested. */\n amount: e18ToDecimal(swap.amountE18),\n /** Minimum destination amount after fees for the whole amount. */\n minAmountOut: e18ToDecimal(swap.minAmountOutE18),\n status: swap.status,\n /** Why a `partially_completed` or `failed` swap did not trade everything; null otherwise. */\n reason: swap.reason === 0 ? null : enumLabel(SwapReasonCodec.protoToOutput, swap.reason),\n /** True once `status` is `completed`, `partially_completed` or `failed`; stop polling. */\n isTerminal: swap.isTerminal,\n /** Source spent in settled fills. */\n executedAmount: e18ToDecimal(swap.executedAmountE18),\n /** Source not spent; it never left the account. Final once `isTerminal`. */\n unspentAmount: e18ToDecimal(swap.unspentAmountE18),\n /** Destination received after fees. */\n receivedAmount: e18ToDecimal(swap.receivedAmountE18),\n /** Total fee, in the destination asset. */\n fee: e18ToDecimal(swap.feeE18),\n /** Spot orders, in placement order. */\n orders: swap.orders,\n createdAt: swap.createdAt ?? null,\n })),\n);\n\n/** One swap and its outcome. Amounts are decimal strings and count settled fills only. */\nexport type Swap = v.InferOutput<typeof SwapSchema>;\n"],"mappings":";;;;;;;;;;;;AAmCA,MAAM,uBAAuB,EAAE,KAAK,EAAE,OAAO,GAAG,EAAE,UAAU,CAAC,CAAC;;AAG9D,SAAS,qBAAqB,OAAe;CACzC,OAAO,EAAE,KACL,EAAE,O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AAQ,KAAK;;CAEb,QAAQ,KAAK,WAAW,IAAI,OAAO,UAAU,gBAAgB,eAAe,KAAK,MAAM;;CAEvF,YAAY,KAAK;;CAEjB,gBAAgB,aAAa,KAAK,iBAAiB;;CAEnD,eAAe,aAAa,KAAK,gBAAgB;;CAEjD,gBAAgB,aAAa,KAAK,iBAAiB;;CAEnD,KAAK,aAAa,KAAK,MAAM;;CAE7B,QAAQ,KAAK;CACb,WAAW,KAAK,aAAa;AACjC,EAAE,CACN"}
@@ -0,0 +1,3 @@
1
+ import { CreateSwapInput, GetSwapInput, QuoteSwapInput, Swap, SwapOrder, SwapQuote, SwapQuoteLeg } from "./swap.schemas.js";
2
+ import { SwapErrorCode, SwapOrderStatus, SwapReason, SwapStatus } from "./swap.codecs.js";
3
+ export type { CreateSwapInput, GetSwapInput, QuoteSwapInput, Swap, SwapErrorCode, SwapOrder, SwapOrderStatus, SwapQuote, SwapQuoteLeg, SwapReason, SwapStatus };
@@ -1,7 +1,7 @@
1
+ import { SystemService as SystemService$1 } from "../../gen/system/v1/system_pb.js";
1
2
  import { parse } from "../../shared/validation.js";
2
3
  import { removeUndefined } from "../../utils/remove-undefined.js";
3
4
  import { toConnectCallOptions } from "../../shared/request-options.js";
4
- import { SystemService as SystemService$1 } from "../../gen/system/v1/system_pb.js";
5
5
  import { ListStatusEventsInputSchema, ListStatusEventsResultSchema } from "./system.schemas.js";
6
6
  import { createClient } from "@connectrpc/connect";
7
7
  //#region src/services/system/system.ts
@@ -1,10 +1,10 @@
1
+ import { OrdersReadService, UserTradeBatchSchema } from "../../gen/orders/v1/orders_read_pb.js";
1
2
  import { parse } from "../../shared/validation.js";
2
3
  import { removeUndefined } from "../../utils/remove-undefined.js";
3
4
  import { toConnectCallOptions } from "../../shared/request-options.js";
4
5
  import { deliverBatch } from "../../shared/subscription-errors.js";
5
6
  import { createCatalogRefreshQueue, hasKnownSymbol, withCatalogRefresh } from "../../shared/decimal-surface.js";
6
7
  import { resolveAccountScopedInput } from "../subaccount-resolver.js";
7
- import { OrdersReadService, UserTradeBatchSchema } from "../../gen/orders/v1/orders_read_pb.js";
8
8
  import { GetUserTradesInputSchema, formatUserTrade } from "./trades.schemas.js";
9
9
  import { createOrderTransferSchema } from "../orders/orders-output.schemas.js";
10
10
  import { connectReadyGatedProtoChannel } from "../../realtime/ready-gated-subscription.js";
@@ -169,7 +169,7 @@ declare const GetUserTradesInputSchema: v.SchemaWithPipe<readonly [v.UnionSchema
169
169
  readonly orderId: v.OptionalSchema<v.NeverSchema<undefined>, undefined>;
170
170
  readonly lineageId: v.SchemaWithPipe<readonly [v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>, v.TransformAction<string, bigint>]>, v.CheckAction<bigint, `${string} must be greater than zero`>]>;
171
171
  readonly throughGeneration: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.MinValueAction<number, 1, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>, undefined>;
172
- }, undefined>], undefined>], ({ input }: v.UnionIssue<v.StringIssue | v.NumberIssue | v.BooleanIssue | v.MinLengthIssue<string, 1> | v.IntegerIssue<number> | v.CheckIssue<bigint> | v.StrictObjectIssue | v.MinValueIssue<number, 1> | v.GtValueIssue<number, 0> | v.MaxValueIssue<number, 4294967295> | v.PicklistIssue | v.UnionIssue<v.StringIssue | v.MinLengthIssue<string, 1> | v.StrictObjectIssue | v.PicklistIssue> | v.MaxValueIssue<number, 1000> | v.NeverIssue | v.UnionIssue<v.StringIssue | v.NumberIssue | v.BooleanIssue | v.MinLengthIssue<string, 1> | v.IntegerIssue<number> | v.CheckIssue<bigint> | v.StrictObjectIssue | v.MinValueIssue<number, 1> | v.GtValueIssue<number, 0> | v.MaxValueIssue<number, 4294967295> | v.PicklistIssue | v.UnionIssue<v.StringIssue | v.MinLengthIssue<string, 1> | v.StrictObjectIssue | v.PicklistIssue> | v.MaxValueIssue<number, 1000> | v.NeverIssue>>) => "Provide at most one of orderId or lineageId" | "throughGeneration requires lineageId" | "symbolId is required when afterMatchId is set" | "Invalid trade filters">, v.TransformAction<{
172
+ }, undefined>], undefined>], ({ input }: v.UnionIssue<v.NumberIssue | v.StringIssue | v.BooleanIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.PicklistIssue | v.UnionIssue<v.StringIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.PicklistIssue> | v.IntegerIssue<number> | v.GtValueIssue<number, 0> | v.MaxValueIssue<number, 4294967295> | v.MinValueIssue<number, 1> | v.CheckIssue<bigint> | v.MaxValueIssue<number, 1000> | v.NeverIssue | v.UnionIssue<v.NumberIssue | v.StringIssue | v.BooleanIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.PicklistIssue | v.UnionIssue<v.StringIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.PicklistIssue> | v.IntegerIssue<number> | v.GtValueIssue<number, 0> | v.MaxValueIssue<number, 4294967295> | v.MinValueIssue<number, 1> | v.CheckIssue<bigint> | v.MaxValueIssue<number, 1000> | v.NeverIssue>>) => "Provide at most one of orderId or lineageId" | "throughGeneration requires lineageId" | "symbolId is required when afterMatchId is set" | "Invalid trade filters">, v.TransformAction<{
173
173
  symbolId?: number | undefined;
174
174
  afterMatchId?: undefined;
175
175
  side?: Side.BUY | Side.SELL | undefined;
@@ -3,7 +3,7 @@ import { ApiKeyEd25519AuthProvider, AuthApiTransports, JwtAuthProvider } from ".
3
3
  import { PolyesterMutationOptions, PolyesterRequestOptions } from "../../shared/request-options.js";
4
4
  import { SubaccountResolver } from "../subaccount-resolver.js";
5
5
  import { SdkScales } from "../../shared/decimal-surface.js";
6
- import { CreateTradingWithdrawResult, CreateTradingWithdrawToExternalChainInput, CreateTradingWithdrawToFundingInput, GetWalletBalancesInput, GetWalletBalancesResult, ValidateWithdrawDestinationInput, ValidateWithdrawDestinationResult } from "./trading-withdraws.schemas.js";
6
+ import { CreateTradingToFundingBatchInput, CreateTradingToFundingBatchResult, CreateTradingWithdrawResult, CreateTradingWithdrawToExternalChainInput, CreateTradingWithdrawToFundingInput, GetWalletBalancesInput, GetWalletBalancesResult, ValidateWithdrawDestinationInput, ValidateWithdrawDestinationResult } from "./trading-withdraws.schemas.js";
7
7
  import { Address, Hex } from "viem";
8
8
  //#region src/services/trading-withdraws/trading-withdraws.d.ts
9
9
  type TradingWithdrawWalletSigner = {
@@ -25,6 +25,20 @@ type CreateTradingWithdrawToFundingServiceInput = CreateTradingWithdrawToFunding
25
25
  type CreateTradingWithdrawToExternalChainServiceInput = CreateTradingWithdrawToExternalChainInput & {
26
26
  walletSigner?: TradingWithdrawWalletSigner;
27
27
  };
28
+ type CreateTradingToFundingBatchServiceInput = CreateTradingToFundingBatchInput & {
29
+ walletSigner: TradingWithdrawWalletSigner;
30
+ };
31
+ /**
32
+ * A signed batch. `submit` always sends the same signed request, so it can be repeated after
33
+ * an MFA step-up, or after an `aborted` or `unavailable` answer: the server then answers the
34
+ * first outcome for the key. It never signs again; a refused batch is final for its key, so
35
+ * moving the funds needs a new batch with a new `idempotencyKey`.
36
+ */
37
+ type PreparedTradingToFundingBatch = Readonly<{
38
+ /** When the backend stops accepting a new submission of this batch. */
39
+ deadline: Date;
40
+ submit: (options?: PolyesterMutationOptions) => Promise<CreateTradingToFundingBatchResult>;
41
+ }>;
28
42
  type PreparedTradingWithdraw = Readonly<{
29
43
  /** When the backend stops accepting the currently signed request. */
30
44
  deadline: Date;
@@ -76,7 +90,20 @@ declare class TradingWithdrawsService {
76
90
  * be resubmitted after backend-directed authorization such as MFA step-up.
77
91
  */
78
92
  prepareToExternalChain(input: CreateTradingWithdrawToExternalChainServiceInput): Promise<PreparedTradingWithdraw>;
93
+ /**
94
+ * Moves up to 10 amounts from one Trading account to Funding accounts with one wallet
95
+ * signature and one MFA check. All legs are accepted or none, and an accepted batch is paid
96
+ * as one or refunded in full. When every leg goes to the caller's own accounts, an
97
+ * MFA-elevated session is enough; any other leg needs a fresh `stepUpToken`. Wallet signers
98
+ * only.
99
+ */
100
+ createToFundingBatch(input: CreateTradingToFundingBatchServiceInput, options?: PolyesterMutationOptions): Promise<CreateTradingToFundingBatchResult>;
101
+ /**
102
+ * Builds and signs a Trading-to-Funding batch once, so the exact request can be resubmitted
103
+ * after an MFA step-up or a transient failure.
104
+ */
105
+ prepareToFundingBatch(input: CreateTradingToFundingBatchServiceInput): Promise<PreparedTradingToFundingBatch>;
79
106
  }
80
107
  //#endregion
81
- export { CreateTradingWithdrawToExternalChainServiceInput, CreateTradingWithdrawToFundingServiceInput, PreparedTradingWithdraw, TradingWithdrawSigningConfig, TradingWithdrawWalletSigner, TradingWithdrawsService };
108
+ export { CreateTradingToFundingBatchServiceInput, CreateTradingWithdrawToExternalChainServiceInput, CreateTradingWithdrawToFundingServiceInput, PreparedTradingToFundingBatch, PreparedTradingWithdraw, TradingWithdrawSigningConfig, TradingWithdrawWalletSigner, TradingWithdrawsService };
82
109
  //# sourceMappingURL=trading-withdraws.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"trading-withdraws.d.ts","names":[],"sources":["../../../src/services/trading-withdraws/trading-withdraws.ts"],"mappings":";;;;;;;;KA8CY;EACR;EACA;;;;;EAKA,cAAc,oBAAoB,QAAQ;;KAGlC;EACR;EACA,uBAAuB;;KAGf,6CAA6C;EACrD,eAAe;;KAGP,mDACR;EACI,eAAe;;KAGX,0BAA0B;;EAElC,UAAU;;;;;;EAMV;;;;;;EAMA,SAAS,UAAU,6BAA6B,QAAQ;;;;;cAoG/C;;EAaL,YAAA,YAAY,mBACZ,UAAU,gCACV,eAAe,8BACf,QAAQ,WACR,UAAU,eACV,OAAO,kBAAkB;;;;;;;EAmBvB,kBACF,QAAO,wBACP,UAAU,0BACX,QAAQ;;;;EAeL,oBACF,OAAO,kCACP,UAAU,0BACX,QAAQ;;;;EAYL,gBACF,OAAO,4CACP,UAAU,2BACX,QAAQ;;;;;EASL,iBACF,OAAO,6CACR,QAAQ;;;;EAWL,sBACF,OAAO,kDACP,UAAU,2BACX,QAAQ;;;;;EASL,uBACF,OAAO,mDACR,QAAQ"}
1
+ {"version":3,"file":"trading-withdraws.d.ts","names":[],"sources":["../../../src/services/trading-withdraws/trading-withdraws.ts"],"mappings":";;;;;;;;KAsDY;EACR;EACA;;;;;EAKA,cAAc,oBAAoB,QAAQ;;KAGlC;EACR;EACA,uBAAuB;;KAGf,6CAA6C;EACrD,eAAe;;KAGP,mDACR;EACI,eAAe;;KAGX,0CAA0C;EAClD,cAAc;;;;;;;;KASN,gCAAgC;;EAExC,UAAU;EACV,SAAS,UAAU,6BAA6B,QAAQ;;KAGhD,0BAA0B;;EAElC,UAAU;;;;;;EAMV;;;;;;EAMA,SAAS,UAAU,6BAA6B,QAAQ;;;;;cAqG/C;;EAcL,YAAA,YAAY,mBACZ,UAAU,gCACV,eAAe,8BACf,QAAQ,WACR,UAAU,eACV,OAAO,kBAAkB;;;;;;;EAoBvB,kBACF,QAAO,wBACP,UAAU,0BACX,QAAQ;;;;EAeL,oBACF,OAAO,kCACP,UAAU,0BACX,QAAQ;;;;EAYL,gBACF,OAAO,4CACP,UAAU,2BACX,QAAQ;;;;;EASL,iBACF,OAAO,6CACR,QAAQ;;;;EAWL,sBACF,OAAO,kDACP,UAAU,2BACX,QAAQ;;;;;EASL,uBACF,OAAO,mDACR,QAAQ;;;;;;;;EAeL,qBACF,OAAO,yCACP,UAAU,2BACX,QAAQ;;;;;EASL,sBACF,OAAO,0CACR,QAAQ"}
@@ -1,3 +1,4 @@
1
+ import { TradingWithdrawIntentPayloadSchema, WithdrawService } from "../../gen/chain/withdraw/v1/withdraw_pb.js";
1
2
  import { ConfigurationError, ValidationError } from "../../shared/errors.js";
2
3
  import { signApiKeyEd25519Payload } from "../../shared/transports.js";
3
4
  import { checksumEvmAddress, evmHexToBytes } from "../../utils/evm.js";
@@ -5,10 +6,10 @@ import { parse } from "../../shared/validation.js";
5
6
  import { removeUndefined } from "../../utils/remove-undefined.js";
6
7
  import { toConnectCallOptions } from "../../shared/request-options.js";
7
8
  import { idToBigInt } from "../../utils/base58-id.js";
9
+ import { toU128 } from "../../utils/u128.js";
8
10
  import { resolveAccountScopedInput } from "../subaccount-resolver.js";
9
- import { TradingWithdrawIntentPayloadSchema, WithdrawService } from "../../gen/chain/withdraw/v1/withdraw_pb.js";
10
- import { CreateTradingWithdrawResultSchema, CreateWalletTradingWithdrawResultSchema, GetWalletBalancesInputSchema, GetWalletBalancesResultSchema, ValidateWithdrawDestinationInputSchema, ValidateWithdrawDestinationResultSchema, createCreateTradingWithdrawToExternalChainInputSchema, createCreateTradingWithdrawToFundingInputSchema, renewTradingWithdrawPayload } from "./trading-withdraws.schemas.js";
11
- import { buildTradingWithdrawWalletMessage } from "./wallet-message.js";
11
+ import { CreateTradingToFundingBatchResultSchema, CreateTradingWithdrawResultSchema, CreateWalletTradingWithdrawResultSchema, GetWalletBalancesInputSchema, GetWalletBalancesResultSchema, ValidateWithdrawDestinationInputSchema, ValidateWithdrawDestinationResultSchema, createCreateTradingToFundingBatchInputSchema, createCreateTradingWithdrawToExternalChainInputSchema, createCreateTradingWithdrawToFundingInputSchema, renewTradingWithdrawPayload } from "./trading-withdraws.schemas.js";
12
+ import { buildTradingToFundingBatchWalletMessage, buildTradingWithdrawWalletMessage } from "./wallet-message.js";
12
13
  import { create, toBinary } from "@bufbuild/protobuf";
13
14
  import { createClient } from "@connectrpc/connect";
14
15
  //#region src/services/trading-withdraws/trading-withdraws.ts
@@ -30,6 +31,10 @@ function preparedWithdraw(signed, resign) {
30
31
  }
31
32
  };
32
33
  }
34
+ function walletSignatureBytes(signature) {
35
+ if (!/^0x[0-9a-fA-F]{128}(?:00|01|1[bBcC])$/.test(signature)) throw new ValidationError("Trading withdraw wallet signature must be 65 bytes with recovery byte 0, 1, 27, or 28.");
36
+ return evmHexToBytes(signature);
37
+ }
33
38
  function resolveTradingWithdrawTargetAccountId(params) {
34
39
  if (params.subaccountId !== void 0) return params.subaccountId;
35
40
  return idToBigInt(params.rootAccountId, "targetAccountId");
@@ -51,17 +56,15 @@ async function resolveTradingWithdrawSigningConfig(params) {
51
56
  async function resolveWalletSignature(params) {
52
57
  const signerWallet = params.walletSigner.signerWallet.trim().toLowerCase();
53
58
  const accountId = idToBigInt(params.walletSigner.accountId, "accountId");
54
- const signature = await params.walletSigner.signMessage(buildTradingWithdrawWalletMessage({
55
- signingConfig: params.signingConfig,
56
- payload: params.payload,
57
- signerWallet,
58
- accountId,
59
- targetAccountId: params.targetAccountId
60
- }));
61
- if (!/^0x[0-9a-fA-F]{128}(?:00|01|1[bBcC])$/.test(signature)) throw new ValidationError("Trading withdraw wallet signature must be 65 bytes with recovery byte 0, 1, 27, or 28.");
62
59
  return {
63
60
  signerWallet,
64
- payloadSignature: evmHexToBytes(signature)
61
+ payloadSignature: walletSignatureBytes(await params.walletSigner.signMessage(buildTradingWithdrawWalletMessage({
62
+ signingConfig: params.signingConfig,
63
+ payload: params.payload,
64
+ signerWallet,
65
+ accountId,
66
+ targetAccountId: params.targetAccountId
67
+ })))
65
68
  };
66
69
  }
67
70
  /**
@@ -76,6 +79,7 @@ var TradingWithdrawsService = class {
76
79
  #auth;
77
80
  #toFundingInputSchema;
78
81
  #toExternalChainInputSchema;
82
+ #toFundingBatchInputSchema;
79
83
  constructor(transports, resolver, signingConfig, scales, catalog, auth) {
80
84
  this.#client = createClient(WithdrawService, transports.authApi);
81
85
  this.#auth = auth;
@@ -85,6 +89,7 @@ var TradingWithdrawsService = class {
85
89
  this.#scales = scales;
86
90
  this.#toFundingInputSchema = createCreateTradingWithdrawToFundingInputSchema(scales);
87
91
  this.#toExternalChainInputSchema = createCreateTradingWithdrawToExternalChainInputSchema(scales);
92
+ this.#toFundingBatchInputSchema = createCreateTradingToFundingBatchInputSchema(scales);
88
93
  }
89
94
  /**
90
95
  * Reads the zTokens the account's smart account wallet holds on Polyester Chain, such as a
@@ -139,6 +144,64 @@ var TradingWithdrawsService = class {
139
144
  const validated = parse(this.#toExternalChainInputSchema, resolvedInput);
140
145
  return this.#prepareWithdraw(validated, walletSigner);
141
146
  }
147
+ /**
148
+ * Moves up to 10 amounts from one Trading account to Funding accounts with one wallet
149
+ * signature and one MFA check. All legs are accepted or none, and an accepted batch is paid
150
+ * as one or refunded in full. When every leg goes to the caller's own accounts, an
151
+ * MFA-elevated session is enough; any other leg needs a fresh `stepUpToken`. Wallet signers
152
+ * only.
153
+ */
154
+ async createToFundingBatch(input, options) {
155
+ return (await this.prepareToFundingBatch(input)).submit(options);
156
+ }
157
+ /**
158
+ * Builds and signs a Trading-to-Funding batch once, so the exact request can be resubmitted
159
+ * after an MFA step-up or a transient failure.
160
+ */
161
+ async prepareToFundingBatch(input) {
162
+ await this.#scales.ready();
163
+ const { walletSigner, ...inputForValidation } = input;
164
+ const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);
165
+ const validated = parse(this.#toFundingBatchInputSchema, resolvedInput);
166
+ const signingConfig = await resolveTradingWithdrawSigningConfig({
167
+ fallback: this.#signingConfig,
168
+ catalog: this.#catalog
169
+ });
170
+ const signerWallet = walletSigner.signerWallet.trim().toLowerCase();
171
+ const signature = await walletSigner.signMessage(buildTradingToFundingBatchWalletMessage({
172
+ signingConfig,
173
+ signerWallet,
174
+ accountId: idToBigInt(walletSigner.accountId, "accountId"),
175
+ targetAccountId: resolveTradingWithdrawTargetAccountId({
176
+ subaccountId: validated.subaccountId,
177
+ rootAccountId: walletSigner.accountId
178
+ }),
179
+ deadlineTsSec: validated.deadlineTsSec,
180
+ nonce: validated.nonce,
181
+ idempotencyKey: validated.idempotencyKey,
182
+ legs: validated.legs
183
+ }));
184
+ const request = removeUndefined({
185
+ legs: validated.legs.map((leg) => ({
186
+ assetId: leg.assetId,
187
+ amountE18: toU128(leg.amountE18),
188
+ destinationAddress: leg.destinationAddress
189
+ })),
190
+ subaccountId: validated.subaccountId,
191
+ deadlineTsSec: validated.deadlineTsSec,
192
+ nonce: toU128(validated.nonce),
193
+ idempotencyKey: validated.idempotencyKey,
194
+ signerWallet,
195
+ payloadSignature: walletSignatureBytes(signature)
196
+ });
197
+ return {
198
+ deadline: /* @__PURE__ */ new Date(Number(validated.deadlineTsSec) * 1e3),
199
+ submit: async (options) => {
200
+ const response = await this.#client.createWalletTradingToFundingBatch(request, toConnectCallOptions(options));
201
+ return parse(CreateTradingToFundingBatchResultSchema, response);
202
+ }
203
+ };
204
+ }
142
205
  async #prepareWithdraw(validated, walletSigner) {
143
206
  if (walletSigner) {
144
207
  const signingConfig = await resolveTradingWithdrawSigningConfig({
@@ -1 +1 @@
1
- {"version":3,"file":"trading-withdraws.js","names":["#client","Proto.WithdrawService","#auth","#resolver","#signingConfig","#catalog","#scales","#toFundingInputSchema","#toExternalChainInputSchema","#prepareWithdraw","Proto.TradingWithdrawIntentPayloadSchema"],"sources":["../../../src/services/trading-withdraws/trading-withdraws.ts"],"sourcesContent":["import { ConfigurationError, ValidationError } from \"../../shared/errors.js\";\nimport { create, toBinary } from \"@bufbuild/protobuf\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport type { Address, Hex } from \"viem\";\nimport { checksumEvmAddress, evmHexToBytes } from \"../../utils/evm.js\";\nimport type { ClientCatalog } from \"../../catalogs/types.js\";\nimport * as Proto from \"../../gen/chain/withdraw/v1/withdraw_pb.js\";\nimport { idToBigInt } from \"../../utils/base58-id.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport {\n signApiKeyEd25519Payload,\n type ApiKeyEd25519AuthProvider,\n type AuthApiTransports,\n type JwtAuthProvider,\n} from \"../../shared/transports.js\";\nimport { parse } from \"../../shared/validation.js\";\nimport {\n createCreateTradingWithdrawToExternalChainInputSchema,\n createCreateTradingWithdrawToFundingInputSchema,\n CreateTradingWithdrawResultSchema,\n CreateWalletTradingWithdrawResultSchema,\n GetWalletBalancesInputSchema,\n GetWalletBalancesResultSchema,\n ValidateWithdrawDestinationInputSchema,\n ValidateWithdrawDestinationResultSchema,\n renewTradingWithdrawPayload,\n type CreateTradingWithdrawResult,\n type CreateTradingWithdrawToExternalChainInput,\n type CreateTradingWithdrawToExternalChainRequest,\n type CreateTradingWithdrawToFundingInput,\n type CreateTradingWithdrawToFundingRequest,\n type GetWalletBalancesInput,\n type GetWalletBalancesResult,\n type TradingWithdrawIntentPayloadRequest,\n type ValidateWithdrawDestinationInput,\n type ValidateWithdrawDestinationResult,\n} from \"./trading-withdraws.schemas.js\";\nimport { buildTradingWithdrawWalletMessage } from \"./wallet-message.js\";\n\nexport type TradingWithdrawWalletSigner = {\n signerWallet: string;\n accountId: string;\n /**\n * Signs the UTF-8 message directly using EIP-191 personal_sign, without pre-hashing or switching chains.\n * For a viem account, use `(message) => account.signMessage({ message })`.\n */\n signMessage: (message: string) => Promise<Hex>;\n};\n\nexport type TradingWithdrawSigningConfig = {\n chainId: number;\n tradingGatewayAddress: Address;\n};\n\nexport type CreateTradingWithdrawToFundingServiceInput = CreateTradingWithdrawToFundingInput & {\n walletSigner?: TradingWithdrawWalletSigner;\n};\n\nexport type CreateTradingWithdrawToExternalChainServiceInput =\n CreateTradingWithdrawToExternalChainInput & {\n walletSigner?: TradingWithdrawWalletSigner;\n };\n\nexport type PreparedTradingWithdraw = Readonly<{\n /** When the backend stops accepting the currently signed request. */\n deadline: Date;\n /**\n * True once the deadline is less than a minute away. The withdraw signs again on\n * `submit` from then on, so callers can keep resubmitting the same prepared withdraw,\n * e.g. after a slow MFA step-up.\n */\n isExpired: () => boolean;\n /**\n * Submits the payload and signature produced during preparation. Repeated calls only\n * change transport options such as the step-up token, unless the deadline is near: the\n * withdraw then signs a fresh deadline and nonce with the same idempotency key.\n */\n submit: (options?: PolyesterMutationOptions) => Promise<CreateTradingWithdrawResult>;\n}>;\n\ntype SignedTradingWithdraw = {\n payload: TradingWithdrawIntentPayloadRequest;\n send: (options?: PolyesterMutationOptions) => Promise<CreateTradingWithdrawResult>;\n};\n\n// Leaves room for the request to reach the backend and for modest clock skew.\nconst PREPARED_WITHDRAW_EXPIRY_MARGIN_MS = 60_000;\n\nfunction deadlineMs(payload: TradingWithdrawIntentPayloadRequest): number {\n return Number(payload.deadlineTsSec) * 1000;\n}\n\nfunction preparedWithdraw(\n signed: SignedTradingWithdraw,\n resign: (payload: TradingWithdrawIntentPayloadRequest) => Promise<SignedTradingWithdraw>,\n): PreparedTradingWithdraw {\n let current = signed;\n const isExpired = () =>\n Date.now() >= deadlineMs(current.payload) - PREPARED_WITHDRAW_EXPIRY_MARGIN_MS;\n return {\n get deadline() {\n return new Date(deadlineMs(current.payload));\n },\n isExpired,\n submit: async (options) => {\n if (isExpired()) {\n current = await resign(renewTradingWithdrawPayload(current.payload));\n }\n return current.send(options);\n },\n };\n}\n\ntype TradingWithdrawRequest =\n | CreateTradingWithdrawToFundingRequest\n | CreateTradingWithdrawToExternalChainRequest;\n\nfunction resolveTradingWithdrawTargetAccountId(params: {\n subaccountId: bigint | undefined;\n rootAccountId: string;\n}): bigint {\n if (params.subaccountId !== undefined) return params.subaccountId;\n return idToBigInt(params.rootAccountId, \"targetAccountId\");\n}\n\nasync function resolveTradingWithdrawSigningConfig(params: {\n fallback: TradingWithdrawSigningConfig;\n catalog?: ClientCatalog;\n}): Promise<TradingWithdrawSigningConfig> {\n if (!params.catalog) return params.fallback;\n\n try {\n await params.catalog.ensureReady();\n const gateway = params.catalog.zipper.getContractByName(\"tradingGateway\");\n const address = gateway?.address?.trim();\n if (!address?.startsWith(\"0x\")) return params.fallback;\n\n return {\n chainId: params.fallback.chainId,\n tradingGatewayAddress: checksumEvmAddress(address),\n };\n } catch {\n return params.fallback;\n }\n}\n\nasync function resolveWalletSignature(params: {\n signingConfig: TradingWithdrawSigningConfig;\n payload: TradingWithdrawIntentPayloadRequest;\n walletSigner: TradingWithdrawWalletSigner;\n targetAccountId: bigint;\n}): Promise<{ signerWallet: string; payloadSignature: Uint8Array }> {\n const signerWallet = params.walletSigner.signerWallet.trim().toLowerCase();\n const accountId = idToBigInt(params.walletSigner.accountId, \"accountId\");\n const signature = await params.walletSigner.signMessage(\n buildTradingWithdrawWalletMessage({\n signingConfig: params.signingConfig,\n payload: params.payload,\n signerWallet,\n accountId,\n targetAccountId: params.targetAccountId,\n }),\n );\n if (!/^0x[0-9a-fA-F]{128}(?:00|01|1[bBcC])$/.test(signature)) {\n throw new ValidationError(\n \"Trading withdraw wallet signature must be 65 bytes with recovery byte 0, 1, 27, or 28.\",\n );\n }\n return {\n signerWallet,\n payloadSignature: evmHexToBytes(signature),\n };\n}\n\n/**\n * Creates durable Trading withdrawal intents, signed by the client's API key or a wallet (EIP-191).\n */\nexport class TradingWithdrawsService {\n #client: Client<typeof Proto.WithdrawService>;\n #resolver?: SubaccountResolver;\n #signingConfig: TradingWithdrawSigningConfig;\n #catalog?: ClientCatalog;\n #scales: SdkScales;\n #auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider;\n #toFundingInputSchema: ReturnType<typeof createCreateTradingWithdrawToFundingInputSchema>;\n #toExternalChainInputSchema: ReturnType<\n typeof createCreateTradingWithdrawToExternalChainInputSchema\n >;\n\n constructor(\n transports: AuthApiTransports,\n resolver: SubaccountResolver | undefined,\n signingConfig: TradingWithdrawSigningConfig,\n scales: SdkScales,\n catalog?: ClientCatalog,\n auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider,\n ) {\n this.#client = createClient(Proto.WithdrawService, transports.authApi);\n this.#auth = auth;\n this.#resolver = resolver;\n this.#signingConfig = signingConfig;\n this.#catalog = catalog;\n this.#scales = scales;\n this.#toFundingInputSchema = createCreateTradingWithdrawToFundingInputSchema(scales);\n this.#toExternalChainInputSchema =\n createCreateTradingWithdrawToExternalChainInputSchema(scales);\n }\n\n /**\n * Reads the zTokens the account's smart account wallet holds on Polyester Chain, such as a\n * rejected withdrawal's refund (see the lifecycle step's `refundAddress`), which stays there\n * until moved. Balances that could not be read are listed in `unavailableAssets`, not\n * reported as zero. API keys need `read-balances`.\n */\n async getWalletBalances(\n input: GetWalletBalancesInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<GetWalletBalancesResult> {\n const request = parse(\n GetWalletBalancesInputSchema,\n resolveAccountScopedInput(input, this.#resolver),\n );\n const response = await this.#client.getWalletBalances(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(GetWalletBalancesResultSchema, response);\n }\n\n /**\n * Checks whether an external-chain destination can receive a withdrawal without creating, signing, or reserving one. API keys need `read-withdraw-validation`.\n */\n async validateDestination(\n input: ValidateWithdrawDestinationInput,\n options?: PolyesterRequestOptions,\n ): Promise<ValidateWithdrawDestinationResult> {\n const request = parse(ValidateWithdrawDestinationInputSchema, input);\n const response = await this.#client.validateWithdrawDestination(\n request,\n toConnectCallOptions(options),\n );\n return parse(ValidateWithdrawDestinationResultSchema, response);\n }\n\n /**\n * Builds a Trading-to-Funding withdraw intent payload with asset id, decimal amount, destination address, five-minute deadline, nonce, and idempotency key. If a wallet signer is provided, it signs the canonical EIP-191 message and calls the wallet endpoint; otherwise the client's API key signs the payload for the API-key endpoint.\n */\n async createToFunding(\n input: CreateTradingWithdrawToFundingServiceInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTradingWithdrawResult> {\n const prepared = await this.prepareToFunding(input);\n return prepared.submit(options);\n }\n\n /**\n * Builds and signs a Trading-to-Funding withdrawal once so the exact request can be\n * resubmitted after backend-directed authorization such as MFA step-up.\n */\n async prepareToFunding(\n input: CreateTradingWithdrawToFundingServiceInput,\n ): Promise<PreparedTradingWithdraw> {\n await this.#scales.ready();\n const { walletSigner, ...inputForValidation } = input;\n const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);\n const validated = parse(this.#toFundingInputSchema, resolvedInput);\n return this.#prepareWithdraw(validated, walletSigner);\n }\n\n /**\n * Builds a Trading-to-external-chain withdraw intent payload with asset id, decimal gross amount, destination network, destination address, five-minute deadline, nonce, and idempotency key. If a wallet signer is provided, it signs the canonical EIP-191 message and calls the wallet endpoint; otherwise the client's API key signs the payload for the API-key endpoint.\n */\n async createToExternalChain(\n input: CreateTradingWithdrawToExternalChainServiceInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTradingWithdrawResult> {\n const prepared = await this.prepareToExternalChain(input);\n return prepared.submit(options);\n }\n\n /**\n * Builds and signs a Trading-to-external-chain withdrawal once so the exact request can\n * be resubmitted after backend-directed authorization such as MFA step-up.\n */\n async prepareToExternalChain(\n input: CreateTradingWithdrawToExternalChainServiceInput,\n ): Promise<PreparedTradingWithdraw> {\n await this.#scales.ready();\n const { walletSigner, ...inputForValidation } = input;\n const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);\n const validated = parse(this.#toExternalChainInputSchema, resolvedInput);\n return this.#prepareWithdraw(validated, walletSigner);\n }\n\n async #prepareWithdraw(\n validated: TradingWithdrawRequest,\n walletSigner: TradingWithdrawWalletSigner | undefined,\n ): Promise<PreparedTradingWithdraw> {\n if (walletSigner) {\n const signingConfig = await resolveTradingWithdrawSigningConfig({\n fallback: this.#signingConfig,\n catalog: this.#catalog,\n });\n const targetAccountId = resolveTradingWithdrawTargetAccountId({\n subaccountId: validated.subaccountId,\n rootAccountId: walletSigner.accountId,\n });\n const sign = async (\n payload: TradingWithdrawIntentPayloadRequest,\n ): Promise<SignedTradingWithdraw> => {\n const walletSignature = await resolveWalletSignature({\n signingConfig,\n payload,\n walletSigner,\n targetAccountId,\n });\n const request = removeUndefined({\n payload,\n subaccountId: validated.subaccountId,\n signerWallet: walletSignature.signerWallet,\n payloadSignature: walletSignature.payloadSignature,\n });\n return {\n payload,\n send: async (options) => {\n const response = await this.#client.createWalletTradingWithdraw(\n request,\n toConnectCallOptions(options),\n );\n return parse(CreateWalletTradingWithdrawResultSchema, response);\n },\n };\n };\n return preparedWithdraw(await sign(validated.payload), sign);\n }\n\n const auth = this.#auth;\n if (auth?.kind !== \"api-key-ed25519\") {\n throw new ConfigurationError(\n \"Trading withdraw requires a wallet signer or API-key auth.\",\n );\n }\n // CreateTradingWithdrawRequest has no subaccount field: the API key decides the account.\n if (validated.subaccountId !== undefined) {\n throw new ValidationError(\n 'API-key trading withdraws cannot target a subaccount. Use `account: \"main\"` or a wallet signer.',\n );\n }\n const sign = async (\n payload: TradingWithdrawIntentPayloadRequest,\n ): Promise<SignedTradingWithdraw> => {\n // The backend verifies the signature over the payload's protobuf encoding.\n const payloadSignature = await signApiKeyEd25519Payload(\n auth,\n toBinary(\n Proto.TradingWithdrawIntentPayloadSchema,\n create(Proto.TradingWithdrawIntentPayloadSchema, payload),\n ),\n );\n return {\n payload,\n send: async (options) => {\n const response = await this.#client.createTradingWithdraw(\n { payload, payloadSignature },\n toConnectCallOptions(options),\n );\n return parse(CreateTradingWithdrawResultSchema, response);\n },\n };\n };\n return preparedWithdraw(await sign(validated.payload), sign);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AA6FA,MAAM,qCAAqC;AAE3C,SAAS,WAAW,SAAsD;CACtE,OAAO,OAAO,QAAQ,aAAa,IAAI;AAC3C;AAEA,SAAS,iBACL,QACA,QACuB;CACvB,IAAI,UAAU;CACd,MAAM,kBACF,KAAK,IAAI,KAAK,WAAW,QAAQ,OAAO,IAAI;CAChD,OAAO;EACH,IAAI,WAAW;GACX,OAAO,IAAI,KAAK,WAAW,QAAQ,OAAO,CAAC;EAC/C;EACA;EACA,QAAQ,OAAO,YAAY;GACvB,IAAI,UAAU,GACV,UAAU,MAAM,OAAO,4BAA4B,QAAQ,OAAO,CAAC;GAEvE,OAAO,QAAQ,KAAK,OAAO;EAC/B;CACJ;AACJ;AAMA,SAAS,sCAAsC,QAGpC;CACP,IAAI,OAAO,iBAAiB,KAAA,GAAW,OAAO,OAAO;CACrD,OAAO,WAAW,OAAO,eAAe,iBAAiB;AAC7D;AAEA,eAAe,oCAAoC,QAGT;CACtC,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IACD,MAAM,UAAU,gBAAgB;KAC5B;KACA,cAAc,UAAU;KACxB,cAAc,gBAAgB;KAC9B,kBAAkB,gBAAgB;IACtC,CAAC;IACD,OAAO;KACH;KACA,MAAM,OAAO,YAAY;MACrB,MAAM,WAAW,MAAM,KAAKL,QAAQ,4BAChC,SACA,qBAAqB,OAAO,CAChC;MACA,OAAO,MAAM,yCAAyC,QAAQ;KAClE;IACJ;GACJ;GACA,OAAO,iBAAiB,MAAM,KAAK,UAAU,OAAO,GAAG,IAAI;EAC/D;EAEA,MAAM,OAAO,KAAKE;EAClB,IAAI,MAAM,SAAS,mBACf,MAAM,IAAI,mBACN,4DACJ;EAGJ,IAAI,UAAU,iBAAiB,KAAA,GAC3B,MAAM,IAAI,gBACN,mGACJ;EAEJ,MAAM,OAAO,OACT,YACiC;GAEjC,MAAM,mBAAmB,MAAM,yBAC3B,MACA,SACIQ,oCACA,OAAOA,oCAA0C,OAAO,CAC5D,CACJ;GACA,OAAO;IACH;IACA,MAAM,OAAO,YAAY;KACrB,MAAM,WAAW,MAAM,KAAKV,QAAQ,sBAChC;MAAE;MAAS;KAAiB,GAC5B,qBAAqB,OAAO,CAChC;KACA,OAAO,MAAM,mCAAmC,QAAQ;IAC5D;GACJ;EACJ;EACA,OAAO,iBAAiB,MAAM,KAAK,UAAU,OAAO,GAAG,IAAI;CAC/D;AACJ"}
1
+ {"version":3,"file":"trading-withdraws.js","names":["#client","Proto.WithdrawService","#auth","#resolver","#signingConfig","#catalog","#scales","#toFundingInputSchema","#toExternalChainInputSchema","#toFundingBatchInputSchema","#prepareWithdraw","Proto.TradingWithdrawIntentPayloadSchema"],"sources":["../../../src/services/trading-withdraws/trading-withdraws.ts"],"sourcesContent":["import { ConfigurationError, ValidationError } from \"../../shared/errors.js\";\nimport { create, toBinary } from \"@bufbuild/protobuf\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport type { Address, Hex } from \"viem\";\nimport { checksumEvmAddress, evmHexToBytes } from \"../../utils/evm.js\";\nimport type { ClientCatalog } from \"../../catalogs/types.js\";\nimport * as Proto from \"../../gen/chain/withdraw/v1/withdraw_pb.js\";\nimport { idToBigInt } from \"../../utils/base58-id.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport {\n toConnectCallOptions,\n type PolyesterMutationOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport {\n signApiKeyEd25519Payload,\n type ApiKeyEd25519AuthProvider,\n type AuthApiTransports,\n type JwtAuthProvider,\n} from \"../../shared/transports.js\";\nimport { parse } from \"../../shared/validation.js\";\nimport {\n createCreateTradingToFundingBatchInputSchema,\n CreateTradingToFundingBatchResultSchema,\n type CreateTradingToFundingBatchInput,\n type CreateTradingToFundingBatchResult,\n createCreateTradingWithdrawToExternalChainInputSchema,\n createCreateTradingWithdrawToFundingInputSchema,\n CreateTradingWithdrawResultSchema,\n CreateWalletTradingWithdrawResultSchema,\n GetWalletBalancesInputSchema,\n GetWalletBalancesResultSchema,\n ValidateWithdrawDestinationInputSchema,\n ValidateWithdrawDestinationResultSchema,\n renewTradingWithdrawPayload,\n type CreateTradingWithdrawResult,\n type CreateTradingWithdrawToExternalChainInput,\n type CreateTradingWithdrawToExternalChainRequest,\n type CreateTradingWithdrawToFundingInput,\n type CreateTradingWithdrawToFundingRequest,\n type GetWalletBalancesInput,\n type GetWalletBalancesResult,\n type TradingWithdrawIntentPayloadRequest,\n type ValidateWithdrawDestinationInput,\n type ValidateWithdrawDestinationResult,\n} from \"./trading-withdraws.schemas.js\";\nimport { toU128 } from \"../../utils/u128.js\";\nimport {\n buildTradingToFundingBatchWalletMessage,\n buildTradingWithdrawWalletMessage,\n} from \"./wallet-message.js\";\n\nexport type TradingWithdrawWalletSigner = {\n signerWallet: string;\n accountId: string;\n /**\n * Signs the UTF-8 message directly using EIP-191 personal_sign, without pre-hashing or switching chains.\n * For a viem account, use `(message) => account.signMessage({ message })`.\n */\n signMessage: (message: string) => Promise<Hex>;\n};\n\nexport type TradingWithdrawSigningConfig = {\n chainId: number;\n tradingGatewayAddress: Address;\n};\n\nexport type CreateTradingWithdrawToFundingServiceInput = CreateTradingWithdrawToFundingInput & {\n walletSigner?: TradingWithdrawWalletSigner;\n};\n\nexport type CreateTradingWithdrawToExternalChainServiceInput =\n CreateTradingWithdrawToExternalChainInput & {\n walletSigner?: TradingWithdrawWalletSigner;\n };\n\nexport type CreateTradingToFundingBatchServiceInput = CreateTradingToFundingBatchInput & {\n walletSigner: TradingWithdrawWalletSigner;\n};\n\n/**\n * A signed batch. `submit` always sends the same signed request, so it can be repeated after\n * an MFA step-up, or after an `aborted` or `unavailable` answer: the server then answers the\n * first outcome for the key. It never signs again; a refused batch is final for its key, so\n * moving the funds needs a new batch with a new `idempotencyKey`.\n */\nexport type PreparedTradingToFundingBatch = Readonly<{\n /** When the backend stops accepting a new submission of this batch. */\n deadline: Date;\n submit: (options?: PolyesterMutationOptions) => Promise<CreateTradingToFundingBatchResult>;\n}>;\n\nexport type PreparedTradingWithdraw = Readonly<{\n /** When the backend stops accepting the currently signed request. */\n deadline: Date;\n /**\n * True once the deadline is less than a minute away. The withdraw signs again on\n * `submit` from then on, so callers can keep resubmitting the same prepared withdraw,\n * e.g. after a slow MFA step-up.\n */\n isExpired: () => boolean;\n /**\n * Submits the payload and signature produced during preparation. Repeated calls only\n * change transport options such as the step-up token, unless the deadline is near: the\n * withdraw then signs a fresh deadline and nonce with the same idempotency key.\n */\n submit: (options?: PolyesterMutationOptions) => Promise<CreateTradingWithdrawResult>;\n}>;\n\ntype SignedTradingWithdraw = {\n payload: TradingWithdrawIntentPayloadRequest;\n send: (options?: PolyesterMutationOptions) => Promise<CreateTradingWithdrawResult>;\n};\n\n// Leaves room for the request to reach the backend and for modest clock skew.\nconst PREPARED_WITHDRAW_EXPIRY_MARGIN_MS = 60_000;\n\nfunction deadlineMs(payload: TradingWithdrawIntentPayloadRequest): number {\n return Number(payload.deadlineTsSec) * 1000;\n}\n\nfunction preparedWithdraw(\n signed: SignedTradingWithdraw,\n resign: (payload: TradingWithdrawIntentPayloadRequest) => Promise<SignedTradingWithdraw>,\n): PreparedTradingWithdraw {\n let current = signed;\n const isExpired = () =>\n Date.now() >= deadlineMs(current.payload) - PREPARED_WITHDRAW_EXPIRY_MARGIN_MS;\n return {\n get deadline() {\n return new Date(deadlineMs(current.payload));\n },\n isExpired,\n submit: async (options) => {\n if (isExpired()) {\n current = await resign(renewTradingWithdrawPayload(current.payload));\n }\n return current.send(options);\n },\n };\n}\n\ntype TradingWithdrawRequest =\n | CreateTradingWithdrawToFundingRequest\n | CreateTradingWithdrawToExternalChainRequest;\n\nfunction walletSignatureBytes(signature: Hex): Uint8Array {\n if (!/^0x[0-9a-fA-F]{128}(?:00|01|1[bBcC])$/.test(signature)) {\n throw new ValidationError(\n \"Trading withdraw wallet signature must be 65 bytes with recovery byte 0, 1, 27, or 28.\",\n );\n }\n return evmHexToBytes(signature);\n}\n\nfunction resolveTradingWithdrawTargetAccountId(params: {\n subaccountId: bigint | undefined;\n rootAccountId: string;\n}): bigint {\n if (params.subaccountId !== undefined) return params.subaccountId;\n return idToBigInt(params.rootAccountId, \"targetAccountId\");\n}\n\nasync function resolveTradingWithdrawSigningConfig(params: {\n fallback: TradingWithdrawSigningConfig;\n catalog?: ClientCatalog;\n}): Promise<TradingWithdrawSigningConfig> {\n if (!params.catalog) return params.fallback;\n\n try {\n await params.catalog.ensureReady();\n const gateway = params.catalog.zipper.getContractByName(\"tradingGateway\");\n const address = gateway?.address?.trim();\n if (!address?.startsWith(\"0x\")) return params.fallback;\n\n return {\n chainId: params.fallback.chainId,\n tradingGatewayAddress: checksumEvmAddress(address),\n };\n } catch {\n return params.fallback;\n }\n}\n\nasync function resolveWalletSignature(params: {\n signingConfig: TradingWithdrawSigningConfig;\n payload: TradingWithdrawIntentPayloadRequest;\n walletSigner: TradingWithdrawWalletSigner;\n targetAccountId: bigint;\n}): Promise<{ signerWallet: string; payloadSignature: Uint8Array }> {\n const signerWallet = params.walletSigner.signerWallet.trim().toLowerCase();\n const accountId = idToBigInt(params.walletSigner.accountId, \"accountId\");\n const signature = await params.walletSigner.signMessage(\n buildTradingWithdrawWalletMessage({\n signingConfig: params.signingConfig,\n payload: params.payload,\n signerWallet,\n accountId,\n targetAccountId: params.targetAccountId,\n }),\n );\n return { signerWallet, payloadSignature: walletSignatureBytes(signature) };\n}\n\n/**\n * Creates durable Trading withdrawal intents, signed by the client's API key or a wallet (EIP-191).\n */\nexport class TradingWithdrawsService {\n #client: Client<typeof Proto.WithdrawService>;\n #resolver?: SubaccountResolver;\n #signingConfig: TradingWithdrawSigningConfig;\n #catalog?: ClientCatalog;\n #scales: SdkScales;\n #auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider;\n #toFundingInputSchema: ReturnType<typeof createCreateTradingWithdrawToFundingInputSchema>;\n #toExternalChainInputSchema: ReturnType<\n typeof createCreateTradingWithdrawToExternalChainInputSchema\n >;\n #toFundingBatchInputSchema: ReturnType<typeof createCreateTradingToFundingBatchInputSchema>;\n\n constructor(\n transports: AuthApiTransports,\n resolver: SubaccountResolver | undefined,\n signingConfig: TradingWithdrawSigningConfig,\n scales: SdkScales,\n catalog?: ClientCatalog,\n auth?: JwtAuthProvider | ApiKeyEd25519AuthProvider,\n ) {\n this.#client = createClient(Proto.WithdrawService, transports.authApi);\n this.#auth = auth;\n this.#resolver = resolver;\n this.#signingConfig = signingConfig;\n this.#catalog = catalog;\n this.#scales = scales;\n this.#toFundingInputSchema = createCreateTradingWithdrawToFundingInputSchema(scales);\n this.#toExternalChainInputSchema =\n createCreateTradingWithdrawToExternalChainInputSchema(scales);\n this.#toFundingBatchInputSchema = createCreateTradingToFundingBatchInputSchema(scales);\n }\n\n /**\n * Reads the zTokens the account's smart account wallet holds on Polyester Chain, such as a\n * rejected withdrawal's refund (see the lifecycle step's `refundAddress`), which stays there\n * until moved. Balances that could not be read are listed in `unavailableAssets`, not\n * reported as zero. API keys need `read-balances`.\n */\n async getWalletBalances(\n input: GetWalletBalancesInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<GetWalletBalancesResult> {\n const request = parse(\n GetWalletBalancesInputSchema,\n resolveAccountScopedInput(input, this.#resolver),\n );\n const response = await this.#client.getWalletBalances(\n removeUndefined(request),\n toConnectCallOptions(options),\n );\n return parse(GetWalletBalancesResultSchema, response);\n }\n\n /**\n * Checks whether an external-chain destination can receive a withdrawal without creating, signing, or reserving one. API keys need `read-withdraw-validation`.\n */\n async validateDestination(\n input: ValidateWithdrawDestinationInput,\n options?: PolyesterRequestOptions,\n ): Promise<ValidateWithdrawDestinationResult> {\n const request = parse(ValidateWithdrawDestinationInputSchema, input);\n const response = await this.#client.validateWithdrawDestination(\n request,\n toConnectCallOptions(options),\n );\n return parse(ValidateWithdrawDestinationResultSchema, response);\n }\n\n /**\n * Builds a Trading-to-Funding withdraw intent payload with asset id, decimal amount, destination address, five-minute deadline, nonce, and idempotency key. If a wallet signer is provided, it signs the canonical EIP-191 message and calls the wallet endpoint; otherwise the client's API key signs the payload for the API-key endpoint.\n */\n async createToFunding(\n input: CreateTradingWithdrawToFundingServiceInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTradingWithdrawResult> {\n const prepared = await this.prepareToFunding(input);\n return prepared.submit(options);\n }\n\n /**\n * Builds and signs a Trading-to-Funding withdrawal once so the exact request can be\n * resubmitted after backend-directed authorization such as MFA step-up.\n */\n async prepareToFunding(\n input: CreateTradingWithdrawToFundingServiceInput,\n ): Promise<PreparedTradingWithdraw> {\n await this.#scales.ready();\n const { walletSigner, ...inputForValidation } = input;\n const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);\n const validated = parse(this.#toFundingInputSchema, resolvedInput);\n return this.#prepareWithdraw(validated, walletSigner);\n }\n\n /**\n * Builds a Trading-to-external-chain withdraw intent payload with asset id, decimal gross amount, destination network, destination address, five-minute deadline, nonce, and idempotency key. If a wallet signer is provided, it signs the canonical EIP-191 message and calls the wallet endpoint; otherwise the client's API key signs the payload for the API-key endpoint.\n */\n async createToExternalChain(\n input: CreateTradingWithdrawToExternalChainServiceInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTradingWithdrawResult> {\n const prepared = await this.prepareToExternalChain(input);\n return prepared.submit(options);\n }\n\n /**\n * Builds and signs a Trading-to-external-chain withdrawal once so the exact request can\n * be resubmitted after backend-directed authorization such as MFA step-up.\n */\n async prepareToExternalChain(\n input: CreateTradingWithdrawToExternalChainServiceInput,\n ): Promise<PreparedTradingWithdraw> {\n await this.#scales.ready();\n const { walletSigner, ...inputForValidation } = input;\n const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);\n const validated = parse(this.#toExternalChainInputSchema, resolvedInput);\n return this.#prepareWithdraw(validated, walletSigner);\n }\n\n /**\n * Moves up to 10 amounts from one Trading account to Funding accounts with one wallet\n * signature and one MFA check. All legs are accepted or none, and an accepted batch is paid\n * as one or refunded in full. When every leg goes to the caller's own accounts, an\n * MFA-elevated session is enough; any other leg needs a fresh `stepUpToken`. Wallet signers\n * only.\n */\n async createToFundingBatch(\n input: CreateTradingToFundingBatchServiceInput,\n options?: PolyesterMutationOptions,\n ): Promise<CreateTradingToFundingBatchResult> {\n const prepared = await this.prepareToFundingBatch(input);\n return prepared.submit(options);\n }\n\n /**\n * Builds and signs a Trading-to-Funding batch once, so the exact request can be resubmitted\n * after an MFA step-up or a transient failure.\n */\n async prepareToFundingBatch(\n input: CreateTradingToFundingBatchServiceInput,\n ): Promise<PreparedTradingToFundingBatch> {\n await this.#scales.ready();\n const { walletSigner, ...inputForValidation } = input;\n const resolvedInput = resolveAccountScopedInput(inputForValidation, this.#resolver);\n const validated = parse(this.#toFundingBatchInputSchema, resolvedInput);\n const signingConfig = await resolveTradingWithdrawSigningConfig({\n fallback: this.#signingConfig,\n catalog: this.#catalog,\n });\n const signerWallet = walletSigner.signerWallet.trim().toLowerCase();\n const signature = await walletSigner.signMessage(\n buildTradingToFundingBatchWalletMessage({\n signingConfig,\n signerWallet,\n accountId: idToBigInt(walletSigner.accountId, \"accountId\"),\n targetAccountId: resolveTradingWithdrawTargetAccountId({\n subaccountId: validated.subaccountId,\n rootAccountId: walletSigner.accountId,\n }),\n deadlineTsSec: validated.deadlineTsSec,\n nonce: validated.nonce,\n idempotencyKey: validated.idempotencyKey,\n legs: validated.legs,\n }),\n );\n const request = removeUndefined({\n legs: validated.legs.map((leg) => ({\n assetId: leg.assetId,\n amountE18: toU128(leg.amountE18),\n destinationAddress: leg.destinationAddress,\n })),\n subaccountId: validated.subaccountId,\n deadlineTsSec: validated.deadlineTsSec,\n nonce: toU128(validated.nonce),\n idempotencyKey: validated.idempotencyKey,\n signerWallet,\n payloadSignature: walletSignatureBytes(signature),\n });\n return {\n deadline: new Date(Number(validated.deadlineTsSec) * 1000),\n submit: async (options) => {\n const response = await this.#client.createWalletTradingToFundingBatch(\n request,\n toConnectCallOptions(options),\n );\n return parse(CreateTradingToFundingBatchResultSchema, response);\n },\n };\n }\n\n async #prepareWithdraw(\n validated: TradingWithdrawRequest,\n walletSigner: TradingWithdrawWalletSigner | undefined,\n ): Promise<PreparedTradingWithdraw> {\n if (walletSigner) {\n const signingConfig = await resolveTradingWithdrawSigningConfig({\n fallback: this.#signingConfig,\n catalog: this.#catalog,\n });\n const targetAccountId = resolveTradingWithdrawTargetAccountId({\n subaccountId: validated.subaccountId,\n rootAccountId: walletSigner.accountId,\n });\n const sign = async (\n payload: TradingWithdrawIntentPayloadRequest,\n ): Promise<SignedTradingWithdraw> => {\n const walletSignature = await resolveWalletSignature({\n signingConfig,\n payload,\n walletSigner,\n targetAccountId,\n });\n const request = removeUndefined({\n payload,\n subaccountId: validated.subaccountId,\n signerWallet: walletSignature.signerWallet,\n payloadSignature: walletSignature.payloadSignature,\n });\n return {\n payload,\n send: async (options) => {\n const response = await this.#client.createWalletTradingWithdraw(\n request,\n toConnectCallOptions(options),\n );\n return parse(CreateWalletTradingWithdrawResultSchema, response);\n },\n };\n };\n return preparedWithdraw(await sign(validated.payload), sign);\n }\n\n const auth = this.#auth;\n if (auth?.kind !== \"api-key-ed25519\") {\n throw new ConfigurationError(\n \"Trading withdraw requires a wallet signer or API-key auth.\",\n );\n }\n // CreateTradingWithdrawRequest has no subaccount field: the API key decides the account.\n if (validated.subaccountId !== undefined) {\n throw new ValidationError(\n 'API-key trading withdraws cannot target a subaccount. Use `account: \"main\"` or a wallet signer.',\n );\n }\n const sign = async (\n payload: TradingWithdrawIntentPayloadRequest,\n ): Promise<SignedTradingWithdraw> => {\n // The backend verifies the signature over the payload's protobuf encoding.\n const payloadSignature = await signApiKeyEd25519Payload(\n auth,\n toBinary(\n Proto.TradingWithdrawIntentPayloadSchema,\n create(Proto.TradingWithdrawIntentPayloadSchema, payload),\n ),\n );\n return {\n payload,\n send: async (options) => {\n const response = await this.#client.createTradingWithdraw(\n { payload, payloadSignature },\n toConnectCallOptions(options),\n );\n return parse(CreateTradingWithdrawResultSchema, response);\n },\n };\n };\n return preparedWithdraw(await sign(validated.payload), sign);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqHA,MAAM,qCAAqC;AAE3C,SAAS,WAAW,SAAsD;CACtE,OAAO,OAAO,QAAQ,aAAa,IAAI;AAC3C;AAEA,SAAS,iBACL,QACA,QACuB;CACvB,IAAI,UAAU;CACd,MAAM,kBACF,KAAK,IAAI,KAAK,WAAW,QAAQ,OAAO,IAAI;CAChD,OAAO;EACH,IAAI,WAAW;GACX,OAAO,IAAI,KAAK,WAAW,QAAQ,OAAO,CAAC;EAC/C;EACA;EACA,QAAQ,OAAO,YAAY;GACvB,IAAI,UAAU,GACV,UAAU,MAAM,OAAO,4BAA4B,QAAQ,OAAO,CAAC;GAEvE,OAAO,QAAQ,KAAK,OAAO;EAC/B;CACJ;AACJ;AAMA,SAAS,qBAAqB,WAA4B;CACtD,IAAI,CAAC,wCAAwC,KAAK,SAAS,GACvD,M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