@polyester/sdk 0.36.0-devnet-20261118123359 → 0.36.0-devnet-20261118184607

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 (339) hide show
  1. package/CHANGELOG.md +60 -8
  2. package/dist/catalogs/index.d.ts +2 -2
  3. package/dist/catalogs/snapshot-validation.js +10 -1
  4. package/dist/catalogs/snapshot-validation.js.map +1 -1
  5. package/dist/catalogs/zipper-catalog.d.ts +2 -0
  6. package/dist/catalogs/zipper-catalog.d.ts.map +1 -1
  7. package/dist/catalogs/zipper-catalog.js.map +1 -1
  8. package/dist/catalogs/zipper-supply.d.ts +2 -0
  9. package/dist/catalogs/zipper-supply.d.ts.map +1 -1
  10. package/dist/catalogs/zipper-supply.js +7 -5
  11. package/dist/catalogs/zipper-supply.js.map +1 -1
  12. package/dist/client.d.ts +2 -0
  13. package/dist/client.d.ts.map +1 -1
  14. package/dist/client.js +2 -0
  15. package/dist/client.js.map +1 -1
  16. package/dist/gen/ai/v1/assistant_pb.d.ts +679 -13
  17. package/dist/gen/ai/v1/assistant_pb.d.ts.map +1 -1
  18. package/dist/gen/ai/v1/assistant_pb.js +355 -97
  19. package/dist/gen/ai/v1/assistant_pb.js.map +1 -1
  20. package/dist/gen/alerts/v1/price_alerts_pb.d.ts +33 -4
  21. package/dist/gen/alerts/v1/price_alerts_pb.d.ts.map +1 -1
  22. package/dist/gen/alerts/v1/price_alerts_pb.js +23 -2
  23. package/dist/gen/alerts/v1/price_alerts_pb.js.map +1 -1
  24. package/dist/gen/auth/v1/activity_pb.d.ts +148 -0
  25. package/dist/gen/auth/v1/activity_pb.d.ts.map +1 -0
  26. package/dist/gen/auth/v1/activity_pb.js +40 -0
  27. package/dist/gen/auth/v1/activity_pb.js.map +1 -0
  28. package/dist/gen/auth/v1/api_keys_pb.d.ts +10 -4
  29. package/dist/gen/auth/v1/api_keys_pb.d.ts.map +1 -1
  30. package/dist/gen/auth/v1/api_keys_pb.js +3 -1
  31. package/dist/gen/auth/v1/api_keys_pb.js.map +1 -1
  32. package/dist/gen/auth/v1/auth_pb.d.ts +61 -5
  33. package/dist/gen/auth/v1/auth_pb.d.ts.map +1 -1
  34. package/dist/gen/auth/v1/auth_pb.js +23 -6
  35. package/dist/gen/auth/v1/auth_pb.js.map +1 -1
  36. package/dist/gen/auth/v1/mfa_pb.d.ts +140 -2
  37. package/dist/gen/auth/v1/mfa_pb.d.ts.map +1 -1
  38. package/dist/gen/auth/v1/mfa_pb.js +80 -8
  39. package/dist/gen/auth/v1/mfa_pb.js.map +1 -1
  40. package/dist/gen/auth/v1/policies_pb.d.ts +18 -3
  41. package/dist/gen/auth/v1/policies_pb.d.ts.map +1 -1
  42. package/dist/gen/auth/v1/policies_pb.js +18 -3
  43. package/dist/gen/auth/v1/policies_pb.js.map +1 -1
  44. package/dist/gen/auth/v1/social_verification_pb.d.ts +36 -15
  45. package/dist/gen/auth/v1/social_verification_pb.d.ts.map +1 -1
  46. package/dist/gen/auth/v1/social_verification_pb.js +1 -1
  47. package/dist/gen/auth/v1/social_verification_pb.js.map +1 -1
  48. package/dist/gen/auth/v1/subaccounts_pb.d.ts +15 -1
  49. package/dist/gen/auth/v1/subaccounts_pb.d.ts.map +1 -1
  50. package/dist/gen/auth/v1/subaccounts_pb.js +1 -1
  51. package/dist/gen/auth/v1/subaccounts_pb.js.map +1 -1
  52. package/dist/gen/chain/withdraw/v1/auto_withdraw_pb.d.ts +6 -2
  53. package/dist/gen/chain/withdraw/v1/auto_withdraw_pb.d.ts.map +1 -1
  54. package/dist/gen/chain/withdraw/v1/auto_withdraw_pb.js.map +1 -1
  55. package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts +104 -6
  56. package/dist/gen/chain/withdraw/v1/withdraw_pb.d.ts.map +1 -1
  57. package/dist/gen/chain/withdraw/v1/withdraw_pb.js +49 -3
  58. package/dist/gen/chain/withdraw/v1/withdraw_pb.js.map +1 -1
  59. package/dist/gen/chain/zipper/v1/zipper_pb.d.ts +76 -3
  60. package/dist/gen/chain/zipper/v1/zipper_pb.d.ts.map +1 -1
  61. package/dist/gen/chain/zipper/v1/zipper_pb.js +46 -2
  62. package/dist/gen/chain/zipper/v1/zipper_pb.js.map +1 -1
  63. package/dist/gen/index.d.ts +3 -1
  64. package/dist/gen/index.js +4 -2
  65. package/dist/gen/ledger/read/v1/ledger_read_pb.d.ts +21 -139
  66. package/dist/gen/ledger/read/v1/ledger_read_pb.d.ts.map +1 -1
  67. package/dist/gen/ledger/read/v1/ledger_read_pb.js +16 -17
  68. package/dist/gen/ledger/read/v1/ledger_read_pb.js.map +1 -1
  69. package/dist/gen/ledger/read/v1/statement_export_pb.d.ts +236 -20
  70. package/dist/gen/ledger/read/v1/statement_export_pb.d.ts.map +1 -1
  71. package/dist/gen/ledger/read/v1/statement_export_pb.js +44 -10
  72. package/dist/gen/ledger/read/v1/statement_export_pb.js.map +1 -1
  73. package/dist/gen/ledger/v1/catalog_pb.d.ts +9 -1
  74. package/dist/gen/ledger/v1/catalog_pb.d.ts.map +1 -1
  75. package/dist/gen/ledger/v1/catalog_pb.js +9 -1
  76. package/dist/gen/ledger/v1/catalog_pb.js.map +1 -1
  77. package/dist/gen/marketdata/v1/asset_info_pb.d.ts +158 -7
  78. package/dist/gen/marketdata/v1/asset_info_pb.d.ts.map +1 -1
  79. package/dist/gen/marketdata/v1/asset_info_pb.js +56 -6
  80. package/dist/gen/marketdata/v1/asset_info_pb.js.map +1 -1
  81. package/dist/gen/notifications/v1/notifications_pb.d.ts +45 -6
  82. package/dist/gen/notifications/v1/notifications_pb.d.ts.map +1 -1
  83. package/dist/gen/notifications/v1/notifications_pb.js +23 -5
  84. package/dist/gen/notifications/v1/notifications_pb.js.map +1 -1
  85. package/dist/gen/orders/v1/orders_pb.d.ts +105 -29
  86. package/dist/gen/orders/v1/orders_pb.d.ts.map +1 -1
  87. package/dist/gen/orders/v1/orders_pb.js +14 -2
  88. package/dist/gen/orders/v1/orders_pb.js.map +1 -1
  89. package/dist/gen/orders/v1/orders_read_pb.d.ts +50 -20
  90. package/dist/gen/orders/v1/orders_read_pb.d.ts.map +1 -1
  91. package/dist/gen/orders/v1/orders_read_pb.js +1 -1
  92. package/dist/gen/orders/v1/orders_read_pb.js.map +1 -1
  93. package/dist/gen/polyester/api/options_pb.d.ts +11 -2
  94. package/dist/gen/polyester/api/options_pb.d.ts.map +1 -1
  95. package/dist/gen/polyester/api/options_pb.js +13 -3
  96. package/dist/gen/polyester/api/options_pb.js.map +1 -1
  97. package/dist/gen/privatews/v1/private_ws_pb.d.ts +13 -3
  98. package/dist/gen/privatews/v1/private_ws_pb.d.ts.map +1 -1
  99. package/dist/gen/privatews/v1/private_ws_pb.js.map +1 -1
  100. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.d.ts +126 -10
  101. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.d.ts.map +1 -1
  102. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.js +14 -6
  103. package/dist/gen/swap/quickswap/v1/quickswap_broker_pb.js.map +1 -1
  104. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.d.ts +665 -0
  105. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.d.ts.map +1 -0
  106. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.js +216 -0
  107. package/dist/gen/swap/quickswap/v1/quickswap_explorer_pb.js.map +1 -0
  108. package/dist/gen/swap/quickswap/v1/quickswap_pb.d.ts +166 -52
  109. package/dist/gen/swap/quickswap/v1/quickswap_pb.d.ts.map +1 -1
  110. package/dist/gen/swap/quickswap/v1/quickswap_pb.js +50 -12
  111. package/dist/gen/swap/quickswap/v1/quickswap_pb.js.map +1 -1
  112. package/dist/gen/system/v1/system_pb.d.ts +49 -2
  113. package/dist/gen/system/v1/system_pb.d.ts.map +1 -1
  114. package/dist/gen/system/v1/system_pb.js +18 -6
  115. package/dist/gen/system/v1/system_pb.js.map +1 -1
  116. package/dist/gen/transfer/v1/internal_transfer_pb.d.ts +150 -71
  117. package/dist/gen/transfer/v1/internal_transfer_pb.d.ts.map +1 -1
  118. package/dist/gen/transfer/v1/internal_transfer_pb.js +56 -34
  119. package/dist/gen/transfer/v1/internal_transfer_pb.js.map +1 -1
  120. package/dist/gen/triggers/v1/triggers_pb.d.ts +117 -16
  121. package/dist/gen/triggers/v1/triggers_pb.d.ts.map +1 -1
  122. package/dist/gen/triggers/v1/triggers_pb.js +45 -2
  123. package/dist/gen/triggers/v1/triggers_pb.js.map +1 -1
  124. package/dist/index.d.ts +13 -9
  125. package/dist/realtime/ready-gated-subscription.js +1 -1
  126. package/dist/realtime/snapshot-then-stream.js +2 -0
  127. package/dist/realtime/snapshot-then-stream.js.map +1 -1
  128. package/dist/services/account-activity/account-activity.d.ts +22 -0
  129. package/dist/services/account-activity/account-activity.d.ts.map +1 -0
  130. package/dist/services/account-activity/account-activity.js +32 -0
  131. package/dist/services/account-activity/account-activity.js.map +1 -0
  132. package/dist/services/account-activity/account-activity.schemas.d.ts +78 -0
  133. package/dist/services/account-activity/account-activity.schemas.d.ts.map +1 -0
  134. package/dist/services/account-activity/account-activity.schemas.js +44 -0
  135. package/dist/services/account-activity/account-activity.schemas.js.map +1 -0
  136. package/dist/services/account-activity/account-activity.types.d.ts +2 -0
  137. package/dist/services/account-activity/service.d.ts +8 -0
  138. package/dist/services/account-activity/service.d.ts.map +1 -0
  139. package/dist/services/account-activity/service.js +9 -0
  140. package/dist/services/account-activity/service.js.map +1 -0
  141. package/dist/services/address-book/address-book.schemas.d.ts +2 -2
  142. package/dist/services/address-book/address-book.schemas.js +2 -2
  143. package/dist/services/api-keys/api-keys.schemas.js +2 -2
  144. package/dist/services/assistant/assistant-events.schemas.d.ts +25 -25
  145. package/dist/services/assistant/assistant.codecs.d.ts +7 -2
  146. package/dist/services/assistant/assistant.codecs.d.ts.map +1 -1
  147. package/dist/services/assistant/assistant.codecs.js +18 -2
  148. package/dist/services/assistant/assistant.codecs.js.map +1 -1
  149. package/dist/services/assistant/assistant.d.ts +29 -2
  150. package/dist/services/assistant/assistant.d.ts.map +1 -1
  151. package/dist/services/assistant/assistant.js +44 -2
  152. package/dist/services/assistant/assistant.js.map +1 -1
  153. package/dist/services/assistant/assistant.schemas.d.ts +111 -6
  154. package/dist/services/assistant/assistant.schemas.d.ts.map +1 -1
  155. package/dist/services/assistant/assistant.schemas.js +74 -6
  156. package/dist/services/assistant/assistant.schemas.js.map +1 -1
  157. package/dist/services/assistant/assistant.types.d.ts +3 -3
  158. package/dist/services/auto-withdraw/auto-withdraw.codecs.d.ts +3 -1
  159. package/dist/services/auto-withdraw/auto-withdraw.codecs.d.ts.map +1 -1
  160. package/dist/services/auto-withdraw/auto-withdraw.codecs.js.map +1 -1
  161. package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts +21 -19
  162. package/dist/services/auto-withdraw/auto-withdraw.schemas.d.ts.map +1 -1
  163. package/dist/services/auto-withdraw/auto-withdraw.schemas.js +1 -0
  164. package/dist/services/auto-withdraw/auto-withdraw.schemas.js.map +1 -1
  165. package/dist/services/balances/balances.d.ts +1 -13
  166. package/dist/services/balances/balances.d.ts.map +1 -1
  167. package/dist/services/balances/balances.js +1 -45
  168. package/dist/services/balances/balances.js.map +1 -1
  169. package/dist/services/balances/balances.schemas.d.ts +1 -67
  170. package/dist/services/balances/balances.schemas.d.ts.map +1 -1
  171. package/dist/services/balances/balances.schemas.js +1 -22
  172. package/dist/services/balances/balances.schemas.js.map +1 -1
  173. package/dist/services/balances/balances.types.d.ts +2 -2
  174. package/dist/services/candles/candles.schemas.d.ts +10 -10
  175. package/dist/services/changelog/changelog.schemas.d.ts +38 -38
  176. package/dist/services/claims/claims.schemas.d.ts +2 -2
  177. package/dist/services/dust-conversion/dust-conversion.schemas.d.ts +2 -2
  178. package/dist/services/heatmap/heatmap.schemas.d.ts +4 -4
  179. package/dist/services/internal-transfers/internal-transfers.codecs.d.ts +11 -6
  180. package/dist/services/internal-transfers/internal-transfers.codecs.d.ts.map +1 -1
  181. package/dist/services/internal-transfers/internal-transfers.codecs.js +6 -6
  182. package/dist/services/internal-transfers/internal-transfers.codecs.js.map +1 -1
  183. package/dist/services/internal-transfers/internal-transfers.d.ts +17 -10
  184. package/dist/services/internal-transfers/internal-transfers.d.ts.map +1 -1
  185. package/dist/services/internal-transfers/internal-transfers.js +21 -10
  186. package/dist/services/internal-transfers/internal-transfers.js.map +1 -1
  187. package/dist/services/internal-transfers/internal-transfers.schemas.d.ts +43 -31
  188. package/dist/services/internal-transfers/internal-transfers.schemas.d.ts.map +1 -1
  189. package/dist/services/internal-transfers/internal-transfers.schemas.js +23 -12
  190. package/dist/services/internal-transfers/internal-transfers.schemas.js.map +1 -1
  191. package/dist/services/internal-transfers/internal-transfers.types.d.ts +2 -2
  192. package/dist/services/lifecycle/lifecycle.js +1 -1
  193. package/dist/services/lifecycle/lifecycle.js.map +1 -1
  194. package/dist/services/lifecycle/lifecycle.schemas.d.ts +55 -55
  195. package/dist/services/market-data/market-data.codecs.d.ts +8 -0
  196. package/dist/services/market-data/market-data.codecs.d.ts.map +1 -0
  197. package/dist/services/market-data/market-data.codecs.js +7 -1
  198. package/dist/services/market-data/market-data.codecs.js.map +1 -1
  199. package/dist/services/market-data/market-data.d.ts +3 -2
  200. package/dist/services/market-data/market-data.d.ts.map +1 -1
  201. package/dist/services/market-data/market-data.js +3 -2
  202. package/dist/services/market-data/market-data.js.map +1 -1
  203. package/dist/services/market-data/market-data.schemas.d.ts +332 -4
  204. package/dist/services/market-data/market-data.schemas.d.ts.map +1 -1
  205. package/dist/services/market-data/market-data.schemas.js +56 -8
  206. package/dist/services/market-data/market-data.schemas.js.map +1 -1
  207. package/dist/services/market-data/market-data.types.d.ts +3 -2
  208. package/dist/services/notifications/notifications.codecs.d.ts +1 -1
  209. package/dist/services/notifications/notifications.codecs.d.ts.map +1 -1
  210. package/dist/services/notifications/notifications.codecs.js +2 -1
  211. package/dist/services/notifications/notifications.codecs.js.map +1 -1
  212. package/dist/services/notifications/notifications.d.ts +4 -2
  213. package/dist/services/notifications/notifications.d.ts.map +1 -1
  214. package/dist/services/notifications/notifications.js +4 -2
  215. package/dist/services/notifications/notifications.js.map +1 -1
  216. package/dist/services/notifications/notifications.schemas.d.ts +50 -6
  217. package/dist/services/notifications/notifications.schemas.d.ts.map +1 -1
  218. package/dist/services/notifications/notifications.schemas.js +5 -0
  219. package/dist/services/notifications/notifications.schemas.js.map +1 -1
  220. package/dist/services/orderbook/orderbook.js +1 -1
  221. package/dist/services/orders/order-enums.codecs.d.ts +2 -0
  222. package/dist/services/orders/order-errors.schemas.d.ts +49 -4
  223. package/dist/services/orders/order-errors.schemas.d.ts.map +1 -1
  224. package/dist/services/orders/order-errors.schemas.js +13 -3
  225. package/dist/services/orders/order-errors.schemas.js.map +1 -1
  226. package/dist/services/orders/orders-batch.schemas.d.ts +290 -50
  227. package/dist/services/orders/orders-batch.schemas.d.ts.map +1 -1
  228. package/dist/services/orders/orders-input.schemas.d.ts +55 -8
  229. package/dist/services/orders/orders-input.schemas.d.ts.map +1 -1
  230. package/dist/services/orders/orders-input.schemas.js +1 -1
  231. package/dist/services/orders/orders-output.schemas.d.ts +10 -10
  232. package/dist/services/orders/orders.d.ts.map +1 -1
  233. package/dist/services/orders/orders.js +47 -43
  234. package/dist/services/orders/orders.js.map +1 -1
  235. package/dist/services/policies/api-key-policies/api-key-policies.schemas.d.ts +15 -15
  236. package/dist/services/policies/api-key-policies/api-key-policies.schemas.js +1 -1
  237. package/dist/services/policies/shared.codecs.js +12 -6
  238. package/dist/services/policies/shared.codecs.js.map +1 -1
  239. package/dist/services/policies/shared.d.ts +1 -1
  240. package/dist/services/policies/shared.js +1 -1
  241. package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.d.ts +9 -9
  242. package/dist/services/policies/subaccount-policies/subaccount-policies.schemas.js +3 -3
  243. package/dist/services/price-alerts/price-alerts.d.ts +5 -2
  244. package/dist/services/price-alerts/price-alerts.d.ts.map +1 -1
  245. package/dist/services/price-alerts/price-alerts.js +5 -2
  246. package/dist/services/price-alerts/price-alerts.js.map +1 -1
  247. package/dist/services/price-alerts/price-alerts.schemas.js +1 -1
  248. package/dist/services/social-verification/social-verification.schemas.d.ts +9 -0
  249. package/dist/services/social-verification/social-verification.schemas.d.ts.map +1 -1
  250. package/dist/services/social-verification/social-verification.schemas.js +9 -2
  251. package/dist/services/social-verification/social-verification.schemas.js.map +1 -1
  252. package/dist/services/statement-exports/statement-exports.codecs.d.ts +3 -2
  253. package/dist/services/statement-exports/statement-exports.codecs.d.ts.map +1 -1
  254. package/dist/services/statement-exports/statement-exports.codecs.js +2 -1
  255. package/dist/services/statement-exports/statement-exports.codecs.js.map +1 -1
  256. package/dist/services/statement-exports/statement-exports.d.ts +25 -10
  257. package/dist/services/statement-exports/statement-exports.d.ts.map +1 -1
  258. package/dist/services/statement-exports/statement-exports.js +33 -10
  259. package/dist/services/statement-exports/statement-exports.js.map +1 -1
  260. package/dist/services/statement-exports/statement-exports.schemas.d.ts +37 -9
  261. package/dist/services/statement-exports/statement-exports.schemas.d.ts.map +1 -1
  262. package/dist/services/statement-exports/statement-exports.schemas.js +24 -5
  263. package/dist/services/statement-exports/statement-exports.schemas.js.map +1 -1
  264. package/dist/services/statement-exports/statement-exports.types.d.ts +2 -2
  265. package/dist/services/subaccounts/subaccounts.codecs.js +112 -38
  266. package/dist/services/subaccounts/subaccounts.codecs.js.map +1 -1
  267. package/dist/services/subaccounts/subaccounts.js +1 -1
  268. package/dist/services/subaccounts/subaccounts.schemas.d.ts +22 -15
  269. package/dist/services/subaccounts/subaccounts.schemas.d.ts.map +1 -1
  270. package/dist/services/subaccounts/subaccounts.schemas.js +10 -3
  271. package/dist/services/subaccounts/subaccounts.schemas.js.map +1 -1
  272. package/dist/services/system/system.d.ts +12 -1
  273. package/dist/services/system/system.d.ts.map +1 -1
  274. package/dist/services/system/system.js +5 -0
  275. package/dist/services/system/system.js.map +1 -1
  276. package/dist/services/system/system.schemas.d.ts +13 -13
  277. package/dist/services/system/system.types.d.ts +2 -2
  278. package/dist/services/trades/trades.d.ts.map +1 -1
  279. package/dist/services/trades/trades.js +12 -4
  280. package/dist/services/trades/trades.js.map +1 -1
  281. package/dist/services/trades/trades.schemas.d.ts +1 -1
  282. package/dist/services/trading-withdraws/trading-withdraws.codecs.d.ts +8 -0
  283. package/dist/services/trading-withdraws/trading-withdraws.codecs.d.ts.map +1 -0
  284. package/dist/services/trading-withdraws/trading-withdraws.codecs.js +7 -1
  285. package/dist/services/trading-withdraws/trading-withdraws.codecs.js.map +1 -1
  286. package/dist/services/trading-withdraws/trading-withdraws.d.ts +2 -1
  287. package/dist/services/trading-withdraws/trading-withdraws.d.ts.map +1 -1
  288. package/dist/services/trading-withdraws/trading-withdraws.js +2 -1
  289. package/dist/services/trading-withdraws/trading-withdraws.js.map +1 -1
  290. package/dist/services/trading-withdraws/trading-withdraws.schemas.d.ts +15 -0
  291. package/dist/services/trading-withdraws/trading-withdraws.schemas.d.ts.map +1 -1
  292. package/dist/services/trading-withdraws/trading-withdraws.schemas.js +16 -2
  293. package/dist/services/trading-withdraws/trading-withdraws.schemas.js.map +1 -1
  294. package/dist/services/trading-withdraws/trading-withdraws.types.d.ts +2 -1
  295. package/dist/services/transfers/transfers.schemas.d.ts +4 -4
  296. package/dist/services/triggers/trigger-input.schemas.d.ts +2 -2
  297. package/dist/services/triggers/triggers-output.schemas.d.ts +153 -35
  298. package/dist/services/triggers/triggers-output.schemas.d.ts.map +1 -1
  299. package/dist/services/triggers/triggers-output.schemas.js +13 -3
  300. package/dist/services/triggers/triggers-output.schemas.js.map +1 -1
  301. package/dist/services/triggers/triggers.codecs.d.ts +10 -0
  302. package/dist/services/triggers/triggers.codecs.d.ts.map +1 -0
  303. package/dist/services/triggers/triggers.codecs.js +7 -1
  304. package/dist/services/triggers/triggers.codecs.js.map +1 -1
  305. package/dist/services/triggers/triggers.d.ts +2 -2
  306. package/dist/services/triggers/triggers.d.ts.map +1 -1
  307. package/dist/services/triggers/triggers.js +16 -12
  308. package/dist/services/triggers/triggers.js.map +1 -1
  309. package/dist/services/zipper/zipper.d.ts.map +1 -1
  310. package/dist/services/zipper/zipper.js +13 -7
  311. package/dist/services/zipper/zipper.js.map +1 -1
  312. package/dist/services/zipper/zipper.schemas.d.ts +7 -2
  313. package/dist/services/zipper/zipper.schemas.d.ts.map +1 -1
  314. package/dist/services/zipper/zipper.schemas.js +29 -9
  315. package/dist/services/zipper/zipper.schemas.js.map +1 -1
  316. package/dist/services/zipper/zipper.types.d.ts +2 -2
  317. package/dist/shared/catalog-config.d.ts +16 -2
  318. package/dist/shared/catalog-config.d.ts.map +1 -1
  319. package/dist/shared/catalog-config.js.map +1 -1
  320. package/dist/shared/connect-error-mapping.d.ts.map +1 -1
  321. package/dist/shared/connect-error-mapping.js +7 -2
  322. package/dist/shared/connect-error-mapping.js.map +1 -1
  323. package/dist/shared/decimal-surface.d.ts +6 -0
  324. package/dist/shared/decimal-surface.d.ts.map +1 -1
  325. package/dist/shared/decimal-surface.js +65 -1
  326. package/dist/shared/decimal-surface.js.map +1 -1
  327. package/dist/shared/error-detail.d.ts +10 -0
  328. package/dist/shared/error-detail.d.ts.map +1 -1
  329. package/dist/shared/error-detail.js.map +1 -1
  330. package/dist/shared/error-details/auth.js +6 -0
  331. package/dist/shared/error-details/auth.js.map +1 -1
  332. package/dist/shared/ledger-codes.d.ts +3 -1
  333. package/dist/shared/ledger-codes.d.ts.map +1 -1
  334. package/dist/shared/ledger-codes.js +6 -3
  335. package/dist/shared/ledger-codes.js.map +1 -1
  336. package/dist/wired-services.d.ts.map +1 -1
  337. package/dist/wired-services.js +3 -1
  338. package/dist/wired-services.js.map +1 -1
  339. package/package.json +1 -1
