@bitgen/sdk 0.1.6 → 1.0.4

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 (338) hide show
  1. package/CHANGELOG.md +63 -2
  2. package/README.md +27 -106
  3. package/dist/cjs/client.d.ts +20 -8
  4. package/dist/cjs/client.d.ts.map +1 -1
  5. package/dist/cjs/client.js +33 -12
  6. package/dist/cjs/client.js.map +1 -1
  7. package/dist/cjs/constants.d.ts +256 -0
  8. package/dist/cjs/constants.d.ts.map +1 -0
  9. package/dist/cjs/constants.js +214 -0
  10. package/dist/cjs/constants.js.map +1 -0
  11. package/dist/cjs/error.d.ts +17 -10
  12. package/dist/cjs/error.d.ts.map +1 -1
  13. package/dist/cjs/error.js +25 -7
  14. package/dist/cjs/error.js.map +1 -1
  15. package/dist/cjs/http.d.ts +13 -8
  16. package/dist/cjs/http.d.ts.map +1 -1
  17. package/dist/cjs/http.js +135 -44
  18. package/dist/cjs/http.js.map +1 -1
  19. package/dist/cjs/index.d.ts +14 -1
  20. package/dist/cjs/index.d.ts.map +1 -1
  21. package/dist/cjs/index.js +30 -1
  22. package/dist/cjs/index.js.map +1 -1
  23. package/dist/cjs/resources/apikeys.d.ts +18 -0
  24. package/dist/cjs/resources/apikeys.d.ts.map +1 -0
  25. package/dist/cjs/resources/apikeys.js +31 -0
  26. package/dist/cjs/resources/apikeys.js.map +1 -0
  27. package/dist/cjs/resources/asset.d.ts +17 -5
  28. package/dist/cjs/resources/asset.d.ts.map +1 -1
  29. package/dist/cjs/resources/asset.js +17 -6
  30. package/dist/cjs/resources/asset.js.map +1 -1
  31. package/dist/cjs/resources/bank.d.ts +11 -6
  32. package/dist/cjs/resources/bank.d.ts.map +1 -1
  33. package/dist/cjs/resources/bank.js +17 -9
  34. package/dist/cjs/resources/bank.js.map +1 -1
  35. package/dist/cjs/resources/core.d.ts +12 -0
  36. package/dist/cjs/resources/core.d.ts.map +1 -0
  37. package/dist/cjs/resources/core.js +22 -0
  38. package/dist/cjs/resources/core.js.map +1 -0
  39. package/dist/cjs/resources/custody.d.ts +27 -0
  40. package/dist/cjs/resources/custody.d.ts.map +1 -0
  41. package/dist/cjs/resources/custody.js +38 -0
  42. package/dist/cjs/resources/custody.js.map +1 -0
  43. package/dist/cjs/resources/customer.d.ts +20 -0
  44. package/dist/cjs/resources/customer.d.ts.map +1 -0
  45. package/dist/cjs/resources/customer.js +38 -0
  46. package/dist/cjs/resources/customer.js.map +1 -0
  47. package/dist/cjs/resources/staking.d.ts +32 -0
  48. package/dist/cjs/resources/staking.d.ts.map +1 -0
  49. package/dist/cjs/resources/staking.js +69 -0
  50. package/dist/cjs/resources/staking.js.map +1 -0
  51. package/dist/cjs/resources/trading.d.ts +24 -0
  52. package/dist/cjs/resources/trading.d.ts.map +1 -0
  53. package/dist/cjs/resources/trading.js +41 -0
  54. package/dist/cjs/resources/trading.js.map +1 -0
  55. package/dist/cjs/resources/transaction.d.ts +6 -9
  56. package/dist/cjs/resources/transaction.d.ts.map +1 -1
  57. package/dist/cjs/resources/transaction.js +10 -15
  58. package/dist/cjs/resources/transaction.js.map +1 -1
  59. package/dist/cjs/resources/webhooks.d.ts +46 -0
  60. package/dist/cjs/resources/webhooks.d.ts.map +1 -0
  61. package/dist/cjs/resources/webhooks.js +142 -0
  62. package/dist/cjs/resources/webhooks.js.map +1 -0
  63. package/dist/cjs/types/apikeys.d.ts +43 -0
  64. package/dist/cjs/types/apikeys.d.ts.map +1 -0
  65. package/dist/cjs/types/apikeys.js +3 -0
  66. package/dist/cjs/types/apikeys.js.map +1 -0
  67. package/dist/cjs/types/asset.d.ts +57 -0
  68. package/dist/cjs/types/asset.d.ts.map +1 -0
  69. package/dist/cjs/types/asset.js +3 -0
  70. package/dist/cjs/types/asset.js.map +1 -0
  71. package/dist/cjs/types/bank.d.ts +58 -0
  72. package/dist/cjs/types/bank.d.ts.map +1 -0
  73. package/dist/cjs/types/bank.js +3 -0
  74. package/dist/cjs/types/bank.js.map +1 -0
  75. package/dist/cjs/types/core.d.ts +32 -0
  76. package/dist/cjs/types/core.d.ts.map +1 -0
  77. package/dist/cjs/types/core.js +3 -0
  78. package/dist/cjs/types/core.js.map +1 -0
  79. package/dist/cjs/types/custody.d.ts +50 -0
  80. package/dist/cjs/types/custody.d.ts.map +1 -0
  81. package/dist/cjs/types/custody.js +3 -0
  82. package/dist/cjs/types/custody.js.map +1 -0
  83. package/dist/cjs/types/customer.d.ts +190 -0
  84. package/dist/cjs/types/customer.d.ts.map +1 -0
  85. package/dist/cjs/types/customer.js +3 -0
  86. package/dist/cjs/types/customer.js.map +1 -0
  87. package/dist/cjs/types/index.d.ts +78 -194
  88. package/dist/cjs/types/index.d.ts.map +1 -1
  89. package/dist/cjs/types/index.js +0 -1
  90. package/dist/cjs/types/index.js.map +1 -1
  91. package/dist/cjs/types/staking.d.ts +88 -0
  92. package/dist/cjs/types/staking.d.ts.map +1 -0
  93. package/dist/cjs/types/staking.js +3 -0
  94. package/dist/cjs/types/staking.js.map +1 -0
  95. package/dist/cjs/types/trading.d.ts +51 -0
  96. package/dist/cjs/types/trading.d.ts.map +1 -0
  97. package/dist/cjs/types/trading.js +3 -0
  98. package/dist/cjs/types/trading.js.map +1 -0
  99. package/dist/cjs/types/transaction.d.ts +61 -0
  100. package/dist/cjs/types/transaction.d.ts.map +1 -0
  101. package/dist/cjs/types/transaction.js +3 -0
  102. package/dist/cjs/types/transaction.js.map +1 -0
  103. package/dist/cjs/types/webhooks.d.ts +55 -0
  104. package/dist/cjs/types/webhooks.d.ts.map +1 -0
  105. package/dist/cjs/types/webhooks.js +3 -0
  106. package/dist/cjs/types/webhooks.js.map +1 -0
  107. package/dist/cjs/utils.d.ts +21 -2
  108. package/dist/cjs/utils.d.ts.map +1 -1
  109. package/dist/cjs/utils.js +67 -4
  110. package/dist/cjs/utils.js.map +1 -1
  111. package/dist/cjs/version.d.ts +2 -0
  112. package/dist/cjs/version.d.ts.map +1 -0
  113. package/dist/cjs/version.js +6 -0
  114. package/dist/cjs/version.js.map +1 -0
  115. package/dist/esm/client.d.ts +20 -8
  116. package/dist/esm/client.d.ts.map +1 -1
  117. package/dist/esm/client.js +33 -12
  118. package/dist/esm/client.js.map +1 -1
  119. package/dist/esm/constants.d.ts +256 -0
  120. package/dist/esm/constants.d.ts.map +1 -0
  121. package/dist/esm/constants.js +211 -0
  122. package/dist/esm/constants.js.map +1 -0
  123. package/dist/esm/error.d.ts +17 -10
  124. package/dist/esm/error.d.ts.map +1 -1
  125. package/dist/esm/error.js +24 -6
  126. package/dist/esm/error.js.map +1 -1
  127. package/dist/esm/http.d.ts +13 -8
  128. package/dist/esm/http.d.ts.map +1 -1
  129. package/dist/esm/http.js +136 -45
  130. package/dist/esm/http.js.map +1 -1
  131. package/dist/esm/index.d.ts +14 -1
  132. package/dist/esm/index.d.ts.map +1 -1
  133. package/dist/esm/index.js +6 -0
  134. package/dist/esm/index.js.map +1 -1
  135. package/dist/esm/resources/apikeys.d.ts +18 -0
  136. package/dist/esm/resources/apikeys.d.ts.map +1 -0
  137. package/dist/esm/resources/apikeys.js +27 -0
  138. package/dist/esm/resources/apikeys.js.map +1 -0
  139. package/dist/esm/resources/asset.d.ts +17 -5
  140. package/dist/esm/resources/asset.d.ts.map +1 -1
  141. package/dist/esm/resources/asset.js +17 -6
  142. package/dist/esm/resources/asset.js.map +1 -1
  143. package/dist/esm/resources/bank.d.ts +11 -6
  144. package/dist/esm/resources/bank.d.ts.map +1 -1
  145. package/dist/esm/resources/bank.js +18 -10
  146. package/dist/esm/resources/bank.js.map +1 -1
  147. package/dist/esm/resources/core.d.ts +12 -0
  148. package/dist/esm/resources/core.d.ts.map +1 -0
  149. package/dist/esm/resources/core.js +18 -0
  150. package/dist/esm/resources/core.js.map +1 -0
  151. package/dist/esm/resources/custody.d.ts +27 -0
  152. package/dist/esm/resources/custody.d.ts.map +1 -0
  153. package/dist/esm/resources/custody.js +34 -0
  154. package/dist/esm/resources/custody.js.map +1 -0
  155. package/dist/esm/resources/customer.d.ts +20 -0
  156. package/dist/esm/resources/customer.d.ts.map +1 -0
  157. package/dist/esm/resources/customer.js +34 -0
  158. package/dist/esm/resources/customer.js.map +1 -0
  159. package/dist/esm/resources/staking.d.ts +32 -0
  160. package/dist/esm/resources/staking.d.ts.map +1 -0
  161. package/dist/esm/resources/staking.js +65 -0
  162. package/dist/esm/resources/staking.js.map +1 -0
  163. package/dist/esm/resources/trading.d.ts +24 -0
  164. package/dist/esm/resources/trading.d.ts.map +1 -0
  165. package/dist/esm/resources/trading.js +37 -0
  166. package/dist/esm/resources/trading.js.map +1 -0
  167. package/dist/esm/resources/transaction.d.ts +6 -9
  168. package/dist/esm/resources/transaction.d.ts.map +1 -1
  169. package/dist/esm/resources/transaction.js +11 -16
  170. package/dist/esm/resources/transaction.js.map +1 -1
  171. package/dist/esm/resources/webhooks.d.ts +46 -0
  172. package/dist/esm/resources/webhooks.d.ts.map +1 -0
  173. package/dist/esm/resources/webhooks.js +138 -0
  174. package/dist/esm/resources/webhooks.js.map +1 -0
  175. package/dist/esm/types/apikeys.d.ts +43 -0
  176. package/dist/esm/types/apikeys.d.ts.map +1 -0
  177. package/dist/esm/types/apikeys.js +2 -0
  178. package/dist/esm/types/apikeys.js.map +1 -0
  179. package/dist/esm/types/asset.d.ts +57 -0
  180. package/dist/esm/types/asset.d.ts.map +1 -0
  181. package/dist/esm/types/asset.js +2 -0
  182. package/dist/esm/types/asset.js.map +1 -0
  183. package/dist/esm/types/bank.d.ts +58 -0
  184. package/dist/esm/types/bank.d.ts.map +1 -0
  185. package/dist/esm/types/bank.js +2 -0
  186. package/dist/esm/types/bank.js.map +1 -0
  187. package/dist/esm/types/core.d.ts +32 -0
  188. package/dist/esm/types/core.d.ts.map +1 -0
  189. package/dist/esm/types/core.js +2 -0
  190. package/dist/esm/types/core.js.map +1 -0
  191. package/dist/esm/types/custody.d.ts +50 -0
  192. package/dist/esm/types/custody.d.ts.map +1 -0
  193. package/dist/esm/types/custody.js +2 -0
  194. package/dist/esm/types/custody.js.map +1 -0
  195. package/dist/esm/types/customer.d.ts +190 -0
  196. package/dist/esm/types/customer.d.ts.map +1 -0
  197. package/dist/esm/types/customer.js +2 -0
  198. package/dist/esm/types/customer.js.map +1 -0
  199. package/dist/esm/types/index.d.ts +78 -194
  200. package/dist/esm/types/index.d.ts.map +1 -1
  201. package/dist/esm/types/index.js +0 -1
  202. package/dist/esm/types/index.js.map +1 -1
  203. package/dist/esm/types/staking.d.ts +88 -0
  204. package/dist/esm/types/staking.d.ts.map +1 -0
  205. package/dist/esm/types/staking.js +2 -0
  206. package/dist/esm/types/staking.js.map +1 -0
  207. package/dist/esm/types/trading.d.ts +51 -0
  208. package/dist/esm/types/trading.d.ts.map +1 -0
  209. package/dist/esm/types/trading.js +2 -0
  210. package/dist/esm/types/trading.js.map +1 -0
  211. package/dist/esm/types/transaction.d.ts +61 -0
  212. package/dist/esm/types/transaction.d.ts.map +1 -0
  213. package/dist/esm/types/transaction.js +2 -0
  214. package/dist/esm/types/transaction.js.map +1 -0
  215. package/dist/esm/types/webhooks.d.ts +55 -0
  216. package/dist/esm/types/webhooks.d.ts.map +1 -0
  217. package/dist/esm/types/webhooks.js +2 -0
  218. package/dist/esm/types/webhooks.js.map +1 -0
  219. package/dist/esm/utils.d.ts +21 -2
  220. package/dist/esm/utils.d.ts.map +1 -1
  221. package/dist/esm/utils.js +62 -4
  222. package/dist/esm/utils.js.map +1 -1
  223. package/dist/esm/version.d.ts +2 -0
  224. package/dist/esm/version.d.ts.map +1 -0
  225. package/dist/esm/version.js +3 -0
  226. package/dist/esm/version.js.map +1 -0
  227. package/package.json +29 -12
  228. package/readme/concepts.md +128 -0
  229. package/readme/configuration.md +72 -0
  230. package/readme/errors.md +67 -0
  231. package/readme/installation.md +43 -0
  232. package/readme/media/activation.svg +58 -0
  233. package/readme/media/deposit-flow.svg +70 -0
  234. package/readme/media/order-buy.svg +43 -0
  235. package/readme/media/order-sell.svg +47 -0
  236. package/readme/media/purchase-flow.svg +61 -0
  237. package/readme/media/sale-flow.svg +61 -0
  238. package/readme/media/staking-position.svg +75 -0
  239. package/readme/media/transaction-lifecycle.svg +61 -0
  240. package/readme/media/webhook-delivery.svg +53 -0
  241. package/readme/media/withdrawal-flow.svg +64 -0
  242. package/readme/quick-start.md +87 -0
  243. package/readme/resource/apikeys.md +103 -0
  244. package/readme/resource/asset.md +121 -0
  245. package/readme/resource/bank.md +161 -0
  246. package/readme/resource/core.md +91 -0
  247. package/readme/resource/custody.md +166 -0
  248. package/readme/resource/customer.md +210 -0
  249. package/readme/resource/staking.md +281 -0
  250. package/readme/resource/trading.md +171 -0
  251. package/readme/resource/transaction.md +110 -0
  252. package/readme/resource/webhooks.md +309 -0
  253. package/src/client.ts +46 -0
  254. package/src/constants.ts +281 -0
  255. package/src/error.ts +36 -0
  256. package/src/http.ts +201 -0
  257. package/src/index.ts +111 -0
  258. package/src/resources/apikeys.ts +30 -0
  259. package/src/resources/asset.ts +28 -0
  260. package/src/resources/bank.ts +39 -0
  261. package/src/resources/core.ts +19 -0
  262. package/src/resources/custody.ts +37 -0
  263. package/src/resources/customer.ts +46 -0
  264. package/src/resources/staking.ts +88 -0
  265. package/src/resources/trading.ts +41 -0
  266. package/src/resources/transaction.ts +20 -0
  267. package/src/resources/webhooks.ts +169 -0
  268. package/src/types/apikeys.ts +35 -0
  269. package/src/types/asset.ts +59 -0
  270. package/src/types/bank.ts +60 -0
  271. package/src/types/core.ts +32 -0
  272. package/src/types/custody.ts +40 -0
  273. package/src/types/customer.ts +189 -0
  274. package/src/types/index.ts +215 -0
  275. package/src/types/staking.ts +87 -0
  276. package/src/types/trading.ts +56 -0
  277. package/src/types/transaction.ts +62 -0
  278. package/src/types/webhooks.ts +60 -0
  279. package/src/utils.ts +74 -0
  280. package/src/version.ts +2 -0
  281. package/dist/cjs/resources/order.d.ts +0 -17
  282. package/dist/cjs/resources/order.d.ts.map +0 -1
  283. package/dist/cjs/resources/order.js +0 -30
  284. package/dist/cjs/resources/order.js.map +0 -1
  285. package/dist/cjs/resources/stats.d.ts +0 -11
  286. package/dist/cjs/resources/stats.d.ts.map +0 -1
  287. package/dist/cjs/resources/stats.js +0 -18
  288. package/dist/cjs/resources/stats.js.map +0 -1
  289. package/dist/cjs/resources/user.d.ts +0 -22
  290. package/dist/cjs/resources/user.d.ts.map +0 -1
  291. package/dist/cjs/resources/user.js +0 -37
  292. package/dist/cjs/resources/user.js.map +0 -1
  293. package/dist/cjs/resources/wallet.d.ts +0 -11
  294. package/dist/cjs/resources/wallet.d.ts.map +0 -1
  295. package/dist/cjs/resources/wallet.js +0 -19
  296. package/dist/cjs/resources/wallet.js.map +0 -1
  297. package/dist/esm/resources/order.d.ts +0 -17
  298. package/dist/esm/resources/order.d.ts.map +0 -1
  299. package/dist/esm/resources/order.js +0 -26
  300. package/dist/esm/resources/order.js.map +0 -1
  301. package/dist/esm/resources/stats.d.ts +0 -11
  302. package/dist/esm/resources/stats.d.ts.map +0 -1
  303. package/dist/esm/resources/stats.js +0 -14
  304. package/dist/esm/resources/stats.js.map +0 -1
  305. package/dist/esm/resources/user.d.ts +0 -22
  306. package/dist/esm/resources/user.d.ts.map +0 -1
  307. package/dist/esm/resources/user.js +0 -33
  308. package/dist/esm/resources/user.js.map +0 -1
  309. package/dist/esm/resources/wallet.d.ts +0 -11
  310. package/dist/esm/resources/wallet.d.ts.map +0 -1
  311. package/dist/esm/resources/wallet.js +0 -15
  312. package/dist/esm/resources/wallet.js.map +0 -1
  313. package/dist/types/client.d.ts +0 -19
  314. package/dist/types/client.d.ts.map +0 -1
  315. package/dist/types/error.d.ts +0 -15
  316. package/dist/types/error.d.ts.map +0 -1
  317. package/dist/types/http.d.ts +0 -21
  318. package/dist/types/http.d.ts.map +0 -1
  319. package/dist/types/index.d.ts +0 -4
  320. package/dist/types/index.d.ts.map +0 -1
  321. package/dist/types/resources/asset.d.ts +0 -11
  322. package/dist/types/resources/asset.d.ts.map +0 -1
  323. package/dist/types/resources/bank.d.ts +0 -13
  324. package/dist/types/resources/bank.d.ts.map +0 -1
  325. package/dist/types/resources/order.d.ts +0 -17
  326. package/dist/types/resources/order.d.ts.map +0 -1
  327. package/dist/types/resources/stats.d.ts +0 -11
  328. package/dist/types/resources/stats.d.ts.map +0 -1
  329. package/dist/types/resources/transaction.d.ts +0 -15
  330. package/dist/types/resources/transaction.d.ts.map +0 -1
  331. package/dist/types/resources/user.d.ts +0 -22
  332. package/dist/types/resources/user.d.ts.map +0 -1
  333. package/dist/types/resources/wallet.d.ts +0 -11
  334. package/dist/types/resources/wallet.d.ts.map +0 -1
  335. package/dist/types/types/index.d.ts +0 -213
  336. package/dist/types/types/index.d.ts.map +0 -1
  337. package/dist/types/utils.d.ts +0 -7
  338. package/dist/types/utils.d.ts.map +0 -1
