@n1xyz/nord-ts 0.0.1 → 0.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 (237) hide show
  1. package/.eslintrc.js +11 -0
  2. package/README.md +148 -65
  3. package/dist/bridge/NordUser.d.ts +78 -0
  4. package/dist/bridge/NordUser.js +196 -0
  5. package/dist/bridge/client.d.ts +150 -0
  6. package/dist/bridge/client.js +394 -0
  7. package/dist/bridge/const.d.ts +23 -0
  8. package/dist/bridge/const.js +47 -0
  9. package/dist/bridge/index.d.ts +5 -0
  10. package/dist/bridge/index.js +23 -0
  11. package/dist/bridge/types.d.ts +118 -0
  12. package/dist/bridge/types.js +16 -0
  13. package/dist/bridge/utils.d.ts +64 -0
  14. package/dist/bridge/utils.js +131 -0
  15. package/dist/client.d.ts +70 -0
  16. package/dist/client.js +129 -0
  17. package/dist/const.d.ts +2 -5
  18. package/dist/const.js +18 -22
  19. package/dist/constants/endpoints.d.ts +65 -0
  20. package/dist/constants/endpoints.js +68 -0
  21. package/dist/gen/common.d.ts +6 -1
  22. package/dist/gen/common.js +19 -9
  23. package/dist/gen/nord.d.ts +75 -17
  24. package/dist/gen/nord.js +987 -423
  25. package/dist/idl/bridge.d.ts +2 -0
  26. package/dist/idl/bridge.js +703 -0
  27. package/dist/index.d.ts +8 -5
  28. package/dist/index.js +18 -2
  29. package/dist/models/account.d.ts +58 -0
  30. package/dist/models/account.js +6 -0
  31. package/dist/models/index.d.ts +8 -0
  32. package/dist/models/index.js +28 -0
  33. package/dist/models/market.d.ts +137 -0
  34. package/dist/models/market.js +6 -0
  35. package/dist/models/order.d.ts +211 -0
  36. package/dist/models/order.js +6 -0
  37. package/dist/models/token.d.ts +50 -0
  38. package/dist/models/token.js +6 -0
  39. package/dist/nord/Nord.d.ts +222 -49
  40. package/dist/nord/Nord.js +290 -278
  41. package/dist/nord/NordError.d.ts +23 -0
  42. package/dist/nord/NordError.js +48 -0
  43. package/dist/nord/NordImpl.d.ts +6 -2
  44. package/dist/nord/NordImpl.js +21 -1
  45. package/dist/nord/NordUser.d.ts +208 -42
  46. package/dist/nord/NordUser.js +389 -157
  47. package/dist/nord/Subscriber.d.ts +37 -0
  48. package/dist/nord/Subscriber.js +29 -0
  49. package/dist/nord/api/actions.d.ts +101 -0
  50. package/dist/nord/api/actions.js +250 -0
  51. package/dist/nord/api/core.d.ts +49 -0
  52. package/dist/nord/api/core.js +121 -0
  53. package/dist/nord/api/index.d.ts +1 -0
  54. package/dist/nord/api/index.js +17 -0
  55. package/dist/nord/api/market.d.ts +36 -0
  56. package/dist/nord/api/market.js +98 -0
  57. package/dist/nord/api/metrics.d.ts +67 -0
  58. package/dist/nord/api/metrics.js +132 -0
  59. package/dist/nord/api/orderFunctions.d.ts +168 -0
  60. package/dist/nord/api/orderFunctions.js +133 -0
  61. package/dist/nord/api/queries.d.ts +81 -0
  62. package/dist/nord/api/queries.js +187 -0
  63. package/dist/nord/client/Nord.d.ts +335 -0
  64. package/dist/nord/client/Nord.js +532 -0
  65. package/dist/nord/client/NordUser.d.ts +320 -0
  66. package/dist/nord/client/NordUser.js +701 -0
  67. package/dist/nord/core.d.ts +48 -0
  68. package/dist/nord/core.js +97 -0
  69. package/dist/nord/index.d.ts +9 -2
  70. package/dist/nord/index.js +30 -6
  71. package/dist/nord/market.d.ts +36 -0
  72. package/dist/nord/market.js +90 -0
  73. package/dist/nord/metrics.d.ts +67 -0
  74. package/dist/nord/metrics.js +124 -0
  75. package/dist/nord/models/Subscriber.d.ts +37 -0
  76. package/dist/nord/models/Subscriber.js +29 -0
  77. package/dist/nord/queries.d.ts +81 -0
  78. package/dist/nord/queries.js +181 -0
  79. package/dist/nord/types.d.ts +88 -0
  80. package/dist/nord/types.js +2 -0
  81. package/dist/nord/utils/NordError.d.ts +35 -0
  82. package/dist/nord/utils/NordError.js +46 -0
  83. package/dist/nord/websocket.d.ts +49 -0
  84. package/dist/nord/websocket.js +107 -0
  85. package/dist/operations/account.d.ts +58 -0
  86. package/dist/operations/account.js +112 -0
  87. package/dist/operations/market.d.ts +65 -0
  88. package/dist/operations/market.js +131 -0
  89. package/dist/operations/orders.d.ts +57 -0
  90. package/dist/operations/orders.js +129 -0
  91. package/dist/solana/NordUser.d.ts +78 -0
  92. package/dist/solana/NordUser.js +196 -0
  93. package/dist/solana/client.d.ts +139 -0
  94. package/dist/solana/client.js +360 -0
  95. package/dist/solana/const.d.ts +23 -0
  96. package/dist/solana/const.js +47 -0
  97. package/dist/solana/index.d.ts +5 -0
  98. package/dist/solana/index.js +23 -0
  99. package/dist/solana/types.d.ts +118 -0
  100. package/dist/solana/types.js +16 -0
  101. package/dist/solana/utils.d.ts +64 -0
  102. package/dist/solana/utils.js +131 -0
  103. package/dist/types/api.d.ts +152 -0
  104. package/dist/types/api.js +6 -0
  105. package/dist/types/config.d.ts +34 -0
  106. package/dist/types/config.js +6 -0
  107. package/dist/types.d.ts +144 -87
  108. package/dist/types.js +13 -2
  109. package/dist/utils/errors.d.ts +96 -0
  110. package/dist/utils/errors.js +132 -0
  111. package/dist/utils/http.d.ts +35 -0
  112. package/dist/utils/http.js +105 -0
  113. package/dist/utils.d.ts +14 -5
  114. package/dist/utils.js +26 -7
  115. package/dist/websocket/NordWebSocketClient.d.ts +71 -0
  116. package/dist/websocket/NordWebSocketClient.js +343 -0
  117. package/dist/websocket/client.d.ts +93 -0
  118. package/dist/websocket/client.js +222 -0
  119. package/dist/websocket/events.d.ts +19 -0
  120. package/dist/websocket/events.js +2 -0
  121. package/dist/websocket/index.d.ts +2 -0
  122. package/dist/websocket/index.js +5 -0
  123. package/dist/websocket.d.ts +55 -0
  124. package/dist/websocket.js +211 -0
  125. package/docs/assets/navigation.js +1 -1
  126. package/docs/assets/search.js +1 -1
  127. package/docs/classes/Nord.html +2 -15
  128. package/docs/classes/NordUser.html +4 -4
  129. package/docs/enums/FillMode.html +2 -2
  130. package/docs/enums/KeyType.html +2 -2
  131. package/docs/enums/PeakTpsPeriodUnit.html +2 -2
  132. package/docs/enums/Side.html +2 -2
  133. package/docs/functions/assert.html +1 -1
  134. package/docs/functions/bigIntToProtoU128.html +1 -1
  135. package/docs/functions/checkPubKeyLength.html +1 -1
  136. package/docs/functions/checkedFetch.html +1 -1
  137. package/docs/functions/decodeLengthDelimited.html +1 -1
  138. package/docs/functions/encodeLengthDelimited.html +1 -1
  139. package/docs/functions/fillModeToProtoFillMode.html +1 -1
  140. package/docs/functions/findMarket.html +1 -1
  141. package/docs/functions/findToken.html +1 -1
  142. package/docs/functions/makeWalletSignFn.html +1 -1
  143. package/docs/functions/optExpect.html +1 -1
  144. package/docs/functions/optMap.html +1 -1
  145. package/docs/functions/optUnwrap.html +1 -1
  146. package/docs/functions/panic.html +1 -1
  147. package/docs/functions/signAction.html +1 -1
  148. package/docs/functions/toScaledU128.html +1 -1
  149. package/docs/functions/toScaledU64.html +1 -1
  150. package/docs/interfaces/Account.html +2 -2
  151. package/docs/interfaces/ActionInfo.html +2 -2
  152. package/docs/interfaces/ActionQuery.html +2 -2
  153. package/docs/interfaces/ActionResponse.html +2 -2
  154. package/docs/interfaces/ActionsExtendedInfo.html +2 -2
  155. package/docs/interfaces/ActionsQuery.html +2 -2
  156. package/docs/interfaces/ActionsResponse.html +2 -2
  157. package/docs/interfaces/AggregateMetrics.html +2 -2
  158. package/docs/interfaces/BlockQuery.html +2 -2
  159. package/docs/interfaces/BlockResponse.html +2 -2
  160. package/docs/interfaces/BlockSummary.html +2 -2
  161. package/docs/interfaces/BlockSummaryResponse.html +2 -2
  162. package/docs/interfaces/DeltaEvent.html +2 -2
  163. package/docs/interfaces/ERC20TokenInfo.html +2 -2
  164. package/docs/interfaces/Info.html +2 -2
  165. package/docs/interfaces/Market.html +2 -2
  166. package/docs/interfaces/MarketStats.html +2 -2
  167. package/docs/interfaces/MarketsStatsResponse.html +2 -2
  168. package/docs/interfaces/NordConfig.html +2 -2
  169. package/docs/interfaces/Order.html +2 -2
  170. package/docs/interfaces/OrderInfo.html +2 -2
  171. package/docs/interfaces/PerpMarketStats.html +2 -2
  172. package/docs/interfaces/RollmanActionExtendedInfo.html +2 -2
  173. package/docs/interfaces/RollmanActionInfo.html +2 -2
  174. package/docs/interfaces/RollmanActionResponse.html +2 -2
  175. package/docs/interfaces/RollmanActionsResponse.html +2 -2
  176. package/docs/interfaces/RollmanBlockResponse.html +2 -2
  177. package/docs/interfaces/SubscriberConfig.html +2 -2
  178. package/docs/interfaces/Token.html +2 -2
  179. package/docs/interfaces/Trade.html +2 -2
  180. package/docs/interfaces/Trades.html +2 -2
  181. package/docs/modules.html +0 -7
  182. package/docs/types/BigIntValue.html +1 -1
  183. package/docs/variables/DEBUG_KEYS.html +1 -1
  184. package/docs/variables/DEFAULT_FUNDING_AMOUNTS.html +1 -1
  185. package/docs/variables/DEV_CONTRACT_ADDRESS.html +1 -1
  186. package/docs/variables/DEV_TOKEN_INFOS.html +1 -1
  187. package/docs/variables/DEV_URL.html +1 -1
  188. package/docs/variables/ERC20_ABI.html +1 -1
  189. package/docs/variables/EVM_DEV_URL.html +1 -1
  190. package/docs/variables/FAUCET_PRIVATE_ADDRESS.html +1 -1
  191. package/docs/variables/MAX_BUFFER_LEN.html +1 -1
  192. package/docs/variables/NORD_GETTERS_FACET_ABI.html +1 -1
  193. package/docs/variables/NORD_RAMP_FACET_ABI.html +1 -1
  194. package/docs/variables/SESSION_TTL.html +1 -1
  195. package/docs/variables/WEBSERVER_DEV_URL.html +1 -1
  196. package/docs/variables/ZERO_DECIMAL.html +1 -1
  197. package/package.json +10 -12
  198. package/src/bridge/client.ts +487 -0
  199. package/src/bridge/const.ts +53 -0
  200. package/src/bridge/index.ts +7 -0
  201. package/src/bridge/types.ts +127 -0
  202. package/src/bridge/utils.ts +140 -0
  203. package/src/const.ts +20 -25
  204. package/src/gen/common.ts +27 -10
  205. package/src/gen/nord.ts +1044 -483
  206. package/src/idl/bridge.ts +702 -0
  207. package/src/index.ts +24 -5
  208. package/src/nord/{actions.ts → api/actions.ts} +33 -37
  209. package/src/nord/api/core.ts +130 -0
  210. package/src/nord/api/market.ts +125 -0
  211. package/src/nord/api/metrics.ts +154 -0
  212. package/src/nord/api/queries.ts +236 -0
  213. package/src/nord/client/Nord.ts +652 -0
  214. package/src/nord/client/NordUser.ts +1105 -0
  215. package/src/nord/index.ts +16 -2
  216. package/src/nord/models/Subscriber.ts +57 -0
  217. package/src/nord/utils/NordError.ts +72 -0
  218. package/src/types.ts +170 -99
  219. package/src/utils.ts +40 -19
  220. package/src/websocket/NordWebSocketClient.ts +432 -0
  221. package/src/websocket/events.ts +31 -0
  222. package/src/websocket/index.ts +2 -0
  223. package/tests/utils.spec.ts +24 -24
  224. package/docs/classes/Subscriber.html +0 -6
  225. package/docs/functions/createWebSocketSubscription.html +0 -12
  226. package/docs/interfaces/OrderbookOrder.html +0 -6
  227. package/docs/interfaces/OrderbookResponse.html +0 -10
  228. package/docs/interfaces/TradeInfo.html +0 -20
  229. package/docs/interfaces/TradesQueryParams.html +0 -10
  230. package/docs/interfaces/TradesResponse.html +0 -12
  231. package/src/abis/ERC20_ABI.ts +0 -310
  232. package/src/abis/NORD_GETTERS_FACET_ABI.ts +0 -192
  233. package/src/abis/NORD_RAMP_FACET_ABI.ts +0 -141
  234. package/src/abis/index.ts +0 -3
  235. package/src/nord/Nord.ts +0 -504
  236. package/src/nord/NordImpl.ts +0 -8
  237. package/src/nord/NordUser.ts +0 -469