@@ -11,7 +11,7 @@ declare const ListStatusEventsInputSchema: v.SchemaWithPipe<readonly [v.StrictOb
11
11
  /** Previous `nextPageToken`; resend the same `states` and `kinds` with it. */
12
12
  readonly pageToken: v.OptionalSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction]>, undefined>;
13
13
  }, undefined>, v.TransformAction<{
14
- states?: ("completed" | "scheduled" | "in_progress" | "canceled")[] | undefined;
14
+ states?: ("completed" | "canceled" | "scheduled" | "in_progress")[] | undefined;
15
15
  kinds?: ("maintenance" | "incident")[] | undefined;
16
16
  limit?: number | undefined;
17
17
  pageToken?: string | undefined;
@@ -26,7 +26,7 @@ type ListStatusEventsInput = v.InferInput<typeof ListStatusEventsInputSchema>;
26
26
  declare const StatusEventSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
27
27
  readonly id: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
28
28
  readonly kind: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "maintenance" | "incident">]>;
29
- readonly state: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "completed" | "scheduled" | "in_progress" | "canceled">]>;
29
+ readonly state: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "completed" | "canceled" | "scheduled" | "in_progress">]>;
30
30
  readonly title: v.StringSchema<undefined>;
31
31
  readonly message: v.StringSchema<undefined>;