package/src/http.ts ADDED
@@ -0,0 +1,201 @@
1
+ import { Env } from './constants.js'
2
+ import { BitgenError, MAX_CODE_LENGTH } from './error.js'
3
+ import type { BitgenConfig, BitgenErrorBody } from './types/index.js'
4
+ import { VERSION } from './version.js'
5
+
6
+ const LOCALHOST_PORT = 3002
7
+
8
+ /** Default request timeout, in seconds (`BitgenConfig.timeout`) */
9
+ const DEFAULT_TIMEOUT = 30
10
+ /** Largest timeout, in seconds: `setTimeout` — hence `AbortSignal.timeout` — accepts at most 2^31 − 1 ms */
11
+ const MAX_TIMEOUT = 2_147_483
12
+
13
+ type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'
14
+
15
+ /** Query string entries — `undefined` and `null` are skipped */
16
+ export type Query = Record<string, string | number | boolean | null | undefined>
17
+
18
+ interface RequestOptions {
19
+ method?: HttpMethod
20
+ body?: unknown
21
+ query?: Query | undefined
22
+ }
23
+
24
+ export class HttpClient {
25
+ /** Organization uuid of the key — resources use it where the API expects the organization */
26
+ readonly scope: string
27
+ private readonly baseUrl: string
28
+ private readonly headers: Record<string, string>
29
+ /** Request timeout in milliseconds (`BitgenConfig.timeout` × 1000), `0` = none */
30
+ private readonly timeout: number
31
+
32
+ constructor(config: BitgenConfig) {
33
+ if (typeof fetch !== 'function') {
34
+ throw new Error('@bitgen/sdk needs a global fetch: use Node.js 20 or later')
35
+ }
36
+ requireHeaderValue(config.scope, 'scope')
37
+ requireHeaderValue(config.apiKey, 'apiKey')
38
+
39
+ this.scope = config.scope
40
+ this.baseUrl = resolveBaseUrl(config)
41
+ this.timeout = resolveTimeout(config.timeout)
42
+ this.headers = {
43
+ 'Content-Type': 'application/json',
44
+ 'User-Agent': `bitgen-sdk-nodejs/${VERSION}`,
45
+ 'BITGEN-Scope': config.scope,
46
+ 'Api-key': config.apiKey,
47
+ }
48
+ }
49
+
50
+ async request<T>(path: string, options: RequestOptions = {}): Promise<T> {
51
+ const { method = 'GET', body, query } = options
52
+
53
+ // Build URL with optional query params — undefined and null entries are skipped
54
+ const url = new URL(path, this.baseUrl)
55
+ if (query) {
56
+ for (const [key, value] of Object.entries(query)) {
57
+ if (value !== undefined && value !== null) {
58
+ url.searchParams.set(key, String(value))
59
+ }
60
+ }
61
+ }
62
+
63
+ // Redirects are never followed: the API does not redirect, and following one would replay the key to another host
64
+ const init: RequestInit = { method, headers: this.headers, redirect: 'manual' }
65
+ if (body !== undefined) {
66
+ init.body = JSON.stringify(body)
67
+ }
68
+ const signal = this.timeout > 0 ? AbortSignal.timeout(this.timeout) : undefined
69
+ if (signal) {
70
+ init.signal = signal
71
+ }
72
+
73
+ let response: Response
74
+ let text: string
75
+ try {
76
+ response = await fetch(url, init)
77
+ text = response.status === 204 ? '' : await response.text()
78
+ } catch (cause) {
79
+ // No HTTP response at all: our own timeout fired, or the network failed (DNS, refused, TLS…)
80
+ const code = signal?.aborted ? 'request_timeout' : 'network_error'
81
+ throw new BitgenError(0, { error: true, message: code, code: 0 }, { cause })
82
+ }
83
+
84
+ // v4 sends the real HTTP status: anything outside 2xx is an error
85
+ if (!response.ok) {
86
+ throw new BitgenError(response.status, parseErrorBody(text) ?? rawBody(text, response))
87
+ }
88
+
89
+ // 204 No Content or empty body — nothing to parse
90
+ if (text.trim() === '') {
91
+ return undefined as unknown as T
92
+ }
93
+
94
+ try {
95
+ return JSON.parse(text) as T
96
+ } catch {
97
+ // A 2xx that is not JSON (proxy page…): reported like a non-JSON error, never rethrown raw
98
+ throw new BitgenError(response.status, rawBody(text, response))
99
+ }
100
+ }
101
+
102
+ get<T>(path: string, query?: Query): Promise<T> {
103
+ return this.request<T>(path, { method: 'GET', query })
104
+ }
105
+
106
+ post<T>(path: string, body?: unknown): Promise<T> {
107
+ return this.request<T>(path, { method: 'POST', body })
108
+ }
109
+
110
+ put<T>(path: string, body?: unknown): Promise<T> {
111
+ return this.request<T>(path, { method: 'PUT', body })
112
+ }
113
+
114
+ patch<T>(path: string, body?: unknown): Promise<T> {
115
+ return this.request<T>(path, { method: 'PATCH', body })
116
+ }
117
+
118
+ delete<T>(path: string, body?: unknown): Promise<T> {
119
+ return this.request<T>(path, { method: 'DELETE', body })
120
+ }
121
+ }
122
+
123
+ /** Fails fast on a missing, empty or non-printable-ASCII header value — never echoes the value itself */
124
+ function requireHeaderValue(value: unknown, name: string): void {
125
+ if (typeof value !== 'string' || value.trim() === '') {
126
+ throw new TypeError(`BitgenConfig.${name} must be a non-empty string`)
127
+ }
128
+ if (!/^[\x20-\x7E]+$/.test(value)) {
129
+ throw new TypeError(`BitgenConfig.${name} contains invalid characters (printable ASCII expected)`)
130
+ }
131
+ }
132
+
133
+ /** Seconds from the config → integer milliseconds for `AbortSignal.timeout` (`0` = no timeout, any positive value ≥ 1 ms) */
134
+ function resolveTimeout(value: number | undefined): number {
135
+ const seconds = value === undefined ? DEFAULT_TIMEOUT : value
136
+ if (typeof seconds !== 'number' || !Number.isFinite(seconds) || seconds < 0 || seconds > MAX_TIMEOUT) {
137
+ throw new TypeError(`BitgenConfig.timeout must be a number of seconds between 0 (no timeout) and ${MAX_TIMEOUT}`)
138
+ }
139
+ return seconds === 0 ? 0 : Math.max(1, Math.round(seconds * 1000))
140
+ }
141
+
142
+ function resolveBaseUrl(config: BitgenConfig): string {
143
+ if (config.port !== undefined && (!Number.isInteger(config.port) || config.port < 1 || config.port > 65535)) {
144
+ throw new TypeError('BitgenConfig.port must be an integer between 1 and 65535')
145
+ }
146
+ const base = resolveBase(config)
147
+ try {
148
+ new URL(base)
149
+ } catch {
150
+ throw new TypeError('BitgenConfig.host and port do not form a valid URL')
151
+ }
152
+ return base
153
+ }
154
+
155
+ function resolveBase(config: BitgenConfig): string {
156
+ // Custom host (e.g. Docker container): bare hostname, scheme and port come from isSsl / port
157
+ if (config.host !== undefined) {
158
+ // Letters, digits, dots, hyphens (and underscores of internal DNS names): a scheme, a port, a path, userinfo (`me@attacker`) or a bracketed IPv6 are refused
159
+ if (typeof config.host !== 'string' || !/^[A-Za-z0-9._-]+$/.test(config.host)) {
160
+ throw new TypeError('BitgenConfig.host must be a bare hostname (no scheme, port or path): use port and isSsl')
161
+ }
162
+ const port = config.port ?? 80
163
+ const scheme = config.isSsl !== false ? 'https' : 'http'
164
+ return `${scheme}://${config.host}:${port}`
165
+ }
166
+
167
+ const env = config.env ?? Env.PRODUCTION
168
+ switch (env) {
169
+ case Env.PRODUCTION: return 'https://api.bitgen.com'
170
+ case Env.SANDBOX: return 'https://api.sandbox.bitgen.com'
171
+ case Env.STAGING: return 'https://api.staging.btgn.dev'
172
+ case Env.LOCALHOST: return `http://localhost:${config.port ?? LOCALHOST_PORT}`
173
+ default:
174
+ // The value given is not echoed: a config mix-up must not leak into logs
175
+ throw new TypeError(`BitgenConfig.env must be one of ${Object.values(Env).join(', ')} (see Env)`)
176
+ }
177
+ }
178
+
179
+ /** Error body built from a non-JSON response: the raw text, truncated, stands for the code */
180
+ function rawBody(text: string, response: Response): BitgenErrorBody {
181
+ const message = text.trim().slice(0, MAX_CODE_LENGTH) || response.statusText || String(response.status)
182
+ return { error: true, message, code: response.status }
183
+ }
184
+
185
+ /** Returns the parsed body when it is a v4 error payload `{ error: true, message, code }`, null otherwise */
186
+ function parseErrorBody(text: string): BitgenErrorBody | null {
187
+ try {
188
+ const data: unknown = JSON.parse(text)
189
+ if (
190
+ typeof data === 'object' &&
191
+ data !== null &&
192
+ (data as { error?: unknown }).error === true &&
193
+ typeof (data as { message?: unknown }).message === 'string'
194
+ ) {
195
+ return data as BitgenErrorBody
196
+ }
197
+ } catch {
198
+ // not JSON
199
+ }
200
+ return null
201
+ }
package/src/index.ts ADDED
@@ -0,0 +1,111 @@
1
+ import { Env, Asset as AssetCodes } from './constants.js'
2
+ import type { Asset as AssetType } from './types/index.js'
3
+
4
+ export { BitgenClient } from './client.js'
5
+ export { BitgenError } from './error.js'
6
+ export { Env }
7
+
8
+ // Enumerated values — each name is both the frozen object of constants and the type of its values (`CoreType.STAKING`)
9
+ export {
10
+ ApikeyState,
11
+ AssetState,
12
+ BankDirection,
13
+ CoreState,
14
+ CoreType,
15
+ CustomerState,
16
+ IdentityMode,
17
+ IdentityState,
18
+ Locale,
19
+ OrderSide,
20
+ OrderState,
21
+ OrganizationCategory,
22
+ StakingMovementKind,
23
+ StakingMovementState,
24
+ StakingPositionState,
25
+ SubscriberState,
26
+ TradingDirection,
27
+ TransactionDirection,
28
+ TransactionSource,
29
+ TransactionState,
30
+ WalletState,
31
+ WalletType,
32
+ WebhookEventName,
33
+ } from './constants.js'
34
+
35
+ /** Asset ISO codes (`Asset.ETH`) — `Asset` is also the type of an asset returned by `client.asset` */
36
+ export const Asset = AssetCodes
37
+ export type Asset = AssetType
38
+
39
+ export type {
40
+ BitgenConfig,
41
+ BitgenEnv,
42
+ UserRef,
43
+ Amount,
44
+ PageParams,
45
+ Page,
46
+ BitgenErrorBody,
47
+ History,
48
+ Created,
49
+ AssetRef,
50
+ AssetInput,
51
+ UserSummary,
52
+ OrganizationHub,
53
+ OrganizationSummary,
54
+ AssetTicker,
55
+ AssetFees,
56
+ AssetNetwork,
57
+ AssetNetworkType,
58
+ KycIdentity,
59
+ KybIdentity,
60
+ Identity,
61
+ CustomerAccount,
62
+ CustomerClient,
63
+ CustomerSetup,
64
+ CollaboratorLink,
65
+ ManagerLink,
66
+ CustomerAlert,
67
+ CustomerBusiness,
68
+ Customer,
69
+ AccountAddress,
70
+ Account,
71
+ CreateCustomerParams,
72
+ CustomerListParams,
73
+ UpdateCustomerParams,
74
+ BankAccount,
75
+ BankOperation,
76
+ BankOperationsParams,
77
+ BankWithdrawParams,
78
+ BankCreditParams,
79
+ Wallet,
80
+ CustodyPortfolio,
81
+ TravelRule,
82
+ CustodyWithdrawParams,
83
+ OrderUser,
84
+ OrderOrganization,
85
+ Order,
86
+ TradingOrderParams,
87
+ TradingListParams,
88
+ TransactionAlert,
89
+ Transaction,
90
+ TransactionListParams,
91
+ CoreConfigField,
92
+ Core,
93
+ CoreListParams,
94
+ CoreRef,
95
+ StakingPosition,
96
+ StakingMovement,
97
+ StakingOperation,
98
+ StakingPortfolio,
99
+ StakeParams,
100
+ StakingListParams,
101
+ StakingAmountParams,
102
+ WebhookType,
103
+ Subscriber,
104
+ WebhookSubscriptions,
105
+ DeliveryLog,
106
+ WebhookEvent,
107
+ VerifyInput,
108
+ Apikey,
109
+ ApikeyLog,
110
+ ApikeyListParams,
111
+ } from './types/index.js'
@@ -0,0 +1,30 @@
1
+ import type { HttpClient } from '../http.js'
2
+ import type { Apikey, ApikeyListParams, ApikeyLog, Page, PageParams } from '../types/index.js'
3
+ import { idOf, pathSegment } from '../utils.js'
4
+
5
+ /**
6
+ * `/organization/{scope}/apikeys` — permission `apikey.read`, read-only: a key cannot be created
7
+ * through the API (and the SDK does not revoke). `{organization}` is always the key's scope.
8
+ */
9
+ export class ApikeysResource {
10
+ constructor(private readonly http: HttpClient) {}
11
+
12
+ /** Keys of the organization — revoked ones with `includeRevoked` */
13
+ async list(params: ApikeyListParams = {}): Promise<Page<Apikey>> {
14
+ return await this.http.get(`/organization/${this.organization()}/apikeys`, { ...params })
15
+ }
16
+
17
+ /** One key by uuid, or by model */
18
+ async get(apikey: string | Apikey): Promise<Apikey> {
19
+ return await this.http.get(`/organization/${this.organization()}/apikeys/${pathSegment(idOf(apikey, 'apikey'), 'apikey')}`)
20
+ }
21
+
22
+ /** Calls made with the key: path, inputs (PII masked), status, error */
23
+ async logs(apikey: string | Apikey, params: PageParams = {}): Promise<Page<ApikeyLog>> {
24
+ return await this.http.get(`/organization/${this.organization()}/apikeys/${pathSegment(idOf(apikey, 'apikey'), 'apikey')}/logs`, { ...params })
25
+ }
26
+
27
+ private organization(): string {
28
+ return pathSegment(this.http.scope, 'scope')
29
+ }
30
+ }
@@ -0,0 +1,28 @@
1
+ import type { HttpClient } from '../http.js'
2
+ import type { Asset, AssetInput, AssetTicker, History, Page } from '../types/index.js'
3
+ import { assetId, pathSegment } from '../utils.js'
4
+
5
+ /** `/asset`, `/ticker` — permission `asset.read` */
6
+ export class AssetResource {
7
+ constructor(private readonly http: HttpClient) {}
8
+
9
+ /** List all assets */
10
+ async list(): Promise<Page<Asset>> {
11
+ return await this.http.get('/asset')
12
+ }
13
+
14
+ /** Get one asset by uuid or ISO code (any case, sent as is — `Asset.ETH`), or by model (its uuid is sent) */
15
+ async get(asset: AssetInput): Promise<Asset> {
16
+ return await this.http.get(`/asset/${pathSegment(assetId(asset), 'asset')}`)
17
+ }
18
+
19
+ /** Tickers of all assets */
20
+ async tickers(): Promise<Page<{ iso: string, ticker: AssetTicker }>> {
21
+ return await this.http.get('/ticker')
22
+ }
23
+
24
+ /** Ticker and EUR price history of one asset, by ISO code */
25
+ async ticker(iso: string): Promise<{ iso: string, ticker: AssetTicker, history: History }> {
26
+ return await this.http.get(`/ticker/${pathSegment(iso, 'iso')}`)
27
+ }
28
+ }
@@ -0,0 +1,39 @@
1
+ import type { HttpClient } from '../http.js'
2
+ import type {
3
+ BankAccount,
4
+ BankCreditParams,
5
+ BankOperation,
6
+ BankOperationsParams,
7
+ BankWithdrawParams,
8
+ Created,
9
+ Page,
10
+ UserRef,
11
+ } from '../types/index.js'
12
+ import { amount, pathSegment, resolveUuid } from '../utils.js'
13
+
14
+ /** `/bank` — permissions `bank.read`, `bank.write`. EUR ledger per customer; `{user}` = uuid or email. */
15
+ export class BankResource {
16
+ constructor(private readonly http: HttpClient) {}
17
+
18
+ /** EUR account of a customer — created on first read (requires a validated KYC or KYB) */
19
+ async get(user: UserRef): Promise<BankAccount> {
20
+ return await this.http.get(`/bank/${pathSegment(resolveUuid(user), 'user')}`)
21
+ }
22
+
23
+ /** EUR operations of a customer */
24
+ async operations(user: UserRef, params: BankOperationsParams = {}): Promise<Page<BankOperation>> {
25
+ return await this.http.get(`/bank/${pathSegment(resolveUuid(user), 'user')}/operations`, { ...params })
26
+ }
27
+
28
+ /** EUR withdrawal to the customer's IBAN — `iban` / `bank` / `bic` update the bank details first */
29
+ async withdraw(user: UserRef, params: BankWithdrawParams): Promise<{ transaction: string }> {
30
+ return await this.http.put(`/bank/${pathSegment(resolveUuid(user), 'user')}`, { ...params, amount: amount(params.amount) })
31
+ }
32
+
33
+ /** Inject an EUR deposit (logical credit) — targets `user` or the wire `message`; `reference` makes it idempotent */
34
+ async credit(params: BankCreditParams): Promise<Created> {
35
+ const { user, ...rest } = params
36
+ // `user` is optional (`message` is the alternative): absent or null → key omitted
37
+ return await this.http.post('/bank', { ...rest, amount: amount(params.amount), user: user === undefined || user === null ? undefined : resolveUuid(user) })
38
+ }
39
+ }
@@ -0,0 +1,19 @@
1
+ import type { HttpClient } from '../http.js'
2
+ import type { Core, CoreListParams, Page } from '../types/index.js'
3
+ import { assetFilter, idOf, pathSegment } from '../utils.js'
4
+
5
+ /** `/applications/core` — permission `core.read`. Platform catalogue of connectors, read-only. */
6
+ export class CoreResource {
7
+ constructor(private readonly http: HttpClient) {}
8
+
9
+ /** Connectors matching the filters — not paginated, `count` is everything that matches */
10
+ async list(params: CoreListParams = {}): Promise<Page<Core>> {
11
+ // spread first: the query keeps the order of the params, `asset` is replaced in place (absent or null = no filter)
12
+ return await this.http.get('/applications/core', { ...params, asset: assetFilter(params.asset) })
13
+ }
14
+
15
+ /** One connector by uuid or by model */
16
+ async get(core: string | Core): Promise<Core> {
17
+ return await this.http.get(`/applications/core/${pathSegment(idOf(core, 'core'), 'core')}`)
18
+ }
19
+ }
@@ -0,0 +1,37 @@
1
+ import type { HttpClient } from '../http.js'
2
+ import type { AssetInput, CustodyPortfolio, CustodyWithdrawParams, UserRef, Wallet } from '../types/index.js'
3
+ import { amount, assetId, pathSegment, resolveUuid } from '../utils.js'
4
+
5
+ /**
6
+ * `/custody` — permissions `custody.read`, `custody.write`. Crypto wallets per customer and asset.
7
+ * `{user}` = customer uuid — or the organization uuid (the scope) for its treasury wallets, read-only.
8
+ */
9
+ export class CustodyResource {
10
+ constructor(private readonly http: HttpClient) {}
11
+
12
+ /** Wallets of a customer (or of the organization), without `history` */
13
+ async wallets(user: UserRef): Promise<Wallet[]> {
14
+ return await this.http.get(`/custody/${pathSegment(resolveUuid(user), 'user')}`)
15
+ }
16
+
17
+ /**
18
+ * One wallet by asset uuid or iso, with `history`. A missing wallet is provisioned on first read
19
+ * (deposit address created at the custodian): the key then needs `custody.write`.
20
+ */
21
+ async wallet(user: UserRef, asset: AssetInput): Promise<Wallet> {
22
+ return await this.http.get(`/custody/${pathSegment(resolveUuid(user), 'user')}/${pathSegment(assetId(asset), 'asset')}`)
23
+ }
24
+
25
+ /** EUR value curve of the customer's custody (customers only) */
26
+ async portfolio(user: UserRef): Promise<CustodyPortfolio> {
27
+ return await this.http.get(`/custody/${pathSegment(resolveUuid(user), 'user')}/portfolio`)
28
+ }
29
+
30
+ /**
31
+ * On-chain withdrawal (customers only). The amount string goes to the API untouched — never
32
+ * rounded or reformatted. `transaction` is null while the analysis has not created the line yet.
33
+ */
34
+ async withdraw(user: UserRef, params: CustodyWithdrawParams): Promise<{ transaction: string | null }> {
35
+ return await this.http.put(`/custody/${pathSegment(resolveUuid(user), 'user')}`, { ...params, asset: assetId(params.asset), amount: amount(params.amount) })
36
+ }
37
+ }
@@ -0,0 +1,46 @@
1
+ import type { HttpClient } from '../http.js'
2
+ import type {
3
+ Account,
4
+ CreateCustomerParams,
5
+ Created,
6
+ Customer,
7
+ CustomerListParams,
8
+ Page,
9
+ UpdateCustomerParams,
10
+ UserRef,
11
+ } from '../types/index.js'
12
+ import { pathSegment, resolveUuid } from '../utils.js'
13
+
14
+ /** `/customer`, `/account` — permissions `customer.write`, `customer.read`, `account.read`, `account.write` */
15
+ export class CustomerResource {
16
+ constructor(private readonly http: HttpClient) {}
17
+
18
+ /**
19
+ * Create a customer of the key's organization — or attach an existing, KYC-validated account to it.
20
+ * By default an activation email is sent: the customer stays `CREATED` and invisible to the financial
21
+ * routes (bank, custody, trading, staking) until they activate (`account.needActivation: false` skips it).
22
+ */
23
+ async create(params: CreateCustomerParams): Promise<Created> {
24
+ const { group, ...rest } = params
25
+ // Only `manager` is taken from the caller: the organization is always the scope, and no role is ever sent (the API takes ROLE_USER)
26
+ return await this.http.post('/customer', { ...rest, group: { manager: group?.manager, organization: this.http.scope } })
27
+ }
28
+
29
+ /** List the organization's customers (a freshly created one appears as `CREATED`) */
30
+ async list(params: CustomerListParams = {}): Promise<Page<Customer>> {
31
+ return await this.http.get('/customer', { ...params })
32
+ }
33
+
34
+ /** Get an account by uuid, email (login) or model (`Created`, `Customer`…) */
35
+ async get(user: UserRef): Promise<Account> {
36
+ return await this.http.get(`/account/${pathSegment(resolveUuid(user), 'user')}`)
37
+ }
38
+
39
+ /** Update the settings a key may write: theme, locale, notifications — nothing else is sent */
40
+ async update(user: UserRef, params: UpdateCustomerParams): Promise<void> {
41
+ await this.http.put(`/account/${pathSegment(resolveUuid(user), 'user')}`, {
42
+ action: { theme: params.theme, locale: params.locale },
43
+ notifications: params.notifications,
44
+ })
45
+ }
46
+ }
@@ -0,0 +1,88 @@
1
+ import { CoreType } from '../constants.js'
2
+ import type { HttpClient } from '../http.js'
3
+ import type {
4
+ AssetInput,
5
+ Core,
6
+ Created,
7
+ Page,
8
+ PageParams,
9
+ StakeParams,
10
+ StakingAmountParams,
11
+ StakingListParams,
12
+ StakingMovement,
13
+ StakingOperation,
14
+ StakingPortfolio,
15
+ StakingPosition,
16
+ UserRef,
17
+ } from '../types/index.js'
18
+ import type { CoreResource } from './core.js'
19
+ import { amount, assetId, idOf, pathSegment, resolveUuid } from '../utils.js'
20
+
21
+ /**
22
+ * `/staking` — permissions `staking.write`, `staking.read` (`core.read` for `providers`).
23
+ * Two distinct ids: the **movement** uuid (returned by `stake`, handled by `get` / `list` / `movements`)
24
+ * and the **position** uuid (`movement.staking.uuid`, taken by `rewards` / `unstake`).
25
+ */
26
+ export class StakingResource {
27
+ constructor(private readonly http: HttpClient, private readonly core: CoreResource) {}
28
+
29
+ /** Staking providers = the `STAKING` cores, optionally for one asset — their `uuid` or `name` is the `provider` of `stake` */
30
+ async providers(asset?: AssetInput): Promise<Page<Core>> {
31
+ return await this.core.list(asset === undefined ? { type: CoreType.STAKING } : { type: CoreType.STAKING, asset })
32
+ }
33
+
34
+ /** Open a staking position — the amount is moved from the customer's custody to the provider's deposit address */
35
+ async stake(user: UserRef, params: StakeParams): Promise<Created> {
36
+ return await this.http.post('/staking', {
37
+ user: resolveUuid(user),
38
+ asset: assetId(params.asset),
39
+ amount: amount(params.amount),
40
+ provider: params.provider,
41
+ })
42
+ }
43
+
44
+ /** Movements of the organization, all states */
45
+ async list(params: StakingListParams = {}): Promise<Page<StakingMovement>> {
46
+ return await this.http.get('/staking', movementsQuery(params))
47
+ }
48
+
49
+ /** Movements still in progress: `REQUESTED`, `PENDING`, `FAILED` */
50
+ async movements(params: StakingListParams = {}): Promise<Page<StakingMovement>> {
51
+ return await this.http.get('/staking/movements', movementsQuery(params))
52
+ }
53
+
54
+ /** One movement by its uuid, or by model */
55
+ async get(movement: string | StakingMovement): Promise<StakingMovement> {
56
+ return await this.http.get(`/staking/${pathSegment(idOf(movement, 'movement'), 'movement')}`)
57
+ }
58
+
59
+ /** Claim the rewards of a position — `amount` absent = all of them. Deducted immediately, the transfer is executed by compliance. */
60
+ async rewards(position: string | StakingPosition, params: StakingAmountParams = {}): Promise<void> {
61
+ await this.http.put(`/staking/${pathSegment(idOf(position, 'position'), 'position')}/rewards`, amountBody(params))
62
+ }
63
+
64
+ /** Leave a position — `amount` absent = the whole position (a full exit ignores the minimums). Deducted immediately, the transfer is executed by compliance. */
65
+ async unstake(position: string | StakingPosition, params: StakingAmountParams = {}): Promise<void> {
66
+ await this.http.put(`/staking/${pathSegment(idOf(position, 'position'), 'position')}/unstake`, amountBody(params))
67
+ }
68
+
69
+ /** Staking operations of a customer */
70
+ async operations(user: UserRef, params: PageParams = {}): Promise<Page<StakingOperation>> {
71
+ return await this.http.get(`/staking/${pathSegment(resolveUuid(user), 'user')}/operations`, { ...params })
72
+ }
73
+
74
+ /** EUR balances and curves (capital, revenues) of a customer's staking */
75
+ async portfolio(user: UserRef): Promise<StakingPortfolio> {
76
+ return await this.http.get(`/staking/${pathSegment(resolveUuid(user), 'user')}/portfolio`)
77
+ }
78
+ }
79
+
80
+ function movementsQuery(params: StakingListParams): Record<string, string | number | undefined> {
81
+ const { user, ...rest } = params
82
+ return { user: user === undefined || user === null ? undefined : resolveUuid(user), ...rest }
83
+ }
84
+
85
+ /** `{ amount }` when given, `{}` otherwise — the API reads an absent amount as "everything" */
86
+ function amountBody(params: StakingAmountParams): { amount?: string } {
87
+ return params.amount === undefined ? {} : { amount: amount(params.amount) }
88
+ }
@@ -0,0 +1,41 @@
1
+ import type { HttpClient } from '../http.js'
2
+ import type { Order, OrderSide, OrderState, Page, TradingListParams, TradingOrderParams, UserRef } from '../types/index.js'
3
+ import { amount, assetFilter, assetId, idOf, pathSegment, resolveUuid } from '../utils.js'
4
+
5
+ /** `/trading` — permissions `trading.write`, `trading.read`. Buy or sell crypto for a customer. */
6
+ export class TradingResource {
7
+ constructor(private readonly http: HttpClient) {}
8
+
9
+ /** Buy crypto with EUR from the customer's bank account — `amount` in EUR (2 decimals max) */
10
+ async buy(user: UserRef, params: TradingOrderParams): Promise<{ tunnel: string, state: OrderState }> {
11
+ return await this.order(user, params, 'BUY')
12
+ }
13
+
14
+ /** Sell crypto from the customer's custody — `amount` is the crypto quantity (string recommended) */
15
+ async sell(user: UserRef, params: TradingOrderParams): Promise<{ tunnel: string, state: OrderState }> {
16
+ return await this.order(user, params, 'SELL')
17
+ }
18
+
19
+ /** One order by its uuid (the `tunnel` returned by `buy` / `sell`) or by model */
20
+ async get(order: string | Order): Promise<Order> {
21
+ return await this.http.get(`/trading/${pathSegment(idOf(order, 'order'), 'order')}`)
22
+ }
23
+
24
+ /** Orders of the organization, optionally filtered by customer, side and asset */
25
+ async list(params: TradingListParams = {}): Promise<Page<Order>> {
26
+ const { user } = params
27
+ // spread first: the query keeps the order of the params, `user` and `asset` are replaced in place (absent or null = no filter)
28
+ return await this.http.get('/trading/orders', { ...params, user: user === undefined || user === null ? undefined : resolveUuid(user), asset: assetFilter(params.asset) })
29
+ }
30
+
31
+ /** `POST /trading` — the customer must be an `ENABLED` member of the organization (uuid or model, no email here) */
32
+ private async order(user: UserRef, params: TradingOrderParams, mode: OrderSide): Promise<{ tunnel: string, state: OrderState }> {
33
+ return await this.http.post('/trading', {
34
+ user: resolveUuid(user),
35
+ asset: assetId(params.asset),
36
+ amount: amount(params.amount),
37
+ mode,
38
+ reference: params.reference,
39
+ })
40
+ }
41
+ }
@@ -0,0 +1,20 @@
1
+ import type { HttpClient } from '../http.js'
2
+ import type { Page, Transaction, TransactionListParams } from '../types/index.js'
3
+ import { assetFilter, idOf, pathSegment, resolveUuid } from '../utils.js'
4
+
5
+ /** `/transaction` — permission `transaction.read`. Unified journal of fiat and crypto movements, read-only. */
6
+ export class TransactionResource {
7
+ constructor(private readonly http: HttpClient) {}
8
+
9
+ /** Transactions of the organization, optionally filtered — `limit` up to 100 on this route */
10
+ async list(params: TransactionListParams = {}): Promise<Page<Transaction>> {
11
+ const { user } = params
12
+ // spread first: the query keeps the order of the params, `user` and `asset` are replaced in place (absent or null = no filter)
13
+ return await this.http.get('/transaction', { ...params, user: user === undefined || user === null ? undefined : resolveUuid(user), asset: assetFilter(params.asset) })
14
+ }
15
+
16
+ /** One transaction by uuid, by reference, or by model */
17
+ async get(transaction: string | Transaction): Promise<Transaction> {
18
+ return await this.http.get(`/transaction/${pathSegment(idOf(transaction, 'transaction'), 'transaction')}`)
19
+ }
20
+ }