@@ -1,5 +1,6 @@
1
- import { ethers } from "ethers";
2
- import { FillMode, fillModeToProtoFillMode, KeyType, Side } from "../types";
1
+ import Decimal from 'decimal.js';
2
+ import * as proto from '../../gen/nord';
3
+ import { FillMode, fillModeToProtoFillMode, KeyType, Side } from '../../types';
3
4
  import {
4
5
  assert,
5
6
  bigIntToProtoU128,
@@ -12,9 +13,7 @@ import {
12
13
  SESSION_TTL,
13
14
  toScaledU128,
14
15
  toScaledU64,
15
- } from "../utils";
16
- import * as proto from "../gen/nord";
17
- import Decimal from "decimal.js";
16
+ } from '../../utils';
18
17
 
19
18
  async function sessionSign(
20
19
  signFn: (message: Uint8Array) => Promise<Uint8Array>,
@@ -25,14 +24,11 @@ async function sessionSign(
25
24
  }
26
25
 
27
26
  async function walletSign(
28
- walletSignFn: (message: string | Uint8Array) => Promise<string>,
27
+ walletSignFn: (message: string | Uint8Array) => Promise<Uint8Array>,
29
28
  message: Uint8Array,
30
29
  ): Promise<Uint8Array> {
31
30
  const signature = await walletSignFn(message);
32
- return new Uint8Array([
33
- ...message,
34
- ...ethers.getBytes(signature.slice(0, -2)),
35
- ]);
31
+ return new Uint8Array([...message, ...signature]);
36
32
  }
37
33
 
38
34
  function makeSendHttp(
@@ -40,9 +36,9 @@ function makeSendHttp(
40
36
  ): (encoded: Uint8Array) => Promise<Uint8Array> {
41
37
  return async (body) => {
42
38
  const response = await checkedFetch(`${serverUrl}/action`, {
43
- method: "POST",
39
+ method: 'POST',
44
40
  headers: {
45
- "Content-Type": "application/json",
41
+ 'Content-Type': 'application/json',
46
42
  },
47
43
  body,
48
44
  });
@@ -61,7 +57,7 @@ async function sendAction(
61
57
  const rawResp = await sendFn(body);
62
58
  const resp: proto.Receipt = decodeLengthDelimited(rawResp, proto.Receipt);
63
59
 
64
- if (resp.kind?.$case === "err") {
60
+ if (resp.kind?.$case === 'err') {
65
61
  throw new Error(
66
62
  `Could not ${actionErrorDesc}, reason: ${proto.errorToJSON(resp.kind.value)}`,
67
63
  );
@@ -72,7 +68,7 @@ async function sendAction(
72
68
 
73
69
  async function createSessionImpl(
74
70
  sendFn: (encoded: Uint8Array) => Promise<Uint8Array>,
75
- walletSignFn: (message: string | Uint8Array) => Promise<string>,
71
+ walletSignFn: (message: string | Uint8Array) => Promise<Uint8Array>,
76
72
  currentTimestamp: bigint,
77
73
  nonce: number,
78
74
  params: {
@@ -82,7 +78,7 @@ async function createSessionImpl(
82
78
  expiryTimestamp?: bigint;
83
79
  },
84
80
  ): Promise<bigint> {
85
- checkPubKeyLength(KeyType.Secp256k1, params.userPubkey.length);
81
+ checkPubKeyLength(KeyType.Ed25519, params.userPubkey.length);
86
82
  checkPubKeyLength(KeyType.Ed25519, params.sessionPubkey.length);
87
83
 
88
84
  let expiry = 0n;
@@ -91,7 +87,7 @@ async function createSessionImpl(
91
87
  expiry = params.expiryTimestamp;
92
88
  assert(
93
89
  expiry > currentTimestamp,
94
- "Cannot set expiry timestamp in the past",
90
+ 'Cannot set expiry timestamp in the past',
95
91
  );
96
92
  } else {
97
93
  expiry = currentTimestamp + SESSION_TTL;
@@ -101,7 +97,7 @@ async function createSessionImpl(
101
97
  currentTimestamp,
102
98
  nonce,
103
99
  kind: {
104
- $case: "createSession",
100
+ $case: 'createSession',
105
101
  value: {
106
102
  userPubkey: params.userPubkey,
107
103
  blstPubkey: params.sessionPubkey,
@@ -114,10 +110,10 @@ async function createSessionImpl(
114
110
  sendFn,
115
111
  (m) => walletSign(walletSignFn, m),
116
112
  action,
117
- "create a new session",
113
+ 'create a new session',
118
114
  );
119
115
 
120
- if (resp.kind?.$case === "createSessionResult") {
116
+ if (resp.kind?.$case === 'createSessionResult') {
121
117
  return resp.kind.value.sessionId;
122
118
  } else {
123
119
  throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
@@ -126,7 +122,7 @@ async function createSessionImpl(
126
122
 
127
123
  export async function createSession(
128
124
  serverUrl: string,
129
- walletSignFn: (message: string | Uint8Array) => Promise<string>,
125
+ walletSignFn: (message: string | Uint8Array) => Promise<Uint8Array>,
130
126
  currentTimestamp: bigint,
131
127
  nonce: number,
132
128
  params: {
@@ -147,7 +143,7 @@ export async function createSession(
147
143
 
148
144
  async function revokeSessionImpl(
149
145
  sendFn: (encoded: Uint8Array) => Promise<Uint8Array>,
150
- walletSignFn: (message: string | Uint8Array) => Promise<string>,
146
+ walletSignFn: (message: string | Uint8Array) => Promise<Uint8Array>,
151
147
  currentTimestamp: bigint,
152
148
  nonce: number,
153
149
  params: {
@@ -158,7 +154,7 @@ async function revokeSessionImpl(
158
154
  currentTimestamp,
159
155
  nonce,
160
156
  kind: {
161
- $case: "revokeSession",
157
+ $case: 'revokeSession',
162
158
  value: {
163
159
  sessionId: BigInt(params.sessionId),
164
160
  },
@@ -169,13 +165,13 @@ async function revokeSessionImpl(
169
165
  sendFn,
170
166
  (m) => walletSign(walletSignFn, m),
171
167
  action,
172
- "create a new session",
168
+ 'create a new session',
173
169
  );
174
170
  }
175
171
 
176
172
  export async function revokeSession(
177
173
  serverUrl: string,
178
- walletSignFn: (message: string | Uint8Array) => Promise<string>,
174
+ walletSignFn: (message: string | Uint8Array) => Promise<Uint8Array>,
179
175
  currentTimestamp: bigint,
180
176
  nonce: number,
181
177
  params: {
@@ -206,14 +202,14 @@ async function withdrawImpl(
206
202
  const amount = toScaledU64(params.amount, params.sizeDecimals);
207
203
 
208
204
  if (amount <= 0) {
209
- throw new Error("Withdraw amount must be positive");
205
+ throw new Error('Withdraw amount must be positive');
210
206
  }
211
207
 
212
208
  const action: proto.Action = {
213
209
  currentTimestamp,
214
210
  nonce,
215
211
  kind: {
216
- $case: "withdraw",
212
+ $case: 'withdraw',
217
213
  value: {
218
214
  sessionId: BigInt(params.sessionId),
219
215
  tokenId: params.tokenId,
@@ -222,7 +218,7 @@ async function withdrawImpl(
222
218
  },
223
219
  };
224
220
 
225
- await sendAction(sendFn, (m) => sessionSign(signFn, m), action, "withdraw");
221
+ await sendAction(sendFn, (m) => sessionSign(signFn, m), action, 'withdraw');
226
222
  }
227
223
 
228
224
  export async function withdraw(
@@ -280,7 +276,7 @@ async function placeOrderImpl(
280
276
  currentTimestamp,
281
277
  nonce,
282
278
  kind: {
283
- $case: "placeOrder",
279
+ $case: 'placeOrder',
284
280
  value: {
285
281
  sessionId: BigInt(params.sessionId),
286
282
  senderAccountId: params.senderId,
@@ -301,10 +297,10 @@ async function placeOrderImpl(
301
297
  sendFn,
302
298
  (m) => sessionSign(signFn, m),
303
299
  action,
304
- "place the order",
300
+ 'place the order',
305
301
  );
306
302
 
307
- if (resp.kind?.$case === "placeOrderResult") {
303
+ if (resp.kind?.$case === 'placeOrderResult') {
308
304
  return resp.kind.value.posted?.orderId;
309
305
  } else {
310
306
  throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
@@ -357,7 +353,7 @@ async function cancelOrderImpl(
357
353
  currentTimestamp,
358
354
  nonce: nonce,
359
355
  kind: {
360
- $case: "cancelOrderById",
356
+ $case: 'cancelOrderById',
361
357
  value: {
362
358
  orderId: BigInt(params.orderId),
363
359
  sessionId: BigInt(params.sessionId),
@@ -371,10 +367,10 @@ async function cancelOrderImpl(
371
367
  sendFn,
372
368
  (m) => sessionSign(signFn, m),
373
369
  action,
374
- "cancel the order",
370
+ 'cancel the order',
375
371
  );
376
372
 
377
- if (resp.kind?.$case === "cancelOrderResult") {
373
+ if (resp.kind?.$case === 'cancelOrderResult') {
378
374
  return resp.kind.value.orderId;
379
375
  } else {
380
376
  throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
@@ -420,7 +416,7 @@ async function transferImpl(
420
416
  currentTimestamp,
421
417
  nonce: nonce,
422
418
  kind: {
423
- $case: "transfer",
419
+ $case: 'transfer',
424
420
  value: {
425
421
  sessionId: BigInt(params.sessionId),
426
422
  fromAccountId: params.fromAccountId,
@@ -435,12 +431,12 @@ async function transferImpl(
435
431
  sendFn,
436
432
  (m) => sessionSign(signFn, m),
437
433
  action,
438
- "transfer asset to other account",
434
+ 'transfer asset to other account',
439
435
  );
440
436
 
441
- if (resp.kind?.$case === "transferred") {
437
+ if (resp.kind?.$case === 'transferred') {
442
438
  if (resp.kind.value.accountCreated) {
443
- return resp.kind.value.toAccountId;
439
+ return resp.kind.value.toUserAccount;
444
440
  } else {
445
441
  return undefined;
446
442
  }
@@ -0,0 +1,130 @@
1
+ import { Account, Info, NordConfig, TokenInfo } from '../../types';
2
+ import { checkedFetch } from '../../utils';
3
+ import { NordError } from '../utils/NordError';
4
+ import { NordWebSocketClient } from '../../websocket/index';
5
+
6
+ /**
7
+ * Get the current timestamp from the Nord server
8
+ *
9
+ * @param webServerUrl - Base URL for the Nord web server
10
+ * @returns Current timestamp as a bigint
11
+ * @throws {NordError} If the request fails
12
+ */
13
+ export async function getTimestamp(webServerUrl: string): Promise<bigint> {
14
+ try {
15
+ const response = await checkedFetch(`${webServerUrl}/timestamp`);
16
+ return BigInt(await response.json());
17
+ } catch (error) {
18
+ throw new NordError('Failed to get timestamp', { cause: error });
19
+ }
20
+ }
21
+
22
+ /**
23
+ * Get the next action nonce from the Nord server
24
+ *
25
+ * @param webServerUrl - Base URL for the Nord web server
26
+ * @returns Next action nonce
27
+ * @throws {NordError} If the request fails
28
+ */
29
+ export async function getActionNonce(webServerUrl: string): Promise<number> {
30
+ try {
31
+ const response = await checkedFetch(`${webServerUrl}/action_nonce`);
32
+ const data = await response.json();
33
+ return data.nonce;
34
+ } catch (error) {
35
+ throw new NordError('Failed to get action nonce', { cause: error });
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Get information about the Nord server
41
+ *
42
+ * @param webServerUrl - Base URL for the Nord web server
43
+ * @returns Information about markets and tokens
44
+ * @throws {NordError} If the request fails
45
+ */
46
+ export async function getInfo(webServerUrl: string): Promise<Info> {
47
+ try {
48
+ const response = await checkedFetch(`${webServerUrl}/info`);
49
+ return await response.json();
50
+ } catch (error) {
51
+ throw new NordError('Failed to get info', { cause: error });
52
+ }
53
+ }
54
+
55
+ /**
56
+ * Get account information
57
+ *
58
+ * @param webServerUrl - Base URL for the Nord web server
59
+ * @param accountId - Account ID to get information for
60
+ * @returns Account information
61
+ * @throws {NordError} If the request fails
62
+ */
63
+ export async function getAccount(
64
+ webServerUrl: string,
65
+ accountId: number,
66
+ ): Promise<Account> {
67
+ try {
68
+ const response = await checkedFetch(
69
+ `${webServerUrl}/account?account_id=${accountId}`,
70
+ );
71
+ return await response.json();
72
+ } catch (error) {
73
+ throw new NordError(`Failed to get account ${accountId}`, { cause: error });
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Initialize a WebSocket client for Nord
79
+ *
80
+ * Connects to one of the specific Nord WebSocket endpoints:
81
+ * - /ws/trades - For trade updates (default)
82
+ * - /ws/deltas - For orderbook delta updates
83
+ * - /ws/user - For user-specific updates
84
+ *
85
+ * @param webServerUrl - Base URL for the Nord web server
86
+ * @param endpoint - Specific WebSocket endpoint to connect to (trades, deltas, or user)
87
+ * @param initialSubscriptions - Optional array of initial subscriptions (e.g., ["trades@BTCUSDC"])
88
+ * @returns WebSocket client
89
+ */
90
+ export function initWebSocketClient(
91
+ webServerUrl: string,
92
+ endpoint?: 'trades' | 'deltas' | 'user',
93
+ initialSubscriptions?: string[],
94
+ ): NordWebSocketClient {
95
+ try {
96
+ // Convert HTTP URL to WebSocket URL with specific endpoint
97
+ // If no specific endpoint is provided, we'll connect to trades by default
98
+ const specificEndpoint = endpoint || 'trades';
99
+ const wsUrl =
100
+ webServerUrl.replace(/^http/, 'ws') + `/ws/${specificEndpoint}`;
101
+ console.log(`Initializing WebSocket client with URL: ${wsUrl}`);
102
+
103
+ // Create and connect the WebSocket client
104
+ const ws = new NordWebSocketClient(wsUrl);
105
+
106
+ // Add error handler
107
+ ws.on('error', (error) => {
108
+ console.error('Nord WebSocket error:', error);
109
+ });
110
+
111
+ // Add connected handler for debugging
112
+ ws.on('connected', () => {
113
+ console.log('Nord WebSocket connected successfully');
114
+
115
+ // Subscribe to initial subscriptions if provided
116
+ if (initialSubscriptions && initialSubscriptions.length > 0) {
117
+ ws.subscribe(initialSubscriptions);
118
+ }
119
+ });
120
+
121
+ // Connect the WebSocket
122
+ ws.connect();
123
+ return ws;
124
+ } catch (error) {
125
+ console.error('Failed to initialize WebSocket client:', error);
126
+ throw new NordError('Failed to initialize WebSocket client', {
127
+ cause: error,
128
+ });
129
+ }
130
+ }
@@ -0,0 +1,125 @@
1
+ import {
2
+ MarketsStatsResponse,
3
+ OrderbookQuery,
4
+ OrderbookResponse,
5
+ TradesQuery,
6
+ TradesResponse,
7
+ UserAccountIdsQuery,
8
+ UserAccountIdsResponse,
9
+ } from '../../types';
10
+ import { checkedFetch } from '../../utils';
11
+ import { NordError } from '../utils/NordError';
12
+
13
+ /**
14
+ * Get market statistics
15
+ *
16
+ * @param webServerUrl - Base URL for the Nord web server
17
+ * @returns Market statistics response
18
+ * @throws {NordError} If the request fails
19
+ */
20
+ export async function marketsStats(
21
+ webServerUrl: string,
22
+ ): Promise<MarketsStatsResponse> {
23
+ try {
24
+ const response = await checkedFetch(`${webServerUrl}/stats`);
25
+ return await response.json();
26
+ } catch (error) {
27
+ throw new NordError('Failed to fetch markets stats', { cause: error });
28
+ }
29
+ }
30
+
31
+ /**
32
+ * Get trades for a market
33
+ *
34
+ * @param webServerUrl - Base URL for the Nord web server
35
+ * @param query - Trades query parameters
36
+ * @returns Trades response
37
+ * @throws {NordError} If the request fails
38
+ */
39
+ export async function getTrades(
40
+ webServerUrl: string,
41
+ query: TradesQuery,
42
+ ): Promise<TradesResponse> {
43
+ try {
44
+ const params = new URLSearchParams();
45
+ params.append('accountId', query.accountId.toString());
46
+
47
+ if (query.since) {
48
+ params.append('since', query.since);
49
+ }
50
+
51
+ if (query.until) {
52
+ params.append('until', query.until);
53
+ }
54
+
55
+ if (query.pageId) {
56
+ params.append('pageId', query.pageId);
57
+ }
58
+
59
+ const response = await checkedFetch(
60
+ `${webServerUrl}/trades?${params.toString()}`,
61
+ );
62
+ return await response.json();
63
+ } catch (error) {
64
+ throw new NordError('Failed to get trades', { cause: error });
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Get user account IDs
70
+ *
71
+ * @param webServerUrl - Base URL for the Nord web server
72
+ * @param query - User account IDs query parameters
73
+ * @returns User account IDs response
74
+ * @throws {NordError} If the request fails
75
+ */
76
+ export async function getUserAccountIds(
77
+ webServerUrl: string,
78
+ query: UserAccountIdsQuery,
79
+ ): Promise<UserAccountIdsResponse> {
80
+ try {
81
+ const params = new URLSearchParams();
82
+ params.append('pubkey', query.pubkey);
83
+
84
+ const response = await checkedFetch(
85
+ `${webServerUrl}/user?${params.toString()}`,
86
+ );
87
+ return await response.json();
88
+ } catch (error) {
89
+ throw new NordError('Failed to get user account IDs', { cause: error });
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Get orderbook for a market
95
+ *
96
+ * @param webServerUrl - Base URL for the Nord web server
97
+ * @param query - Orderbook query parameters
98
+ * @returns Orderbook response
99
+ * @throws {NordError} If the request fails
100
+ */
101
+ export async function getOrderbook(
102
+ webServerUrl: string,
103
+ query: OrderbookQuery,
104
+ ): Promise<OrderbookResponse> {
105
+ try {
106
+ const params = new URLSearchParams();
107
+
108
+ if (query.symbol) {
109
+ params.append('symbol', query.symbol);
110
+ } else if (query.market_id !== undefined) {
111
+ params.append('market_id', query.market_id.toString());
112
+ } else {
113
+ throw new NordError(
114
+ 'Either symbol or market_id must be provided for orderbook query',
115
+ );
116
+ }
117
+
118
+ const response = await checkedFetch(
119
+ `${webServerUrl}/orderbook?${params.toString()}`,
120
+ );
121
+ return await response.json();
122
+ } catch (error) {
123
+ throw new NordError('Failed to get orderbook', { cause: error });
124
+ }
125
+ }
@@ -0,0 +1,154 @@
1
+ import { AggregateMetrics, PeakTpsPeriodUnit } from '../../types';
2
+ import { checkedFetch } from '../../utils';
3
+ import { NordError } from '../utils/NordError';
4
+
5
+ /**
6
+ * Time periods for metrics queries
7
+ */
8
+ export enum MetricPeriod {
9
+ ONE_MINUTE = '1m',
10
+ FIVE_MINUTES = '5m',
11
+ FIFTEEN_MINUTES = '15m',
12
+ ONE_HOUR = '1h',
13
+ FOUR_HOURS = '4h',
14
+ ONE_DAY = '24h',
15
+ ONE_WEEK = '7d',
16
+ }
17
+
18
+ /**
19
+ * Fetch aggregate metrics from the Nord API
20
+ *
21
+ * @param webServerUrl - Base URL for the Nord web server
22
+ * @param txPeakTpsPeriod - Period for peak TPS calculation
23
+ * @param txPeakTpsPeriodUnit - Unit for peak TPS period
24
+ * @returns Aggregate metrics
25
+ * @throws {NordError} If the request fails
26
+ */
27
+ export async function aggregateMetrics(
28
+ webServerUrl: string,
29
+ txPeakTpsPeriod = 1,
30
+ txPeakTpsPeriodUnit: PeakTpsPeriodUnit = PeakTpsPeriodUnit.Day,
31
+ ): Promise<AggregateMetrics> {
32
+ try {
33
+ const response = await checkedFetch(
34
+ `${webServerUrl}/metrics?tx_peak_tps_period=${txPeakTpsPeriod}&tx_peak_tps_period_unit=${txPeakTpsPeriodUnit}`,
35
+ );
36
+ return await response.json();
37
+ } catch (error) {
38
+ throw new NordError('Failed to fetch aggregate metrics', { cause: error });
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Get current transactions per second
44
+ *
45
+ * @param webServerUrl - Base URL for the Nord web server
46
+ * @param period - Time period for the query
47
+ * @returns Current TPS value
48
+ * @throws {NordError} If the request fails
49
+ */
50
+ export async function getCurrentTps(
51
+ webServerUrl: string,
52
+ period: string = '1m',
53
+ ): Promise<number> {
54
+ try {
55
+ return await queryPrometheus(
56
+ webServerUrl,
57
+ `sum(rate(nord_tx_count[${period}]))`,
58
+ );
59
+ } catch (error) {
60
+ throw new NordError(`Failed to get current TPS for period ${period}`, {
61
+ cause: error,
62
+ });
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Get peak transactions per second
68
+ *
69
+ * @param webServerUrl - Base URL for the Nord web server
70
+ * @param period - Time period for the query
71
+ * @returns Peak TPS value
72
+ * @throws {NordError} If the request fails
73
+ */
74
+ export async function getPeakTps(
75
+ webServerUrl: string,
76
+ period: string = '24h',
77
+ ): Promise<number> {
78
+ try {
79
+ return await queryPrometheus(
80
+ webServerUrl,
81
+ `max_over_time(sum(rate(nord_tx_count[1m]))[${period}:])`,
82
+ );
83
+ } catch (error) {
84
+ throw new NordError(`Failed to get peak TPS for period ${period}`, {
85
+ cause: error,
86
+ });
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Get median transaction latency
92
+ *
93
+ * @param webServerUrl - Base URL for the Nord web server
94
+ * @param period - Time period for the query
95
+ * @returns Median latency in milliseconds
96
+ * @throws {NordError} If the request fails
97
+ */
98
+ export async function getMedianLatency(
99
+ webServerUrl: string,
100
+ period: string = '1m',
101
+ ): Promise<number> {
102
+ try {
103
+ return await queryPrometheus(
104
+ webServerUrl,
105
+ `quantile_over_time(0.5, nord_tx_latency_ms[${period}])`,
106
+ );
107
+ } catch (error) {
108
+ throw new NordError(`Failed to get median latency for period ${period}`, {
109
+ cause: error,
110
+ });
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Get total transaction count
116
+ *
117
+ * @param webServerUrl - Base URL for the Nord web server
118
+ * @returns Total transaction count
119
+ * @throws {NordError} If the request fails
120
+ */
121
+ export async function getTotalTransactions(
122
+ webServerUrl: string,
123
+ ): Promise<number> {
124
+ try {
125
+ return await queryPrometheus(webServerUrl, 'sum(nord_tx_count)');
126
+ } catch (error) {
127
+ throw new NordError('Failed to get total transactions', { cause: error });
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Query Prometheus metrics
133
+ *
134
+ * @param webServerUrl - Base URL for the Nord web server
135
+ * @param params - Prometheus query parameters
136
+ * @returns Query result as a number
137
+ * @throws {NordError} If the request fails
138
+ */
139
+ export async function queryPrometheus(
140
+ webServerUrl: string,
141
+ params: string,
142
+ ): Promise<number> {
143
+ try {
144
+ const response = await checkedFetch(
145
+ `${webServerUrl}/prometheus?query=${encodeURIComponent(params)}`,
146
+ );
147
+ const data = await response.json();
148
+ return data.data.result[0]?.value[1] || 0;
149
+ } catch (error) {
150
+ throw new NordError(`Failed to query Prometheus: ${params}`, {
151
+ cause: error,
152
+ });
153
+ }
154
+ }