32
32
  readonly startTime: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
@@ -43,7 +43,7 @@ declare const StatusEventSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
43
43
  seconds: bigint;
44
44
  nanos: number;
45
45
  } | undefined, number | undefined>]>;
46
- readonly services: v.ArraySchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "deposits" | "withdrawals" | "transfers" | "trading" | "accounts" | "api" | "market_data" | "quickswap" | "app">]>, undefined>;
46
+ readonly services: v.ArraySchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "api" | "trading" | "accounts" | "market_data" | "quickswap" | "deposits" | "withdrawals" | "transfers" | "app">]>, undefined>;
47
47
  readonly markets: v.ArraySchema<v.StringSchema<undefined>, undefined>;
48
48
  readonly updatedAt: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
49
49
  readonly seconds: v.BigintSchema<undefined>;
@@ -77,12 +77,12 @@ declare const StatusEventSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
77
77
  }, undefined>, v.TransformAction<{
78
78
  id: string;
79
79
  kind: "unspecified" | "maintenance" | "incident";
80
- state: "unspecified" | "completed" | "scheduled" | "in_progress" | "canceled";
80
+ state: "unspecified" | "completed" | "canceled" | "scheduled" | "in_progress";
81
81
  title: string;
82
82
  message: string;
83
83
  startTime?: number | undefined;
84
84
  endTime?: number | undefined;
85
- services: ("unspecified" | "deposits" | "withdrawals" | "transfers" | "trading" | "accounts" | "api" | "market_data" | "quickswap" | "app")[];
85
+ services: ("unspecified" | "api" | "trading" | "accounts" | "market_data" | "quickswap" | "deposits" | "withdrawals" | "transfers" | "app")[];
86
86
  markets: string[];
87
87
  updatedAt?: number | undefined;
88
88
  impact: "unspecified" | "degraded" | "partial_outage" | "major_outage";
@@ -98,13 +98,13 @@ declare const StatusEventSchema: v.SchemaWithPipe<readonly [v.ObjectSchema<{
98
98
  /** Stable across updates; match events across pages by it. */
99
99
  id: string;
100
100
  kind: "unspecified" | "maintenance" | "incident";
101
- state: "unspecified" | "completed" | "scheduled" | "in_progress" | "canceled";
101
+ state: "unspecified" | "completed" | "canceled" | "scheduled" | "in_progress";
102
102
  title: string;
103
103
  message: string;
104
104
  startTime: number | null;
105
105
  /** Always set for maintenance; null for an incident with no expected end yet. */
106
106
  endTime: number | null;
107
- services: ("unspecified" | "deposits" | "withdrawals" | "transfers" | "trading" | "accounts" | "api" | "market_data" | "quickswap" | "app")[];
107
+ services: ("unspecified" | "api" | "trading" | "accounts" | "market_data" | "quickswap" | "deposits" | "withdrawals" | "transfers" | "app")[];
108
108
  /** Affected market symbols such as `"BTC-USDT"`; empty when not limited to markets. */
109
109
  markets: string[];
110
110
  /** Affected asset codes such as `"SOL"`; empty when not limited to assets. */
@@ -128,7 +128,7 @@ declare const ListStatusEventsResultSchema: v.ObjectSchema<{
128
128
  readonly events: v.ArraySchema<v.SchemaWithPipe<readonly [v.ObjectSchema<{
129
129
  readonly id: v.SchemaWithPipe<readonly [v.BigintSchema<undefined>, v.TransformAction<bigint, string>]>;
130
130
  readonly kind: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "maintenance" | "incident">]>;
131
- readonly state: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "completed" | "scheduled" | "in_progress" | "canceled">]>;
131
+ readonly state: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "completed" | "canceled" | "scheduled" | "in_progress">]>;
132
132
  readonly title: v.StringSchema<undefined>;
133
133
  readonly message: v.StringSchema<undefined>;
134
134
  readonly startTime: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
@@ -145,7 +145,7 @@ declare const ListStatusEventsResultSchema: v.ObjectSchema<{
145
145
  seconds: bigint;
146
146
  nanos: number;
147
147
  } | undefined, number | undefined>]>;
148
- readonly services: v.ArraySchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "deposits" | "withdrawals" | "transfers" | "trading" | "accounts" | "api" | "market_data" | "quickswap" | "app">]>, undefined>;
148
+ readonly services: v.ArraySchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "api" | "trading" | "accounts" | "market_data" | "quickswap" | "deposits" | "withdrawals" | "transfers" | "app">]>, undefined>;
149
149
  readonly markets: v.ArraySchema<v.StringSchema<undefined>, undefined>;
150
150
  readonly updatedAt: v.SchemaWithPipe<readonly [v.OptionalSchema<v.ObjectSchema<{
151
151
  readonly seconds: v.BigintSchema<undefined>;
@@ -179,12 +179,12 @@ declare const ListStatusEventsResultSchema: v.ObjectSchema<{
179
179
  }, undefined>, v.TransformAction<{
180
180
  id: string;
181
181
  kind: "unspecified" | "maintenance" | "incident";
182
- state: "unspecified" | "completed" | "scheduled" | "in_progress" | "canceled";
182
+ state: "unspecified" | "completed" | "canceled" | "scheduled" | "in_progress";
183
183
  title: string;
184
184
  message: string;
185
185
  startTime?: number | undefined;
186
186
  endTime?: number | undefined;
187
- services: ("unspecified" | "deposits" | "withdrawals" | "transfers" | "trading" | "accounts" | "api" | "market_data" | "quickswap" | "app")[];
187
+ services: ("unspecified" | "api" | "trading" | "accounts" | "market_data" | "quickswap" | "deposits" | "withdrawals" | "transfers" | "app")[];
188
188
  markets: string[];
189
189
  updatedAt?: number | undefined;
190
190
  impact: "unspecified" | "degraded" | "partial_outage" | "major_outage";
@@ -200,13 +200,13 @@ declare const ListStatusEventsResultSchema: v.ObjectSchema<{
200
200
  /** Stable across updates; match events across pages by it. */
201
201
  id: string;
202
202
  kind: "unspecified" | "maintenance" | "incident";
203
- state: "unspecified" | "completed" | "scheduled" | "in_progress" | "canceled";
203
+ state: "unspecified" | "completed" | "canceled" | "scheduled" | "in_progress";
204
204
  title: string;
205
205
  message: string;
206
206
  startTime: number | null;
207
207
  /** Always set for maintenance; null for an incident with no expected end yet. */
208
208
  endTime: number | null;
209
- services: ("unspecified" | "deposits" | "withdrawals" | "transfers" | "trading" | "accounts" | "api" | "market_data" | "quickswap" | "app")[];
209
+ services: ("unspecified" | "api" | "trading" | "accounts" | "market_data" | "quickswap" | "deposits" | "withdrawals" | "transfers" | "app")[];
210
210
  /** Affected market symbols such as `"BTC-USDT"`; empty when not limited to markets. */
211
211
  markets: string[];
212
212
  /** Affected asset codes such as `"SOL"`; empty when not limited to assets. */
@@ -1,4 +1,4 @@
1
1
  import { ListStatusEventsInput, ListStatusEventsResult, StatusEvent } from "./system.schemas.js";
2
- import { SystemVersion } from "./system.js";
2
+ import { SystemTime, SystemVersion } from "./system.js";
3
3
  import { StatusEventImpact, StatusEventKind, StatusEventService, StatusEventState } from "./system.codecs.js";
4
- export type { ListStatusEventsInput, ListStatusEventsResult, StatusEvent, StatusEventImpact, StatusEventKind, StatusEventService, StatusEventState, SystemVersion };
4
+ export type { ListStatusEventsInput, ListStatusEventsResult, StatusEvent, StatusEventImpact, StatusEventKind, StatusEventService, StatusEventState, SystemTime, SystemVersion };
@@ -1 +1 @@
1
- {"version":3,"file":"trades.d.ts","names":[],"sources":["../../../src/services/trades/trades.ts"],"mappings":";;;;;;;;;UAwBU,6BAA6B,mBAAmB;EACtD;;;;;cAMS;;EAOL,YAAA,YAAY,mBACZ,UAAU,mBACV,UAAU,gCACV,QAAQ;;;;;;EAaN,KACF,QAAO,oBACP,UAAU,0BACX;IAAU,QAAQ;IAAS,WAAW;IAAiB;;;;;;;EAoB1D,UAAU,OAAO"}
1
+ {"version":3,"file":"trades.d.ts","names":[],"sources":["../../../src/services/trades/trades.ts"],"mappings":";;;;;;;;;UA6BU,6BAA6B,mBAAmB;EACtD;;;;;cAMS;;EAOL,YAAA,YAAY,mBACZ,UAAU,mBACV,UAAU,gCACV,QAAQ;;;;;;EAaN,KACF,QAAO,oBACP,UAAU,0BACX;IAAU,QAAQ;IAAS,WAAW;IAAiB;;;;;;;EAsB1D,UAAU,OAAO"}
@@ -2,6 +2,7 @@ import { parse } from "../../shared/validation.js";
2
2
  import { removeUndefined } from "../../utils/remove-undefined.js";
3
3
  import { toConnectCallOptions } from "../../shared/request-options.js";
4
4
  import { deliverBatch } from "../../shared/subscription-errors.js";
5
+ import { createCatalogRefreshQueue, hasKnownSymbol, withCatalogRefresh } from "../../shared/decimal-surface.js";
5
6
  import { resolveAccountScopedInput } from "../subaccount-resolver.js";
6
7
  import { OrdersReadService, UserTradeBatchSchema } from "../../gen/orders/v1/orders_read_pb.js";
7
8
  import { GetUserTradesInputSchema, formatUserTrade } from "./trades.schemas.js";
@@ -35,7 +36,7 @@ var TradesService = class {
35
36
  const validatedInput = parse(GetUserTradesInputSchema, resolved);
36
37
  const res = await this.#client.getUserTrades(removeUndefined(validatedInput), toConnectCallOptions(options));
37
38
  return {
38
- trades: res.trades.map((trade) => formatUserTrade(this.#scales, trade)),
39
+ trades: await withCatalogRefresh(this.#scales, () => res.trades.map((trade) => formatUserTrade(this.#scales, trade))),
39
40
  transfers: parse(v.array(createOrderTransferSchema()), res.transfers ?? []),
40
41
  nextPageToken: res.nextPageToken
41
42
  };
@@ -47,15 +48,22 @@ var TradesService = class {
47
48
  */
48
49
  subscribe(input) {
49
50
  const channel = `private:spot:trades:${input.accountId}:proto`;
50
- return connectReadyGatedProtoChannel(this.#realtime, {
51
+ const scales = this.#scales;
52
+ let open = true;
53
+ const queue = createCatalogRefreshQueue(scales, channel, input.onError, () => open);
54
+ const stop = connectReadyGatedProtoChannel(this.#realtime, {
51
55
  channel,
52
56
  schema: UserTradeBatchSchema,
53
- ready: () => this.#scales.ready(),
54
- onPublication: (batch) => deliverBatch(channel, batch.events, (trade) => input.onEvent(formatUserTrade(this.#scales, trade)), input.onError),
57
+ ready: () => scales.ready(),
58
+ onPublication: (batch) => queue(batch.events.some((trade) => !hasKnownSymbol(scales, trade.symbolId)), () => deliverBatch(channel, batch.events, (trade) => input.onEvent(formatUserTrade(scales, trade)), input.onError)),
55
59
  onConnected: () => input.onOpen?.(),
56
60
  onDisconnected: () => input.onClose?.(),
57
61
  onError: input.onError
58
62
  });
63
+ return () => {
64
+ open = false;
65
+ stop();
66
+ };
59
67
  }
60
68
  };
61
69
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"trades.js","names":["#client","Proto.OrdersReadService","#realtime","#resolver","#scales","Proto.UserTradeBatchSchema"],"sources":["../../../src/services/trades/trades.ts"],"sourcesContent":["import { createOrderTransferSchema, type OrderTransfer } from \"../orders/orders-output.schemas.js\";\nimport * as Proto from \"../../gen/orders/v1/orders_read_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport { connectReadyGatedProtoChannel } from \"../../realtime/ready-gated-subscription.js\";\nimport { deliverBatch } from \"../../shared/subscription-errors.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport {\n toConnectCallOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport type { SdkScales } from \"../../shared/decimal-surface.js\";\nimport type { AuthApiTransports } from \"../../shared/transports.js\";\nimport {\n GetUserTradesInputSchema,\n formatUserTrade,\n type GetUserTradesInput,\n type Trade,\n} from \"./trades.schemas.js\";\n\ninterface SubscribeTradesInput extends BaseSubscribeInput<Trade> {\n accountId: string;\n}\n\n/**\n * Reads and streams authenticated user trade fills.\n */\nexport class TradesService {\n #client: Client<typeof Proto.OrdersReadService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n\n constructor(\n transports: AuthApiTransports,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#client = createClient(Proto.OrdersReadService, transports.authApi);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n }\n\n /**\n * Returns user trades for the resolved root account or subaccount, supporting symbol, side, time range, limit, page token, and after-match-ID replay cursor filters. The `afterMatchId` cursor requires `symbolId`, enforced at the type and validation level. Results include the next page token from GetUserTrades.\n * Scope executions to an order or lineage, optionally through a generation. Requested transfers\n * belong to matches on this page; deduplicate them across pages by txId.\n */\n async list(\n input: GetUserTradesInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ trades: Trade[]; transfers: OrderTransfer[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(GetUserTradesInputSchema, resolved);\n const res = await this.#client.getUserTrades(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n trades: res.trades.map((trade) => formatUserTrade(this.#scales, trade)),\n transfers: parse(v.array(createOrderTransferSchema()), res.transfers ?? []),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Subscribes to private user trade updates on private:spot:trades:{accountId}:proto and emits parsed fills.\n * Each publication batches fills, emitted one at a time; `(matchId, orderId)` identifies a\n * fill, and a repeated identity replaces the earlier copy.\n */\n subscribe(input: SubscribeTradesInput) {\n const channel = `private:spot:trades:${input.accountId}:proto`;\n return connectReadyGatedProtoChannel(this.#realtime, {\n channel,\n schema: Proto.UserTradeBatchSchema,\n ready: () => this.#scales.ready(),\n onPublication: (batch) =>\n deliverBatch(\n channel,\n batch.events,\n (trade) => input.onEvent(formatUserTrade(this.#scales, trade)),\n input.onError,\n ),\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AA+BA,IAAa,gBAAb,MAA2B;CACvB;CACA;CACA;CACA;CAEA,YACI,YACA,UACA,UACA,QACF;EACE,KAAKA,UAAU,aAAaC,mBAAyB,WAAW,OAAO;EACvE,KAAKC,YAAY;EACjB,KAAKC,YAAY;EACjB,KAAKC,UAAU;CACnB;;;;;;CAOA,MAAM,KACF,QAA4B,CAAC,GAC7B,SAC+E;EAC/E,MAAM,KAAKA,QAAQ,MAAM;EACzB,MAAM,WAAW,0BAA0B,OAAO,KAAKD,SAAS;EAChE,MAAM,iBAAiB,MAAM,0BAA0B,QAAQ;EAC/D,MAAM,MAAM,MAAM,KAAKH,QAAQ,cAC3B,gBAAgB,cAAc,GAC9B,qBAAqB,OAAO,CAChC;EACA,OAAO;GACH,QAAQ,IAAI,OAAO,KAAK,UAAU,gBAAgB,KAAKI,SAAS,KAAK,CAAC;GACtE,WAAW,MAAM,EAAE,MAAM,0BAA0B,CAAC,GAAG,IAAI,aAAa,CAAC,CAAC;GAC1E,eAAe,IAAI;EACvB;CACJ;;;;;;CAOA,UAAU,OAA6B;EACnC,MAAM,UAAU,uBAAuB,MAAM,UAAU;EACvD,OAAO,8BAA8B,KAAKF,WAAW;GACjD;GACA,QAAQG;GACR,aAAa,KAAKD,QAAQ,MAAM;GAChC,gBAAgB,UACZ,aACI,SACA,MAAM,SACL,UAAU,MAAM,QAAQ,gBAAgB,KAAKA,SAAS,KAAK,CAAC,GAC7D,MAAM,OACV;GACJ,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,SAAS,MAAM;EACnB,CAAC;CACL;AACJ"}
1
+ {"version":3,"file":"trades.js","names":["#client","Proto.OrdersReadService","#realtime","#resolver","#scales","Proto.UserTradeBatchSchema"],"sources":["../../../src/services/trades/trades.ts"],"sourcesContent":["import { createOrderTransferSchema, type OrderTransfer } from \"../orders/orders-output.schemas.js\";\nimport * as Proto from \"../../gen/orders/v1/orders_read_pb.js\";\nimport { createClient, type Client } from \"@connectrpc/connect\";\nimport * as v from \"valibot\";\nimport { parse } from \"../../shared/validation.js\";\nimport { removeUndefined } from \"../../utils/remove-undefined.js\";\nimport { type SubaccountResolver, resolveAccountScopedInput } from \"../subaccount-resolver.js\";\nimport type { PolyesterRealtime } from \"../../realtime/types.js\";\nimport { deliverBatch } from \"../../shared/subscription-errors.js\";\nimport { connectReadyGatedProtoChannel } from \"../../realtime/ready-gated-subscription.js\";\nimport type { BaseSubscribeInput } from \"../../shared/types.js\";\nimport {\n toConnectCallOptions,\n type PolyesterRequestOptions,\n} from \"../../shared/request-options.js\";\nimport {\n createCatalogRefreshQueue,\n hasKnownSymbol,\n withCatalogRefresh,\n type SdkScales,\n} from \"../../shared/decimal-surface.js\";\nimport type { AuthApiTransports } from \"../../shared/transports.js\";\nimport {\n GetUserTradesInputSchema,\n formatUserTrade,\n type GetUserTradesInput,\n type Trade,\n} from \"./trades.schemas.js\";\n\ninterface SubscribeTradesInput extends BaseSubscribeInput<Trade> {\n accountId: string;\n}\n\n/**\n * Reads and streams authenticated user trade fills.\n */\nexport class TradesService {\n #client: Client<typeof Proto.OrdersReadService>;\n #realtime: PolyesterRealtime;\n #resolver?: SubaccountResolver;\n #scales: SdkScales;\n\n constructor(\n transports: AuthApiTransports,\n realtime: PolyesterRealtime,\n resolver: SubaccountResolver | undefined,\n scales: SdkScales,\n ) {\n this.#client = createClient(Proto.OrdersReadService, transports.authApi);\n this.#realtime = realtime;\n this.#resolver = resolver;\n this.#scales = scales;\n }\n\n /**\n * Returns user trades for the resolved root account or subaccount, supporting symbol, side, time range, limit, page token, and after-match-ID replay cursor filters. The `afterMatchId` cursor requires `symbolId`, enforced at the type and validation level. Results include the next page token from GetUserTrades.\n * Scope executions to an order or lineage, optionally through a generation. Requested transfers\n * belong to matches on this page; deduplicate them across pages by txId.\n */\n async list(\n input: GetUserTradesInput = {},\n options?: PolyesterRequestOptions,\n ): Promise<{ trades: Trade[]; transfers: OrderTransfer[]; nextPageToken: string }> {\n await this.#scales.ready();\n const resolved = resolveAccountScopedInput(input, this.#resolver);\n const validatedInput = parse(GetUserTradesInputSchema, resolved);\n const res = await this.#client.getUserTrades(\n removeUndefined(validatedInput),\n toConnectCallOptions(options),\n );\n return {\n trades: await withCatalogRefresh(this.#scales, () =>\n res.trades.map((trade) => formatUserTrade(this.#scales, trade)),\n ),\n transfers: parse(v.array(createOrderTransferSchema()), res.transfers ?? []),\n nextPageToken: res.nextPageToken,\n };\n }\n\n /**\n * Subscribes to private user trade updates on private:spot:trades:{accountId}:proto and emits parsed fills.\n * Each publication batches fills, emitted one at a time; `(matchId, orderId)` identifies a\n * fill, and a repeated identity replaces the earlier copy.\n */\n subscribe(input: SubscribeTradesInput): () => void {\n const channel = `private:spot:trades:${input.accountId}:proto`;\n const scales = this.#scales;\n let open = true;\n const queue = createCatalogRefreshQueue(scales, channel, input.onError, () => open);\n const stop = connectReadyGatedProtoChannel(this.#realtime, {\n channel,\n schema: Proto.UserTradeBatchSchema,\n ready: () => scales.ready(),\n onPublication: (batch) =>\n queue(\n batch.events.some((trade) => !hasKnownSymbol(scales, trade.symbolId)),\n () =>\n deliverBatch(\n channel,\n batch.events,\n (trade) => input.onEvent(formatUserTrade(scales, trade)),\n input.onError,\n ),\n ),\n onConnected: () => input.onOpen?.(),\n onDisconnected: () => input.onClose?.(),\n onError: input.onError,\n });\n return () => {\n open = false;\n stop();\n };\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoCA,IAAa,gBAAb,MAA2B;CACvB;CACA;CACA;CACA;CAEA,YACI,YACA,UACA,UACA,QACF;EACE,KAAKA,UAAU,aAAaC,mBAAyB,WAAW,OAAO;EACvE,KAAKC,YAAY;EACjB,KAAKC,YAAY;EACjB,KAAKC,UAAU;CACnB;;;;;;CAOA,MAAM,KACF,QAA4B,CAAC,GAC7B,SAC+E;EAC/E,MAAM,KAAKA,QAAQ,MAAM;EACzB,MAAM,WAAW,0BAA0B,OAAO,KAAKD,SAAS;EAChE,MAAM,iBAAiB,MAAM,0BAA0B,QAAQ;EAC/D,MAAM,MAAM,MAAM,KAAKH,QAAQ,cAC3B,gBAAgB,cAAc,GAC9B,qBAAqB,OAAO,CAChC;EACA,OAAO;GACH,QAAQ,MAAM,mBAAmB,KAAKI,eAClC,IAAI,OAAO,KAAK,UAAU,gBAAgB,KAAKA,SAAS,KAAK,CAAC,CAClE;GACA,WAAW,MAAM,EAAE,MAAM,0BAA0B,CAAC,GAAG,IAAI,aAAa,CAAC,CAAC;GAC1E,eAAe,IAAI;EACvB;CACJ;;;;;;CAOA,UAAU,OAAyC;EAC/C,MAAM,UAAU,uBAAuB,MAAM,UAAU;EACvD,MAAM,SAAS,KAAKA;EACpB,IAAI,OAAO;EACX,MAAM,QAAQ,0BAA0B,QAAQ,SAAS,MAAM,eAAe,IAAI;EAClF,MAAM,OAAO,8BAA8B,KAAKF,WAAW;GACvD;GACA,QAAQG;GACR,aAAa,OAAO,MAAM;GAC1B,gBAAgB,UACZ,MACI,MAAM,OAAO,MAAM,UAAU,CAAC,eAAe,QAAQ,MAAM,QAAQ,CAAC,SAEhE,aACI,SACA,MAAM,SACL,UAAU,MAAM,QAAQ,gBAAgB,QAAQ,KAAK,CAAC,GACvD,MAAM,OACV,CACR;GACJ,mBAAmB,MAAM,SAAS;GAClC,sBAAsB,MAAM,UAAU;GACtC,SAAS,MAAM;EACnB,CAAC;EACD,aAAa;GACT,OAAO;GACP,KAAK;EACT;CACJ;AACJ"}
@@ -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.NumberIssue | v.StringIssue | v.BooleanIssue | v.IntegerIssue<number> | v.MinValueIssue<number, 1> | v.MaxValueIssue<number, 4294967295> | v.MinLengthIssue<string, 1> | v.StrictObjectIssue | v.PicklistIssue | v.UnionIssue<v.StringIssue | v.MinLengthIssue<string, 1> | v.StrictObjectIssue | v.PicklistIssue> | v.GtValueIssue<number, 0> | v.CheckIssue<bigint> | v.MaxValueIssue<number, 1000> | v.NeverIssue | v.UnionIssue<v.NumberIssue | v.StringIssue | v.BooleanIssue | v.IntegerIssue<number> | v.MinValueIssue<number, 1> | v.MaxValueIssue<number, 4294967295> | v.MinLengthIssue<string, 1> | v.StrictObjectIssue | v.PicklistIssue | v.UnionIssue<v.StringIssue | v.MinLengthIssue<string, 1> | v.StrictObjectIssue | v.PicklistIssue> | v.GtValueIssue<number, 0> | 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<{
172
+ }, undefined>], undefined>], ({ input }: v.UnionIssue<v.StringIssue | v.NumberIssue | v.BooleanIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.PicklistIssue | v.IntegerIssue<number> | v.MinValueIssue<number, 1> | v.UnionIssue<v.StringIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.PicklistIssue> | v.GtValueIssue<number, 0> | v.MaxValueIssue<number, 4294967295> | v.CheckIssue<bigint> | v.MaxValueIssue<number, 1000> | v.NeverIssue | v.UnionIssue<v.StringIssue | v.NumberIssue | v.BooleanIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.PicklistIssue | v.IntegerIssue<number> | v.MinValueIssue<number, 1> | v.UnionIssue<v.StringIssue | v.StrictObjectIssue | v.MinLengthIssue<string, 1> | v.PicklistIssue> | v.GtValueIssue<number, 0> | v.MaxValueIssue<number, 4294967295> | 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;
@@ -0,0 +1,8 @@
1
+ import "../../gen/chain/withdraw/v1/withdraw_pb.js";
2
+ //#region src/services/trading-withdraws/trading-withdraws.codecs.d.ts
3
+ declare const WALLET_ASSET_UNAVAILABLE_REASON_VALUES: readonly ["no_contract", "read_failed", "invalid_balance"];
4
+ /** Why a zToken balance could not be read. */
5
+ type WalletAssetUnavailableReasonValue = (typeof WALLET_ASSET_UNAVAILABLE_REASON_VALUES)[number];
6
+ //#endregion
7
+ export { WALLET_ASSET_UNAVAILABLE_REASON_VALUES, WalletAssetUnavailableReasonValue };
8
+ //# sourceMappingURL=trading-withdraws.codecs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trading-withdraws.codecs.d.ts","names":[],"sources":["../../../src/services/trading-withdraws/trading-withdraws.codecs.ts"],"mappings":";;cAiBa;;KAMD,4CACA"}
@@ -13,7 +13,13 @@ const WithdrawDestinationValidationCodeCodec = { protoToOutput: {
13
13
  [5]: "token_contract",
14
14
  [6]: "denylisted_address"
15
15
  } };
16
+ const WalletAssetUnavailableReasonCodec = { protoToOutput: {
17
+ [0]: "unspecified",
18
+ [1]: "no_contract",
19
+ [2]: "read_failed",
20
+ [3]: "invalid_balance"
21
+ } };
16
22
  //#endregion
17
- export { TradingWithdrawActionCodec, WithdrawDestinationValidationCodeCodec };
23
+ export { TradingWithdrawActionCodec, WalletAssetUnavailableReasonCodec, WithdrawDestinationValidationCodeCodec };
18
24
 
19
25
  //# sourceMappingURL=trading-withdraws.codecs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"trading-withdraws.codecs.js","names":[],"sources":["../../../src/services/trading-withdraws/trading-withdraws.codecs.ts"],"sourcesContent":["import * as Proto from \"../../gen/chain/withdraw/v1/withdraw_pb.js\";\nimport type { ProtoToOutput } from \"../../utils/types.js\";\n\nexport const TRADING_WITHDRAW_ACTION_VALUES = [\"to_funding\", \"to_external_chain\"] as const;\nexport type TradingWithdrawActionValue = (typeof TRADING_WITHDRAW_ACTION_VALUES)[number];\n\nexport const WITHDRAW_DESTINATION_VALIDATION_CODE_VALUES = [\n \"valid\",\n \"invalid_address\",\n \"unsupported_chain\",\n \"polyester_smart_account\",\n \"token_contract\",\n \"denylisted_address\",\n] as const;\nexport type WithdrawDestinationValidationCodeValue =\n (typeof WITHDRAW_DESTINATION_VALIDATION_CODE_VALUES)[number];\n\nexport const TradingWithdrawActionCodec = {\n inputToProto: {\n to_funding: Proto.TradingWithdrawAction.TO_FUNDING,\n to_external_chain: Proto.TradingWithdrawAction.TO_EXTERNAL_CHAIN,\n } satisfies Record<TradingWithdrawActionValue, Proto.TradingWithdrawAction>,\n} as const;\n\nexport const WithdrawDestinationValidationCodeCodec = {\n protoToOutput: {\n [Proto.WithdrawDestinationValidationCode.RESULT_UNSPECIFIED]: \"unspecified\",\n [Proto.WithdrawDestinationValidationCode.VALID]: \"valid\",\n [Proto.WithdrawDestinationValidationCode.INVALID_ADDRESS]: \"invalid_address\",\n [Proto.WithdrawDestinationValidationCode.UNSUPPORTED_CHAIN]: \"unsupported_chain\",\n [Proto.WithdrawDestinationValidationCode.POLYESTER_SMART_ACCOUNT]:\n \"polyester_smart_account\",\n [Proto.WithdrawDestinationValidationCode.TOKEN_CONTRACT]: \"token_contract\",\n [Proto.WithdrawDestinationValidationCode.DENYLISTED_ADDRESS]: \"denylisted_address\",\n } satisfies ProtoToOutput<\n Proto.WithdrawDestinationValidationCode,\n WithdrawDestinationValidationCodeValue\n >,\n} as const;\n"],"mappings":";;AAiBA,MAAa,6BAA6B,EACtC,cAAc;CACV,YAAA;CACA,mBAAA;AACJ,EACJ;AAEA,MAAa,yCAAyC,EAClD,eAAe;EACmD,IAAA;EACb,IAAA;EACU,IAAA;EACE,IAAA;EAEzD,IAAA;EACsD,IAAA;EACI,IAAA;AAClE,EAIJ"}
1
+ {"version":3,"file":"trading-withdraws.codecs.js","names":[],"sources":["../../../src/services/trading-withdraws/trading-withdraws.codecs.ts"],"sourcesContent":["import * as Proto from \"../../gen/chain/withdraw/v1/withdraw_pb.js\";\nimport type { ProtoToOutput } from \"../../utils/types.js\";\n\nexport const TRADING_WITHDRAW_ACTION_VALUES = [\"to_funding\", \"to_external_chain\"] as const;\nexport type TradingWithdrawActionValue = (typeof TRADING_WITHDRAW_ACTION_VALUES)[number];\n\nexport const WITHDRAW_DESTINATION_VALIDATION_CODE_VALUES = [\n \"valid\",\n \"invalid_address\",\n \"unsupported_chain\",\n \"polyester_smart_account\",\n \"token_contract\",\n \"denylisted_address\",\n] as const;\nexport type WithdrawDestinationValidationCodeValue =\n (typeof WITHDRAW_DESTINATION_VALIDATION_CODE_VALUES)[number];\n\nexport const WALLET_ASSET_UNAVAILABLE_REASON_VALUES = [\n \"no_contract\",\n \"read_failed\",\n \"invalid_balance\",\n] as const;\n/** Why a zToken balance could not be read. */\nexport type WalletAssetUnavailableReasonValue =\n (typeof WALLET_ASSET_UNAVAILABLE_REASON_VALUES)[number];\n\nexport const TradingWithdrawActionCodec = {\n inputToProto: {\n to_funding: Proto.TradingWithdrawAction.TO_FUNDING,\n to_external_chain: Proto.TradingWithdrawAction.TO_EXTERNAL_CHAIN,\n } satisfies Record<TradingWithdrawActionValue, Proto.TradingWithdrawAction>,\n} as const;\n\nexport const WithdrawDestinationValidationCodeCodec = {\n protoToOutput: {\n [Proto.WithdrawDestinationValidationCode.RESULT_UNSPECIFIED]: \"unspecified\",\n [Proto.WithdrawDestinationValidationCode.VALID]: \"valid\",\n [Proto.WithdrawDestinationValidationCode.INVALID_ADDRESS]: \"invalid_address\",\n [Proto.WithdrawDestinationValidationCode.UNSUPPORTED_CHAIN]: \"unsupported_chain\",\n [Proto.WithdrawDestinationValidationCode.POLYESTER_SMART_ACCOUNT]:\n \"polyester_smart_account\",\n [Proto.WithdrawDestinationValidationCode.TOKEN_CONTRACT]: \"token_contract\",\n [Proto.WithdrawDestinationValidationCode.DENYLISTED_ADDRESS]: \"denylisted_address\",\n } satisfies ProtoToOutput<\n Proto.WithdrawDestinationValidationCode,\n WithdrawDestinationValidationCodeValue\n >,\n} as const;\n\nexport const WalletAssetUnavailableReasonCodec = {\n protoToOutput: {\n [Proto.WalletAssetUnavailableReason.UNAVAILABLE_UNSPECIFIED]: \"unspecified\",\n [Proto.WalletAssetUnavailableReason.NO_CONTRACT]: \"no_contract\",\n [Proto.WalletAssetUnavailableReason.READ_FAILED]: \"read_failed\",\n [Proto.WalletAssetUnavailableReason.INVALID_BALANCE]: \"invalid_balance\",\n } satisfies ProtoToOutput<\n Proto.WalletAssetUnavailableReason,\n WalletAssetUnavailableReasonValue\n >,\n} as const;\n"],"mappings":";;AA0BA,MAAa,6BAA6B,EACtC,cAAc;CACV,YAAA;CACA,mBAAA;AACJ,EACJ;AAEA,MAAa,yCAAyC,EAClD,eAAe;EACmD,IAAA;EACb,IAAA;EACU,IAAA;EACE,IAAA;EAEzD,IAAA;EACsD,IAAA;EACI,IAAA;AAClE,EAIJ;AAEA,MAAa,oCAAoC,EAC7C,eAAe;EACmD,IAAA;EACZ,IAAA;EACA,IAAA;EACI,IAAA;AAC1D,EAIJ"}
@@ -50,7 +50,8 @@ declare class TradingWithdrawsService {
50
50
  /**
51
51
  * Reads the zTokens the account's smart account wallet holds on Polyester Chain, such as a
52
52
  * rejected withdrawal's refund (see the lifecycle step's `refundAddress`), which stays there
53
- * until moved. API keys need `read-balances`.
53
+ * until moved. Balances that could not be read are listed in `unavailableAssets`, not
54
+ * reported as zero. API keys need `read-balances`.
54
55
  */
55
56
  getWalletBalances(input?: GetWalletBalancesInput, options?: PolyesterRequestOptions): Promise<GetWalletBalancesResult>;
56
57
  /**
@@ -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;;;;;;EAkBvB,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":";;;;;;;;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"}
@@ -89,7 +89,8 @@ var TradingWithdrawsService = class {
89
89
  /**
90
90
  * Reads the zTokens the account's smart account wallet holds on Polyester Chain, such as a
91
91
  * rejected withdrawal's refund (see the lifecycle step's `refundAddress`), which stays there
92
- * until moved. API keys need `read-balances`.
92
+ * until moved. Balances that could not be read are listed in `unavailableAssets`, not
93
+ * reported as zero. API keys need `read-balances`.
93
94
  */
94
95
  async getWalletBalances(input = {}, options) {
95
96
  const request = parse(GetWalletBalancesInputSchema, resolveAccountScopedInput(input, this.#resolver));
@@ -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. 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,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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","#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,IAAI,CAAC,OAAO,SAAS,OAAO,OAAO;CAEnC,IAAI;EACA,MAAM,OAAO,QAAQ,YAAY;EA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kB,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"}
@@ -45,6 +45,7 @@ declare function createCreateTradingWithdrawToFundingInputSchema(scales: SdkScal
45
45
  declare function createCreateTradingWithdrawToExternalChainInputSchema(scales: SdkScales): v.SchemaWithPipe<readonly [v.StrictObjectSchema<{
46
46
  readonly assetId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, 4294967295, undefined>]>;
47
47
  readonly quantity: v.StringSchema<undefined>;
48
+ /** Polyester chain ID of the network: a Zipper chain's `chainId`, not its `nativeChainId`. */
48
49
  readonly destinationChainId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, number, undefined>]>;
49
50
  readonly destinationAddress: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>]>;
50
51
  readonly idempotencyKey: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>]>;
@@ -76,6 +77,7 @@ declare const CreateTradingWithdrawResultSchema: v.ObjectSchema<{
76
77
  }, undefined>;
77
78
  type CreateTradingWithdrawResult = v.InferOutput<typeof CreateTradingWithdrawResultSchema>;
78
79
  declare const ValidateWithdrawDestinationInputSchema: v.SchemaWithPipe<readonly [v.StrictObjectSchema<{
80
+ /** Polyester chain ID of the network: a Zipper chain's `chainId`, not its `nativeChainId`. */
79
81
  readonly destinationChainId: v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.IntegerAction<number, undefined>, v.GtValueAction<number, 0, undefined>, v.MaxValueAction<number, number, undefined>]>;
80
82
  readonly destinationAddress: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.TrimAction, v.MinLengthAction<string, 1, undefined>]>;
81
83
  }, undefined>, v.TransformAction<{
@@ -151,12 +153,25 @@ declare const GetWalletBalancesResultSchema: v.ObjectSchema<{
151
153
  chainId: number;
152
154
  ztokenAddress: string;
153
155
  }>]>, undefined>;
156
+ /**
157
+ * zTokens whose balance could not be read: unknown, not zero. Read again later; the read is
158
+ * complete only when this is empty.
159
+ */
160
+ readonly unavailableAssets: v.ArraySchema<v.ObjectSchema<{
161
+ readonly zippedAssetId: v.NumberSchema<undefined>;
162
+ readonly unifiedAssetId: v.NumberSchema<undefined>;
163
+ readonly chainId: v.NumberSchema<undefined>;
164
+ readonly ztokenAddress: v.StringSchema<undefined>;
165
+ readonly reason: v.OptionalSchema<v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.TransformAction<number, "unspecified" | "no_contract" | "read_failed" | "invalid_balance">]>, 0>;
166
+ }, undefined>, undefined>;
154
167
  }, undefined>;
155
168
  /**
156
169
  * zTokens the account's smart account wallet holds on Polyester Chain, read live from the
157
170
  * chain: for example a rejected withdrawal's refund, which stays there until moved. `amount`
158
171
  * is a decimal string (zTokens have 18 decimals); `chainId` is a `GetDepositWithdrawConfig`
159
172
  * chain. `balances` lists nonzero balances by `zippedAssetId` and is empty when there are none.
173
+ * An asset whose balance could not be read is in `unavailableAssets` instead, never in `balances`
174
+ * as zero.
160
175
  */
161
176
  type GetWalletBalancesResult = v.InferOutput<typeof GetWalletBalancesResultSchema>;
162
177
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"trading-withdraws.schemas.d.ts","names":[],"sources":["../../../src/services/trading-withdraws/trading-withdraws.schemas.ts"],"mappings":";;;;;KAwBY;EACR,QAAQ;EACR;EACA;EACA,WAAW;EACX;EACA,OAAO;EACP;EACA;;KAGC;EACD;EACA,SAAS;;iBAmDG,gDAAgD,QAAQ,YAAS,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;GAmChF;iBAEe,sDAAsD,QAAQ,YAAS,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCtF;KAEW,sCAAsC,EAAE,WAChD,kBAAkB;KAOV,4CAA4C,EAAE,WACtD,kBAAkB;cAOT,mCAAiC,EAAA;;;KAIlC,8BAA8B,EAAE,mBAAmB;cAOlD,wCAAsC,EAAA,yBAAA,EAAA;;;;;;;;;;KAgBvC,mCAAmC,EAAE,kBACtC;cA4CE,yCAAuC,EAAA,aAAA,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAKxC,oCAAoC,EAAE,mBACvC;cAGL,iCAA+B,EAAA;;;;;KAOzB,yBAAyB,EAAE,kBAAkB;cAE5C,+BAA6B,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAyB9B,0BAA0B,EAAE,mBAAmB"}
1
+ {"version":3,"file":"trading-withdraws.schemas.d.ts","names":[],"sources":["../../../src/services/trading-withdraws/trading-withdraws.schemas.ts"],"mappings":";;;;;KA0BY;EACR,QAAQ;EACR;EACA;EACA,WAAW;EACX;EACA,OAAO;EACP;EACA;;KAGC;EACD;EACA,SAAS;;iBAmDG,gDAAgD,QAAQ,YAAS,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;GAmChF;iBAEe,sDAAsD,QAAQ,YAAS,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA0CtF;KAEW,sCAAsC,EAAE,WAChD,kBAAkB;KAOV,4CAA4C,EAAE,WACtD,kBAAkB;cAOT,mCAAiC,EAAA;;;KAIlC,8BAA8B,EAAE,mBAAmB;cAOlD,wCAAsC,EAAA,yBAAA,EAAA;;;;;;;;;;;KAiBvC,mCAAmC,EAAE,kBACtC;cA4CE,yCAAuC,EAAA,aAAA,EAAA,yBAAA,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAKxC,oCAAoC,EAAE,mBACvC;cAGL,iCAA+B,EAAA;;;;;KAOzB,yBAAyB,EAAE,kBAAkB;cAE5C,+BAA6B,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAwC9B,0BAA0B,EAAE,mBAAmB"}
@@ -1,11 +1,12 @@
1
1
  import { ConfigurationError } from "../../shared/errors.js";
2
2
  import { U128Schema } from "../../shared/schemas.js";
3
+ import { enumLabelSchema } from "../../shared/proto-enum-codec.js";
3
4
  import { fromU128, toU128 } from "../../utils/u128.js";
4
5
  import { quantityInputToE18, scaledToDecimalOutput } from "../../shared/decimal-surface.js";
5
6
  import { PositiveUint32InputSchema } from "../shared.js";
6
7
  import { AccountScopeInputEntries, accountScopeToSubaccountId } from "../../shared/account-scope.js";
7
8
  import "../../gen/chain/withdraw/v1/withdraw_pb.js";
8
- import { TradingWithdrawActionCodec, WithdrawDestinationValidationCodeCodec } from "./trading-withdraws.codecs.js";
9
+ import { TradingWithdrawActionCodec, WalletAssetUnavailableReasonCodec, WithdrawDestinationValidationCodeCodec } from "./trading-withdraws.codecs.js";
9
10
  import * as v from "valibot";
10
11
  //#region src/services/trading-withdraws/trading-withdraws.schemas.ts
11
12
  const DEFAULT_DEADLINE_SECONDS = 300;
@@ -75,6 +76,7 @@ function createCreateTradingWithdrawToExternalChainInputSchema(scales) {
75
76
  ...AccountScopeInputEntries,
76
77
  assetId: PositiveUint32InputSchema,
77
78
  quantity: v.string(),
79
+ /** Polyester chain ID of the network: a Zipper chain's `chainId`, not its `nativeChainId`. */
78
80
  destinationChainId: v.pipe(v.number(), v.integer(), v.gtValue(0), v.maxValue(Number.MAX_SAFE_INTEGER)),
79
81
  destinationAddress: v.pipe(v.string(), v.trim(), v.minLength(1)),
80
82
  idempotencyKey: v.pipe(v.string(), v.trim(), v.minLength(1)),
@@ -107,6 +109,7 @@ function createCreateTradingWithdrawToExternalChainInputSchema(scales) {
107
109
  const CreateTradingWithdrawResultSchema = v.object({ intentId: v.pipe(v.string(), v.trim(), v.minLength(1)) });
108
110
  const CreateWalletTradingWithdrawResultSchema = CreateTradingWithdrawResultSchema;
109
111
  const ValidateWithdrawDestinationInputSchema = v.pipe(v.strictObject({
112
+ /** Polyester chain ID of the network: a Zipper chain's `chainId`, not its `nativeChainId`. */
110
113
  destinationChainId: v.pipe(v.number(), v.integer(), v.gtValue(0), v.maxValue(Number.MAX_SAFE_INTEGER)),
111
114
  destinationAddress: v.pipe(v.string(), v.trim(), v.minLength(1))
112
115
  }), v.transform((input) => ({
@@ -153,7 +156,18 @@ const GetWalletBalancesResultSchema = v.object({
153
156
  }), v.transform(({ amountE18, ...balance }) => ({
154
157
  ...balance,
155
158
  amount: scaledToDecimalOutput(fromU128(amountE18), 18)
156
- }))))
159
+ })))),
160
+ /**
161
+ * zTokens whose balance could not be read: unknown, not zero. Read again later; the read is
162
+ * complete only when this is empty.
163
+ */
164
+ unavailableAssets: v.array(v.object({
165
+ zippedAssetId: v.number(),
166
+ unifiedAssetId: v.number(),
167
+ chainId: v.number(),
168
+ ztokenAddress: v.string(),
169
+ reason: v.optional(enumLabelSchema(WalletAssetUnavailableReasonCodec.protoToOutput), 0)
170
+ }))
157
171
  });
158
172
  //#endregion
159
173
  export { CreateTradingWithdrawResultSchema, CreateWalletTradingWithdrawResultSchema, GetWalletBalancesInputSchema, GetWalletBalancesResultSchema, ValidateWithdrawDestinationInputSchema, ValidateWithdrawDestinationResultSchema, createCreateTradingWithdrawToExternalChainInputSchema, createCreateTradingWithdrawToFundingInputSchema, renewTradingWithdrawPayload };
@@ -1 +1 @@
1
- {"version":3,"file":"trading-withdraws.schemas.js","names":[],"sources":["../../../src/services/trading-withdraws/trading-withdraws.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { PositiveUint32InputSchema } from \"../shared.js\";\nimport {\n E18_SCALE,\n quantityInputToE18,\n scaledToDecimalOutput,\n type SdkScales,\n} from \"../../shared/decimal-surface.js\";\nimport {\n AccountScopeInputEntries,\n accountScopeToSubaccountId,\n} from \"../../shared/account-scope.js\";\nimport type * as Proto from \"../../gen/chain/withdraw/v1/withdraw_pb.js\";\nimport { WithdrawDestinationValidationCode } from \"../../gen/chain/withdraw/v1/withdraw_pb.js\";\nimport { fromU128, toU128, type U128Value } from \"../../utils/u128.js\";\nimport { U128Schema } from \"../../shared/schemas.js\";\nimport { ConfigurationError } from \"../../shared/errors.js\";\nimport {\n TradingWithdrawActionCodec,\n WithdrawDestinationValidationCodeCodec,\n} from \"./trading-withdraws.codecs.js\";\n\nconst DEFAULT_DEADLINE_SECONDS = 5 * 60;\n\nexport type TradingWithdrawIntentPayloadRequest = {\n action: Proto.TradingWithdrawAction;\n assetId: number;\n destinationChainId: bigint;\n amountE18: U128Value;\n deadlineTsSec: bigint;\n nonce: U128Value;\n destinationAddress: string;\n idempotencyKey: string;\n};\n\ntype CreateTradingWithdrawRequestBase = {\n subaccountId: bigint | undefined;\n payload: TradingWithdrawIntentPayloadRequest;\n};\n\nfunction createNonce(): bigint {\n const random = globalThis.crypto?.getRandomValues?.bind(globalThis.crypto);\n if (!random) {\n throw new ConfigurationError(\"Secure nonce generation requires crypto.getRandomValues.\");\n }\n\n const bytes = new BigUint64Array(1);\n random(bytes);\n const nonce = bytes[0]!;\n return nonce === 0n ? 1n : nonce;\n}\n\nfunction createTradingWithdrawPayload(input: {\n action: Proto.TradingWithdrawAction;\n assetId: number;\n destinationChainId: bigint;\n quantityScaled: bigint;\n destinationAddress: string;\n idempotencyKey: string;\n deadline: Date | undefined;\n}): TradingWithdrawIntentPayloadRequest {\n return {\n action: input.action,\n assetId: input.assetId,\n destinationChainId: input.destinationChainId,\n amountE18: toU128(input.quantityScaled),\n deadlineTsSec: BigInt(\n input.deadline\n ? Math.floor(input.deadline.getTime() / 1000)\n : Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS,\n ),\n nonce: toU128(createNonce()),\n destinationAddress: input.destinationAddress,\n idempotencyKey: input.idempotencyKey,\n };\n}\n\n/** The same withdraw with a fresh default deadline and nonce, for signing again. */\nexport function renewTradingWithdrawPayload(\n payload: TradingWithdrawIntentPayloadRequest,\n): TradingWithdrawIntentPayloadRequest {\n return {\n ...payload,\n deadlineTsSec: BigInt(Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS),\n nonce: toU128(createNonce()),\n };\n}\n\nexport function createCreateTradingWithdrawToFundingInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...AccountScopeInputEntries,\n assetId: PositiveUint32InputSchema,\n quantity: v.string(),\n idempotencyKey: v.pipe(v.string(), v.trim(), v.minLength(1)),\n destinationAddress: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n signerWallet: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n /**\n * When the signed authorization lapses. Defaults to five minutes from now\n * on the device clock.\n */\n deadline: v.optional(v.date()),\n }),\n v.transform((input): CreateTradingWithdrawRequestBase => {\n const quantityScaled = quantityInputToE18({\n scales,\n assetId: input.assetId,\n quantity: input.quantity,\n });\n return {\n subaccountId: accountScopeToSubaccountId(input.account),\n payload: createTradingWithdrawPayload({\n action: TradingWithdrawActionCodec.inputToProto.to_funding,\n assetId: input.assetId,\n destinationChainId: 0n,\n quantityScaled,\n destinationAddress: input.destinationAddress,\n idempotencyKey: input.idempotencyKey,\n deadline: input.deadline,\n }),\n };\n }),\n );\n}\n\nexport function createCreateTradingWithdrawToExternalChainInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...AccountScopeInputEntries,\n assetId: PositiveUint32InputSchema,\n quantity: v.string(),\n destinationChainId: v.pipe(\n v.number(),\n v.integer(),\n v.gtValue(0),\n v.maxValue(Number.MAX_SAFE_INTEGER),\n ),\n destinationAddress: v.pipe(v.string(), v.trim(), v.minLength(1)),\n idempotencyKey: v.pipe(v.string(), v.trim(), v.minLength(1)),\n signerWallet: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n /**\n * When the signed authorization lapses. Defaults to five minutes from now\n * on the device clock.\n */\n deadline: v.optional(v.date()),\n }),\n v.transform((input): CreateTradingWithdrawRequestBase => {\n const quantityScaled = quantityInputToE18({\n scales,\n assetId: input.assetId,\n quantity: input.quantity,\n });\n return {\n subaccountId: accountScopeToSubaccountId(input.account),\n payload: createTradingWithdrawPayload({\n action: TradingWithdrawActionCodec.inputToProto.to_external_chain,\n assetId: input.assetId,\n destinationChainId: BigInt(input.destinationChainId),\n quantityScaled,\n destinationAddress: input.destinationAddress,\n idempotencyKey: input.idempotencyKey,\n deadline: input.deadline,\n }),\n };\n }),\n );\n}\n\nexport type CreateTradingWithdrawToFundingInput = v.InferInput<\n ReturnType<typeof createCreateTradingWithdrawToFundingInputSchema>\n>;\n\nexport type CreateTradingWithdrawToFundingRequest = v.InferOutput<\n ReturnType<typeof createCreateTradingWithdrawToFundingInputSchema>\n>;\n\nexport type CreateTradingWithdrawToExternalChainInput = v.InferInput<\n ReturnType<typeof createCreateTradingWithdrawToExternalChainInputSchema>\n>;\n\nexport type CreateTradingWithdrawToExternalChainRequest = v.InferOutput<\n ReturnType<typeof createCreateTradingWithdrawToExternalChainInputSchema>\n>;\n\nexport const CreateTradingWithdrawResultSchema = v.object({\n intentId: v.pipe(v.string(), v.trim(), v.minLength(1)),\n});\n\nexport type CreateTradingWithdrawResult = v.InferOutput<typeof CreateTradingWithdrawResultSchema>;\n\nexport const CreateWalletTradingWithdrawResultSchema = CreateTradingWithdrawResultSchema;\nexport type CreateWalletTradingWithdrawResult = v.InferOutput<\n typeof CreateWalletTradingWithdrawResultSchema\n>;\n\nexport const ValidateWithdrawDestinationInputSchema = v.pipe(\n v.strictObject({\n destinationChainId: v.pipe(\n v.number(),\n v.integer(),\n v.gtValue(0),\n v.maxValue(Number.MAX_SAFE_INTEGER),\n ),\n destinationAddress: v.pipe(v.string(), v.trim(), v.minLength(1)),\n }),\n v.transform((input) => ({\n destinationChainId: BigInt(input.destinationChainId),\n destinationAddress: input.destinationAddress,\n })),\n);\n\nexport type ValidateWithdrawDestinationInput = v.InferInput<\n typeof ValidateWithdrawDestinationInputSchema\n>;\nexport type ValidateWithdrawDestinationRequest = v.InferOutput<\n typeof ValidateWithdrawDestinationInputSchema\n>;\n\nconst ValidWithdrawDestinationResultSchema = v.pipe(\n v.object({\n valid: v.literal(true),\n code: v.literal(WithdrawDestinationValidationCode.VALID),\n message: v.string(),\n canonicalDestinationAddress: v.pipe(v.string(), v.trim(), v.minLength(1)),\n }),\n v.transform((result) => ({\n ...result,\n code: WithdrawDestinationValidationCodeCodec.protoToOutput[result.code],\n })),\n);\n\nconst {\n [WithdrawDestinationValidationCode.VALID]: _validWithdrawDestinationCode,\n ...InvalidWithdrawDestinationCodeCodec\n} = WithdrawDestinationValidationCodeCodec.protoToOutput;\n\nconst InvalidWithdrawDestinationResultSchema = v.pipe(\n v.object({\n valid: v.literal(false),\n code: v.picklist([\n WithdrawDestinationValidationCode.RESULT_UNSPECIFIED,\n WithdrawDestinationValidationCode.INVALID_ADDRESS,\n WithdrawDestinationValidationCode.UNSUPPORTED_CHAIN,\n WithdrawDestinationValidationCode.POLYESTER_SMART_ACCOUNT,\n WithdrawDestinationValidationCode.TOKEN_CONTRACT,\n WithdrawDestinationValidationCode.DENYLISTED_ADDRESS,\n ]),\n message: v.string(),\n canonicalDestinationAddress: v.string(),\n }),\n v.transform((result) => ({\n ...result,\n code: InvalidWithdrawDestinationCodeCodec[result.code],\n })),\n);\n\nexport const ValidateWithdrawDestinationResultSchema = v.union([\n ValidWithdrawDestinationResultSchema,\n InvalidWithdrawDestinationResultSchema,\n]);\n\nexport type ValidateWithdrawDestinationResult = v.InferOutput<\n typeof ValidateWithdrawDestinationResultSchema\n>;\n\nconst WalletBalancesInputObjectSchema = v.strictObject({ ...AccountScopeInputEntries });\n\nexport const GetWalletBalancesInputSchema = v.pipe(\n WalletBalancesInputObjectSchema,\n v.transform(({ account }) => ({ subaccountId: accountScopeToSubaccountId(account) })),\n);\n\nexport type GetWalletBalancesInput = v.InferInput<typeof WalletBalancesInputObjectSchema>;\n\nexport const GetWalletBalancesResultSchema = v.object({\n smartAccountAddress: v.string(),\n balances: v.array(\n v.pipe(\n v.object({\n zippedAssetId: v.number(),\n unifiedAssetId: v.number(),\n chainId: v.number(),\n ztokenAddress: v.string(),\n amountE18: v.optional(U128Schema),\n }),\n v.transform(({ amountE18, ...balance }) => ({\n ...balance,\n amount: scaledToDecimalOutput(fromU128(amountE18), E18_SCALE),\n })),\n ),\n ),\n});\n\n/**\n * zTokens the account's smart account wallet holds on Polyester Chain, read live from the\n * chain: for example a rejected withdrawal's refund, which stays there until moved. `amount`\n * is a decimal string (zTokens have 18 decimals); `chainId` is a `GetDepositWithdrawConfig`\n * chain. `balances` lists nonzero balances by `zippedAssetId` and is empty when there are none.\n */\nexport type GetWalletBalancesResult = v.InferOutput<typeof GetWalletBalancesResultSchema>;\n"],"mappings":";;;;;;;;;;AAsBA,MAAM,2BAA2B;AAkBjC,SAAS,cAAsB;CAC3B,MAAM,SAAS,WAAW,QAAQ,iBAAiB,KAAK,WAAW,MAAM;CACzE,IAAI,CAAC,QAC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AAO;CAClD,qBAAqB,EAAE,OAAO;CAC9B,UAAU,EAAE,MACR,EAAE,KACE,EAAE,OAAO;EACL,eAAe,EAAE,OAAO;EACxB,gBAAgB,EAAE,OAAO;EACzB,SAAS,EAAE,OAAO;EAClB,eAAe,EAAE,OAAO;EACxB,WAAW,EAAE,SAAS,UAAU;CACpC,CAAC,GACD,EAAE,WAAW,EAAE,WAAW,GAAG,eAAe;EACxC,GAAG;EACH,QAAQ,sBAAsB,SAAS,SAAS,GAAA,EAAY;CAChE,EAAE,CACN,CACJ;AACJ,CAAC"}
1
+ {"version":3,"file":"trading-withdraws.schemas.js","names":[],"sources":["../../../src/services/trading-withdraws/trading-withdraws.schemas.ts"],"sourcesContent":["import * as v from \"valibot\";\nimport { PositiveUint32InputSchema } from \"../shared.js\";\nimport {\n E18_SCALE,\n quantityInputToE18,\n scaledToDecimalOutput,\n type SdkScales,\n} from \"../../shared/decimal-surface.js\";\nimport {\n AccountScopeInputEntries,\n accountScopeToSubaccountId,\n} from \"../../shared/account-scope.js\";\nimport type * as Proto from \"../../gen/chain/withdraw/v1/withdraw_pb.js\";\nimport { WithdrawDestinationValidationCode } from \"../../gen/chain/withdraw/v1/withdraw_pb.js\";\nimport { fromU128, toU128, type U128Value } from \"../../utils/u128.js\";\nimport { U128Schema } from \"../../shared/schemas.js\";\nimport { ConfigurationError } from \"../../shared/errors.js\";\nimport { enumLabelSchema } from \"../../shared/proto-enum-codec.js\";\nimport {\n TradingWithdrawActionCodec,\n WalletAssetUnavailableReasonCodec,\n WithdrawDestinationValidationCodeCodec,\n} from \"./trading-withdraws.codecs.js\";\n\nconst DEFAULT_DEADLINE_SECONDS = 5 * 60;\n\nexport type TradingWithdrawIntentPayloadRequest = {\n action: Proto.TradingWithdrawAction;\n assetId: number;\n destinationChainId: bigint;\n amountE18: U128Value;\n deadlineTsSec: bigint;\n nonce: U128Value;\n destinationAddress: string;\n idempotencyKey: string;\n};\n\ntype CreateTradingWithdrawRequestBase = {\n subaccountId: bigint | undefined;\n payload: TradingWithdrawIntentPayloadRequest;\n};\n\nfunction createNonce(): bigint {\n const random = globalThis.crypto?.getRandomValues?.bind(globalThis.crypto);\n if (!random) {\n throw new ConfigurationError(\"Secure nonce generation requires crypto.getRandomValues.\");\n }\n\n const bytes = new BigUint64Array(1);\n random(bytes);\n const nonce = bytes[0]!;\n return nonce === 0n ? 1n : nonce;\n}\n\nfunction createTradingWithdrawPayload(input: {\n action: Proto.TradingWithdrawAction;\n assetId: number;\n destinationChainId: bigint;\n quantityScaled: bigint;\n destinationAddress: string;\n idempotencyKey: string;\n deadline: Date | undefined;\n}): TradingWithdrawIntentPayloadRequest {\n return {\n action: input.action,\n assetId: input.assetId,\n destinationChainId: input.destinationChainId,\n amountE18: toU128(input.quantityScaled),\n deadlineTsSec: BigInt(\n input.deadline\n ? Math.floor(input.deadline.getTime() / 1000)\n : Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS,\n ),\n nonce: toU128(createNonce()),\n destinationAddress: input.destinationAddress,\n idempotencyKey: input.idempotencyKey,\n };\n}\n\n/** The same withdraw with a fresh default deadline and nonce, for signing again. */\nexport function renewTradingWithdrawPayload(\n payload: TradingWithdrawIntentPayloadRequest,\n): TradingWithdrawIntentPayloadRequest {\n return {\n ...payload,\n deadlineTsSec: BigInt(Math.floor(Date.now() / 1000) + DEFAULT_DEADLINE_SECONDS),\n nonce: toU128(createNonce()),\n };\n}\n\nexport function createCreateTradingWithdrawToFundingInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...AccountScopeInputEntries,\n assetId: PositiveUint32InputSchema,\n quantity: v.string(),\n idempotencyKey: v.pipe(v.string(), v.trim(), v.minLength(1)),\n destinationAddress: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n signerWallet: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n /**\n * When the signed authorization lapses. Defaults to five minutes from now\n * on the device clock.\n */\n deadline: v.optional(v.date()),\n }),\n v.transform((input): CreateTradingWithdrawRequestBase => {\n const quantityScaled = quantityInputToE18({\n scales,\n assetId: input.assetId,\n quantity: input.quantity,\n });\n return {\n subaccountId: accountScopeToSubaccountId(input.account),\n payload: createTradingWithdrawPayload({\n action: TradingWithdrawActionCodec.inputToProto.to_funding,\n assetId: input.assetId,\n destinationChainId: 0n,\n quantityScaled,\n destinationAddress: input.destinationAddress,\n idempotencyKey: input.idempotencyKey,\n deadline: input.deadline,\n }),\n };\n }),\n );\n}\n\nexport function createCreateTradingWithdrawToExternalChainInputSchema(scales: SdkScales) {\n return v.pipe(\n v.strictObject({\n ...AccountScopeInputEntries,\n assetId: PositiveUint32InputSchema,\n quantity: v.string(),\n /** Polyester chain ID of the network: a Zipper chain's `chainId`, not its `nativeChainId`. */\n destinationChainId: v.pipe(\n v.number(),\n v.integer(),\n v.gtValue(0),\n v.maxValue(Number.MAX_SAFE_INTEGER),\n ),\n destinationAddress: v.pipe(v.string(), v.trim(), v.minLength(1)),\n idempotencyKey: v.pipe(v.string(), v.trim(), v.minLength(1)),\n signerWallet: v.optional(v.pipe(v.string(), v.trim()), \"\"),\n /**\n * When the signed authorization lapses. Defaults to five minutes from now\n * on the device clock.\n */\n deadline: v.optional(v.date()),\n }),\n v.transform((input): CreateTradingWithdrawRequestBase => {\n const quantityScaled = quantityInputToE18({\n scales,\n assetId: input.assetId,\n quantity: input.quantity,\n });\n return {\n subaccountId: accountScopeToSubaccountId(input.account),\n payload: createTradingWithdrawPayload({\n action: TradingWithdrawActionCodec.inputToProto.to_external_chain,\n assetId: input.assetId,\n destinationChainId: BigInt(input.destinationChainId),\n quantityScaled,\n destinationAddress: input.destinationAddress,\n idempotencyKey: input.idempotencyKey,\n deadline: input.deadline,\n }),\n };\n }),\n );\n}\n\nexport type CreateTradingWithdrawToFundingInput = v.InferInput<\n ReturnType<typeof createCreateTradingWithdrawToFundingInputSchema>\n>;\n\nexport type CreateTradingWithdrawToFundingRequest = v.InferOutput<\n ReturnType<typeof createCreateTradingWithdrawToFundingInputSchema>\n>;\n\nexport type CreateTradingWithdrawToExternalChainInput = v.InferInput<\n ReturnType<typeof createCreateTradingWithdrawToExternalChainInputSchema>\n>;\n\nexport type CreateTradingWithdrawToExternalChainRequest = v.InferOutput<\n ReturnType<typeof createCreateTradingWithdrawToExternalChainInputSchema>\n>;\n\nexport const CreateTradingWithdrawResultSchema = v.object({\n intentId: v.pipe(v.string(), v.trim(), v.minLength(1)),\n});\n\nexport type CreateTradingWithdrawResult = v.InferOutput<typeof CreateTradingWithdrawResultSchema>;\n\nexport const CreateWalletTradingWithdrawResultSchema = CreateTradingWithdrawResultSchema;\nexport type CreateWalletTradingWithdrawResult = v.InferOutput<\n typeof CreateWalletTradingWithdrawResultSchema\n>;\n\nexport const ValidateWithdrawDestinationInputSchema = v.pipe(\n v.strictObject({\n /** Polyester chain ID of the network: a Zipper chain's `chainId`, not its `nativeChainId`. */\n destinationChainId: v.pipe(\n v.number(),\n v.integer(),\n v.gtValue(0),\n v.maxValue(Number.MAX_SAFE_INTEGER),\n ),\n destinationAddress: v.pipe(v.string(), v.trim(), v.minLength(1)),\n }),\n v.transform((input) => ({\n destinationChainId: BigInt(input.destinationChainId),\n destinationAddress: input.destinationAddress,\n })),\n);\n\nexport type ValidateWithdrawDestinationInput = v.InferInput<\n typeof ValidateWithdrawDestinationInputSchema\n>;\nexport type ValidateWithdrawDestinationRequest = v.InferOutput<\n typeof ValidateWithdrawDestinationInputSchema\n>;\n\nconst ValidWithdrawDestinationResultSchema = v.pipe(\n v.object({\n valid: v.literal(true),\n code: v.literal(WithdrawDestinationValidationCode.VALID),\n message: v.string(),\n canonicalDestinationAddress: v.pipe(v.string(), v.trim(), v.minLength(1)),\n }),\n v.transform((result) => ({\n ...result,\n code: WithdrawDestinationValidationCodeCodec.protoToOutput[result.code],\n })),\n);\n\nconst {\n [WithdrawDestinationValidationCode.VALID]: _validWithdrawDestinationCode,\n ...InvalidWithdrawDestinationCodeCodec\n} = WithdrawDestinationValidationCodeCodec.protoToOutput;\n\nconst InvalidWithdrawDestinationResultSchema = v.pipe(\n v.object({\n valid: v.literal(false),\n code: v.picklist([\n WithdrawDestinationValidationCode.RESULT_UNSPECIFIED,\n WithdrawDestinationValidationCode.INVALID_ADDRESS,\n WithdrawDestinationValidationCode.UNSUPPORTED_CHAIN,\n WithdrawDestinationValidationCode.POLYESTER_SMART_ACCOUNT,\n WithdrawDestinationValidationCode.TOKEN_CONTRACT,\n WithdrawDestinationValidationCode.DENYLISTED_ADDRESS,\n ]),\n message: v.string(),\n canonicalDestinationAddress: v.string(),\n }),\n v.transform((result) => ({\n ...result,\n code: InvalidWithdrawDestinationCodeCodec[result.code],\n })),\n);\n\nexport const ValidateWithdrawDestinationResultSchema = v.union([\n ValidWithdrawDestinationResultSchema,\n InvalidWithdrawDestinationResultSchema,\n]);\n\nexport type ValidateWithdrawDestinationResult = v.InferOutput<\n typeof ValidateWithdrawDestinationResultSchema\n>;\n\nconst WalletBalancesInputObjectSchema = v.strictObject({ ...AccountScopeInputEntries });\n\nexport const GetWalletBalancesInputSchema = v.pipe(\n WalletBalancesInputObjectSchema,\n v.transform(({ account }) => ({ subaccountId: accountScopeToSubaccountId(account) })),\n);\n\nexport type GetWalletBalancesInput = v.InferInput<typeof WalletBalancesInputObjectSchema>;\n\nexport const GetWalletBalancesResultSchema = v.object({\n smartAccountAddress: v.string(),\n balances: v.array(\n v.pipe(\n v.object({\n zippedAssetId: v.number(),\n unifiedAssetId: v.number(),\n chainId: v.number(),\n ztokenAddress: v.string(),\n amountE18: v.optional(U128Schema),\n }),\n v.transform(({ amountE18, ...balance }) => ({\n ...balance,\n amount: scaledToDecimalOutput(fromU128(amountE18), E18_SCALE),\n })),\n ),\n ),\n /**\n * zTokens whose balance could not be read: unknown, not zero. Read again later; the read is\n * complete only when this is empty.\n */\n unavailableAssets: v.array(\n v.object({\n zippedAssetId: v.number(),\n unifiedAssetId: v.number(),\n chainId: v.number(),\n ztokenAddress: v.string(),\n reason: v.optional(enumLabelSchema(WalletAssetUnavailableReasonCodec.protoToOutput), 0),\n }),\n ),\n});\n\n/**\n * zTokens the account's smart account wallet holds on Polyester Chain, read live from the\n * chain: for example a rejected withdrawal's refund, which stays there until moved. `amount`\n * is a decimal string (zTokens have 18 decimals); `chainId` is a `GetDepositWithdrawConfig`\n * chain. `balances` lists nonzero balances by `zippedAssetId` and is empty when there are none.\n * An asset whose balance could not be read is in `unavailableAssets` instead, never in `balances`\n * as zero.\n */\nexport type GetWalletBalancesResult = v.InferOutput<typeof GetWalletBalancesResultSchema>;\n"],"mappings":";;;;;;;;;;;AAwBA,MAAM,2BAA2B;AAkBjC,SAAS,cAAsB;CAC3B,MAAM,SAAS,WAAW,QAAQ,iBAAiB,KAAK,WAAW,MAAM;CACzE,IAAI,CAAC,QACD,MAAM,IAAI,mBAAmB,0DAA0D;CAG3F,MAAM,wBAAQ,IAAI,eAAe,CAAC;CAClC,OAAO,KAAK;CACZ,MAAM,QAAQ,MAAM;CACpB,OAAO,UAAU,KAAK,KAAK;AAC/B;AAEA,SAAS,6BAA6B,OAQE;CACpC,OAAO;EACH,QAAQ,MAAM;EACd,SAAS,MAAM;EACf,oBAAoB,MAAM;EAC1B,WAAW,OAAO,MAAM,cAAc;EACtC,eAAe,OACX,MAAM,WACA,KAAK,MAAM,MAAM,SAAS,QAAQ,IAAI,GAAI,IAC1C,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI,wBAC1C;EACA,OAAO,OAAO,YAAY,CAAC;EAC3B,oBAAoB,MAAM;EAC1B,gBAAgB,MAAM;CAC1B;AACJ;;AAGA,SAAgB,4BACZ,SACmC;CACnC,OAAO;EACH,GAAG;EACH,eAAe,OAAO,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI,IAAI,wBAAwB;EAC9E,OAAO,OAAO,YAAY,CAAC;CAC/B;AACJ;AAEA,SAAgB,gDAAgD,QAAmB;CAC/E,OAAO,EAAE,KACL,EAAE,aAAa;EACX,GAAG;EACH,SAAS;EACT,UAAU,EAAE,OAA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E,OAAO;CACL,OAAO,EAAE,QAAQ,KAAK;CACtB,MAAM,EAAE,SAAS;;;;;;;CAOjB,CAAC;CACD,SAAS,EAAE,OAAO;CAClB,6BAA6B,EAAE,OAAO;AAC1C,CAAC,GACD,EAAE,WAAW,YAAY;CACrB,GAAG;CACH,MAAM,oCAAoC,OAAO;AACrD,EAAE,CACN;AAEA,MAAa,0CAA0C,EAAE,MAAM,CAC3D,sCACA,sCACJ,CAAC;AAMD,MAAM,kCAAkC,EAAE,aAAa,EAAE,GAAG,yBAAyB,CAAC;AAEtF,MAAa,+BAA+B,EAAE,KAC1C,iCACA,EAAE,WAAW,EAAE,eAAe,EAAE,cAAc,2BAA2B,OAAO,EAAE,EAAE,CACxF;AAIA,MAAa,gCAAgC,EAAE,OAAO;CAClD,qBAAqB,EAAE,OAAO;CAC9B,UAAU,EAAE,MACR,EAAE,KACE,EAAE,OAAO;EACL,eAAe,EAAE,OAAO;EACxB,gBAAgB,EAAE,OAAO;EACzB,SAAS,EAAE,OAAO;EAClB,eAAe,EAAE,OAAO;EACxB,WAAW,EAAE,SAAS,UAAU;CACpC,CAAC,GACD,EAAE,WAAW,EAAE,WAAW,GAAG,eAAe;EACxC,GAAG;EACH,QAAQ,sBAAsB,SAAS,SAAS,GAAA,EAAY;CAChE,EAAE,CACN,CACJ;;;;;CAKA,mBAAmB,EAAE,MACjB,EAAE,OAAO;EACL,eAAe,EAAE,OAAO;EACxB,gBAAgB,EAAE,OAAO;EACzB,SAAS,EAAE,OAAO;EAClB,eAAe,EAAE,OAAO;EACxB,QAAQ,EAAE,SAAS,gBAAgB,kCAAkC,aAAa,GAAG,CAAC;CAC1F,CAAC,CACL;AACJ,CAAC"}
@@ -1,3 +1,4 @@
1
1
  import { CreateTradingWithdrawResult, CreateTradingWithdrawToExternalChainInput, CreateTradingWithdrawToFundingInput, GetWalletBalancesInput, GetWalletBalancesResult, ValidateWithdrawDestinationInput, ValidateWithdrawDestinationResult } from "./trading-withdraws.schemas.js";
2
2
  import { CreateTradingWithdrawToExternalChainServiceInput, CreateTradingWithdrawToFundingServiceInput, PreparedTradingWithdraw, TradingWithdrawSigningConfig, TradingWithdrawWalletSigner } from "./trading-withdraws.js";
3
- export type { CreateTradingWithdrawResult, CreateTradingWithdrawToExternalChainInput, CreateTradingWithdrawToExternalChainServiceInput, CreateTradingWithdrawToFundingInput, CreateTradingWithdrawToFundingServiceInput, GetWalletBalancesInput, GetWalletBalancesResult, PreparedTradingWithdraw, TradingWithdrawSigningConfig, TradingWithdrawWalletSigner, ValidateWithdrawDestinationInput, ValidateWithdrawDestinationResult };
3
+ import { WalletAssetUnavailableReasonValue } from "./trading-withdraws.codecs.js";
4
+ export type { CreateTradingWithdrawResult, CreateTradingWithdrawToExternalChainInput, CreateTradingWithdrawToExternalChainServiceInput, CreateTradingWithdrawToFundingInput, CreateTradingWithdrawToFundingServiceInput, GetWalletBalancesInput, GetWalletBalancesResult, PreparedTradingWithdraw, TradingWithdrawSigningConfig, TradingWithdrawWalletSigner, ValidateWithdrawDestinationInput, ValidateWithdrawDestinationResult, WalletAssetUnavailableReasonValue };