@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
package/src/nord/index.ts CHANGED
@@ -1,2 +1,16 @@
1
- export { NordUser } from "./NordUser";
2
- export { Nord, createWebSocketSubscription, Subscriber } from "./Nord";
1
+ // Export main client classes
2
+ export { Nord } from './client/Nord';
3
+ export { NordUser } from './client/NordUser';
4
+
5
+ // Export utility classes
6
+ export { NordError } from './utils/NordError';
7
+
8
+ // Export API modules
9
+ export * from './api/core';
10
+ export * from './api/metrics';
11
+ export * from './api/queries';
12
+ export * from './api/market';
13
+ export * from './api/actions';
14
+
15
+ // Export models
16
+ export * from './models/Subscriber';
@@ -0,0 +1,57 @@
1
+ import WebSocket from 'ws';
2
+ import { EventEmitter } from 'events';
3
+ import {
4
+ DeltaEvent,
5
+ Trades,
6
+ Account,
7
+ SubscriberConfig,
8
+ OrderbookResponse,
9
+ Trade,
10
+ } from '../../types';
11
+ import { MAX_BUFFER_LEN } from '../../utils';
12
+
13
+ /**
14
+ * Subscriber class for handling WebSocket subscriptions
15
+ */
16
+ export class Subscriber {
17
+ streamURL: string;
18
+ buffer: (DeltaEvent | Trades | Account)[];
19
+ maxBufferLen: number;
20
+
21
+ /**
22
+ * Create a new Subscriber instance
23
+ * @param config Subscriber configuration
24
+ */
25
+ constructor(config: SubscriberConfig) {
26
+ this.streamURL = config.streamURL;
27
+ this.buffer = [];
28
+ this.maxBufferLen = config.maxBufferLen ?? MAX_BUFFER_LEN;
29
+ }
30
+
31
+ /**
32
+ * Subscribe to WebSocket events
33
+ */
34
+ subscribe(): void {
35
+ const ws = new WebSocket(this.streamURL);
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Interface for orderbook subscription
41
+ */
42
+ export interface OrderbookSubscription extends EventEmitter {
43
+ on(event: 'message', listener: (data: OrderbookResponse) => void): this;
44
+ on(event: 'error', listener: (error: Error) => void): this;
45
+ close(): void;
46
+ removeAllListeners(event?: string): this;
47
+ }
48
+
49
+ /**
50
+ * Interface for trade subscription
51
+ */
52
+ export interface TradeSubscription extends EventEmitter {
53
+ on(event: 'message', listener: (data: Trade[]) => void): this;
54
+ on(event: 'error', listener: (error: Error) => void): this;
55
+ close(): void;
56
+ removeAllListeners(event?: string): this;
57
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Options for creating a NordError
3
+ */
4
+ export interface NordErrorOptions {
5
+ /** The original error that caused this error */
6
+ cause?: unknown;
7
+
8
+ /** HTTP status code (if applicable) */
9
+ statusCode?: number;
10
+
11
+ /** Additional error details */
12
+ details?: Record<string, unknown>;
13
+ }
14
+
15
+ /**
16
+ * Custom error class for Nord-related errors
17
+ */
18
+ export class NordError extends Error {
19
+ /** The original error that caused this error */
20
+ public readonly cause?: unknown;
21
+
22
+ /** HTTP status code (if applicable) */
23
+ public readonly statusCode?: number;
24
+
25
+ /** Additional error details */
26
+ public readonly details?: Record<string, unknown>;
27
+
28
+ /**
29
+ * Create a new NordError
30
+ *
31
+ * @param message - Error message
32
+ * @param options - Error options
33
+ */
34
+ constructor(message: string, options: NordErrorOptions = {}) {
35
+ super(message);
36
+
37
+ this.name = 'NordError';
38
+ this.cause = options.cause;
39
+ this.statusCode = options.statusCode;
40
+ this.details = options.details;
41
+
42
+ // Capture stack trace
43
+ if (Error.captureStackTrace) {
44
+ Error.captureStackTrace(this, NordError);
45
+ }
46
+
47
+ // Handle nested errors
48
+ if (this.cause instanceof Error) {
49
+ this.stack =
50
+ this.stack + '\nCaused by: ' + (this.cause.stack || this.cause.message);
51
+ }
52
+ }
53
+
54
+ /**
55
+ * Convert the error to a string representation
56
+ *
57
+ * @returns String representation of the error
58
+ */
59
+ toString(): string {
60
+ let result = `${this.name}: ${this.message}`;
61
+
62
+ if (this.statusCode) {
63
+ result += ` (Status: ${this.statusCode})`;
64
+ }
65
+
66
+ if (this.details && Object.keys(this.details).length > 0) {
67
+ result += `\nDetails: ${JSON.stringify(this.details, null, 2)}`;
68
+ }
69
+
70
+ return result;
71
+ }
72
+ }
package/src/types.ts CHANGED
@@ -1,4 +1,4 @@
1
- import * as proto from "./gen/nord";
1
+ import * as proto from './gen/nord';
2
2
 
3
3
  /**
4
4
  * The peak TPS rate is queried over the specified period.
@@ -10,21 +10,32 @@ import * as proto from "./gen/nord";
10
10
  * AggregateMetrics.txPeakTpsPeriodUnit = "w" => Peak TPS over last week.
11
11
  */
12
12
  export enum PeakTpsPeriodUnit {
13
- Hour = "h",
14
- Day = "d",
15
- Week = "w",
16
- Month = "m",
17
- Year = "y",
13
+ Hour = 'h',
14
+ Day = 'd',
15
+ Week = 'w',
16
+ Month = 'm',
17
+ Year = 'y',
18
18
  }
19
19
 
20
+ /**
21
+ * Configuration options for the Nord client
22
+ */
20
23
  export interface NordConfig {
21
- evmUrl: string;
24
+ /** Base URL for the Nord web server */
22
25
  webServerUrl: string;
23
- contractAddress: string;
24
- tokenInfos: ERC20TokenInfo[];
25
- }
26
-
27
- export interface ERC20TokenInfo {
26
+ /** Solana program ID */
27
+ solanaProgramId: string;
28
+ /** Solana cluster URL */
29
+ solanaUrl: string;
30
+ /** Whether to initialize WebSockets on creation, defaults to true */
31
+ initWebSockets?: boolean;
32
+ /** Initial subscriptions for the trades WebSocket (e.g., ["trades@BTCUSDC"]) */
33
+ tradesSubscriptions?: string[];
34
+ /** Initial subscriptions for the deltas WebSocket (e.g., ["deltas@BTCUSDC"]) */
35
+ deltasSubscriptions?: string[];
36
+ }
37
+
38
+ export interface TokenInfo {
28
39
  address: string;
29
40
  precision: number;
30
41
  tokenId: number;
@@ -63,18 +74,20 @@ export interface SubscriberConfig {
63
74
  }
64
75
 
65
76
  export interface Market {
77
+ marketId: number;
66
78
  symbol: string;
67
- baseTokenId: number;
68
- quoteTokenId: number;
69
79
  priceDecimals: number;
70
80
  sizeDecimals: number;
81
+ baseTokenId: number;
82
+ quoteTokenId: number;
83
+ frozen: boolean;
71
84
  }
72
85
 
73
86
  export interface Token {
87
+ tokenId: number;
74
88
  symbol: string;
75
- ethAddr: string;
76
89
  decimals: number;
77
- tokenId: number;
90
+ mintAddr: string;
78
91
  }
79
92
 
80
93
  export interface Info {
@@ -86,8 +99,8 @@ export interface DeltaEvent {
86
99
  last_update_id: number;
87
100
  update_id: number;
88
101
  market_symbol: string;
89
- asks: [number, number];
90
- bids: [number, number];
102
+ asks: OrderbookEntry[];
103
+ bids: OrderbookEntry[];
91
104
  }
92
105
 
93
106
  export interface Trade {
@@ -107,7 +120,7 @@ export interface Trades {
107
120
  export interface OrderInfo {
108
121
  id: number;
109
122
  reduce_only: boolean;
110
- imit_price: number;
123
+ limit_price: number;
111
124
  size: number;
112
125
  account_id: number;
113
126
  }
@@ -120,7 +133,7 @@ export interface Account {
120
133
  last_update_id: number;
121
134
  update_id: number;
122
135
  account_id: number;
123
- fills: HashMap<FillMode>;
136
+ fills: HashMap<number>;
124
137
  places: HashMap<OrderInfo>;
125
138
  cancels: HashMap<OrderInfo>;
126
139
  balances: HashMap<number>;
@@ -249,84 +262,6 @@ export interface AggregateMetrics {
249
262
  request_latency_average: number;
250
263
  }
251
264
 
252
- /**
253
- * Parameters for querying trades
254
- * @field {number} accountId - ID of target account
255
- * @field {string} [since] - Start with this timestamp (RFC3339); defaults to UNIX epoch start
256
- * @field {string} [until] - End with this timestamp (RFC3339); defaults to current date-time
257
- * @field {string} [pageId] - Fetch results starting with this page
258
- */
259
- export interface TradesQueryParams {
260
- accountId: number;
261
- since?: string;
262
- until?: string;
263
- pageId?: string;
264
- }
265
-
266
- /**
267
- * Trade information
268
- * @field {string} id - Trade ID
269
- * @field {string} timestamp - Trade timestamp (RFC3339)
270
- * @field {string} symbol - Market symbol
271
- * @field {string} side - Trade side (buy/sell)
272
- * @field {number} price - Trade price
273
- * @field {number} size - Trade size
274
- * @field {number} fee - Trade fee
275
- * @field {string} feeCurrency - Fee currency
276
- * @field {number} orderId - Order ID
277
- */
278
- export interface TradeInfo {
279
- id: string;
280
- timestamp: string;
281
- symbol: string;
282
- side: string;
283
- price: number;
284
- size: number;
285
- fee: number;
286
- feeCurrency: string;
287
- orderId: number;
288
- }
289
-
290
- /**
291
- * Response for trades query
292
- * @field {number} accountId - Account ID
293
- * @field {string} since - Start timestamp (RFC3339)
294
- * @field {string} until - End timestamp (RFC3339)
295
- * @field {string} [nextPageId] - ID for the next page of results
296
- * @field {TradeInfo[]} trades - Array of trades
297
- */
298
- export interface TradesResponse {
299
- accountId: number;
300
- since: string;
301
- until: string;
302
- nextPageId?: string;
303
- trades: TradeInfo[];
304
- }
305
-
306
- /**
307
- * Order in the orderbook
308
- * @field {number} price - Order price
309
- * @field {number} size - Order size
310
- */
311
- export interface OrderbookOrder {
312
- price: number;
313
- size: number;
314
- }
315
-
316
- /**
317
- * Response for orderbook query
318
- * @field {string} symbol - Market symbol
319
- * @field {number} timestamp - Orderbook timestamp
320
- * @field {OrderbookOrder[]} bids - Array of bid orders
321
- * @field {OrderbookOrder[]} asks - Array of ask orders
322
- */
323
- export interface OrderbookResponse {
324
- symbol: string;
325
- timestamp: number;
326
- bids: OrderbookOrder[];
327
- asks: OrderbookOrder[];
328
- }
329
-
330
265
  // The JSON types returned by rollman, that need to be translated to TS format.
331
266
  export interface RollmanBlockResponse {
332
267
  block_number: number;
@@ -389,5 +324,141 @@ export function fillModeToProtoFillMode(x: FillMode): proto.FillMode {
389
324
  return proto.FillMode.IMMEDIATE_OR_CANCEL;
390
325
  }
391
326
  if (x === FillMode.FillOrKill) return proto.FillMode.FILL_OR_KILL;
392
- throw new Error("Invalid fill mode");
327
+ throw new Error('Invalid fill mode');
328
+ }
329
+
330
+ /**
331
+ * Response for trades query with pagination support
332
+ */
333
+ export interface TradesResponse {
334
+ trades: Trade[];
335
+ accountId: number;
336
+ since?: string; // RFC3339 timestamp
337
+ until?: string; // RFC3339 timestamp
338
+ nextPageId?: string;
339
+ }
340
+
341
+ /**
342
+ * Query parameters for trades endpoint
343
+ */
344
+ export interface TradesQuery {
345
+ accountId: number;
346
+ since?: string; // RFC3339 timestamp
347
+ until?: string; // RFC3339 timestamp
348
+ pageId?: string;
349
+ }
350
+
351
+ /**
352
+ * Response for user account IDs query
353
+ */
354
+ export interface UserAccountIdsResponse {
355
+ accountIds: number[];
356
+ }
357
+
358
+ /**
359
+ * Query parameters for user account IDs
360
+ */
361
+ export interface UserAccountIdsQuery {
362
+ pubkey: string; // secp256k1 public key in hex format
363
+ }
364
+
365
+ /**
366
+ * Orderbook entry representing price and size
367
+ */
368
+ export interface OrderbookEntry {
369
+ price: number;
370
+ size: number;
371
+ }
372
+
373
+ /**
374
+ * Response for orderbook query
375
+ */
376
+ export interface OrderbookResponse {
377
+ symbol: string;
378
+ asks: OrderbookEntry[];
379
+ bids: OrderbookEntry[];
380
+ timestamp: number;
381
+ }
382
+
383
+ /**
384
+ * Query parameters for orderbook
385
+ *
386
+ * Note: While you can provide either symbol or market_id, the API endpoint only accepts market_id.
387
+ * If you provide a symbol, it will be converted to a market_id internally.
388
+ */
389
+ export interface OrderbookQuery {
390
+ symbol?: string;
391
+ market_id?: number;
392
+ }
393
+
394
+ /**
395
+ * Response for timestamp query
396
+ */
397
+ export interface TimestampResponse {
398
+ timestamp: number; // engine's current logical timestamp
399
+ }
400
+
401
+ /**
402
+ * Response for action nonce query
403
+ */
404
+ export interface ActionNonceResponse {
405
+ nonce: number; // next expected action nonce
406
+ }
407
+
408
+ /**
409
+ * WebSocket message types
410
+ */
411
+ export enum WebSocketMessageType {
412
+ Subscribe = 'subscribe',
413
+ Unsubscribe = 'unsubscribe',
414
+ TradeUpdate = 'trade',
415
+ DeltaUpdate = 'delta',
416
+ UserUpdate = 'user',
417
+ }
418
+
419
+ /**
420
+ * WebSocket subscription request
421
+ */
422
+ export interface WebSocketSubscription {
423
+ type: WebSocketMessageType;
424
+ streams: string[]; // Array of streams to subscribe/unsubscribe (e.g. ["trades@BTCUSDC", "deltas@BTCUSDC"])
393
425
  }
426
+
427
+ /**
428
+ * WebSocket trade update message
429
+ */
430
+ export interface WebSocketTradeUpdate {
431
+ type: WebSocketMessageType.TradeUpdate;
432
+ symbol: string;
433
+ trades: Trade[];
434
+ timestamp: number;
435
+ }
436
+
437
+ /**
438
+ * WebSocket delta update message
439
+ */
440
+ export interface WebSocketDeltaUpdate {
441
+ type: WebSocketMessageType.DeltaUpdate;
442
+ last_update_id: number;
443
+ update_id: number;
444
+ market_symbol: string;
445
+ asks: OrderbookEntry[];
446
+ bids: OrderbookEntry[];
447
+ timestamp: number;
448
+ }
449
+
450
+ /**
451
+ * WebSocket user update message
452
+ */
453
+ export interface WebSocketUserUpdate {
454
+ type: WebSocketMessageType.UserUpdate;
455
+ userId: number;
456
+ account: Account;
457
+ timestamp: number;
458
+ }
459
+
460
+ export type WebSocketMessage =
461
+ | WebSocketSubscription
462
+ | WebSocketTradeUpdate
463
+ | WebSocketDeltaUpdate
464
+ | WebSocketUserUpdate;
package/src/utils.ts CHANGED
@@ -1,16 +1,17 @@
1
- import { Decimal } from "decimal.js";
2
- import { ed25519 } from "@noble/curves/ed25519";
3
- import { bls12_381 as bls } from "@noble/curves/bls12-381";
4
- import { secp256k1 as secp } from "@noble/curves/secp256k1";
5
- import { sha256 } from "@noble/hashes/sha256";
6
- import { KeyType, type Market, type Token } from "./types";
7
- import * as proto from "./gen/nord";
8
- import { BinaryReader, BinaryWriter } from "@bufbuild/protobuf/wire";
9
- import { ethers } from "ethers";
10
- import fetch from "node-fetch";
11
- import { RequestInfo, RequestInit, Response } from "node-fetch";
12
-
13
- export const SESSION_TTL: bigint = 10n * 60n * 1000n * 10000n;
1
+ import { Decimal } from 'decimal.js';
2
+ import { ed25519 } from '@noble/curves/ed25519';
3
+ import { bls12_381 as bls } from '@noble/curves/bls12-381';
4
+ import { secp256k1 as secp } from '@noble/curves/secp256k1';
5
+ import { sha256 } from '@noble/hashes/sha256';
6
+ import { KeyType, type Market, type Token } from './types';
7
+ import * as proto from './gen/nord';
8
+ import { BinaryReader, BinaryWriter } from '@bufbuild/protobuf/wire';
9
+ import { ethers } from 'ethers';
10
+ import fetch from 'node-fetch';
11
+ import { RequestInfo, RequestInit, Response } from 'node-fetch';
12
+ import { BN } from '@coral-xyz/anchor';
13
+
14
+ export const SESSION_TTL: bigint = 60n * 60n * 24n * 30n;
14
15
  export const ZERO_DECIMAL = new Decimal(0);
15
16
  export const MAX_BUFFER_LEN = 10_000;
16
17
 
@@ -24,7 +25,7 @@ export function panic(message: string): never {
24
25
  }
25
26
 
26
27
  export function assert(predicate: boolean, message?: string): void {
27
- if (!predicate) panic(message ?? "Assertion violated");
28
+ if (!predicate) panic(message ?? 'Assertion violated');
28
29
  }
29
30
  /**
30
31
  * Extracts value out of optional if it's defined, or throws error if it's not
@@ -42,7 +43,7 @@ export function optExpect<T>(value: T | undefined, message: string): T {
42
43
  * @returns
43
44
  */
44
45
  export function optUnwrap<T>(value: T | undefined): T {
45
- return optExpect(value, "Optional contains no value");
46
+ return optExpect(value, 'Optional contains no value');
46
47
  }
47
48
  /**
48
49
  * Applies function to value if it's defined, or passes `undefined` through
@@ -92,7 +93,7 @@ export function signAction(
92
93
  } else if (keyType === KeyType.Secp256k1) {
93
94
  sig = secp.sign(sha256(action), sk).toCompactRawBytes();
94
95
  } else {
95
- throw new Error("Invalid key type");
96
+ throw new Error('Invalid key type');
96
97
  }
97
98
  return new Uint8Array([...action, ...sig]);
98
99
  }
@@ -272,16 +273,16 @@ export function decodeLengthDelimited<T, M extends proto.MessageFns<T>>(
272
273
  export function checkPubKeyLength(keyType: KeyType, len: number): void {
273
274
  if (keyType === KeyType.Bls12_381) {
274
275
  throw new Error(
275
- "Cannot create a user using Bls12_381, use Ed25119 or Secp256k1 instead.",
276
+ 'Cannot create a user using Bls12_381, use Ed25119 or Secp256k1 instead.',
276
277
  );
277
278
  }
278
279
 
279
280
  if (len !== 32 && keyType === KeyType.Ed25519) {
280
- throw new Error("Ed25519 pubkeys must be 32 length.");
281
+ throw new Error('Ed25519 pubkeys must be 32 length.');
281
282
  }
282
283
 
283
284
  if (len !== 33 && keyType === KeyType.Secp256k1) {
284
- throw new Error("Secp256k1 pubkeys must be 33 length.");
285
+ throw new Error('Secp256k1 pubkeys must be 33 length.');
285
286
  }
286
287
  }
287
288
 
@@ -298,3 +299,23 @@ export function findToken(tokens: Token[], tokenId: number): Token {
298
299
  }
299
300
  return tokens[tokenId];
300
301
  }
302
+
303
+ /**
304
+ * Convert a number to a BN with the specified number of decimals
305
+ *
306
+ * @param amount Amount as a number
307
+ * @param decimals Number of decimal places
308
+ * @returns Amount as a BN
309
+ */
310
+ export function toBN(amount: number, decimals: number): BN {
311
+ const amountString = amount.toFixed(decimals);
312
+ const [whole, fraction] = amountString.split('.');
313
+
314
+ // Convert to smallest units (no decimals)
315
+ const wholeBN = new BN(whole).mul(new BN(10).pow(new BN(decimals)));
316
+ const fractionBN = fraction
317
+ ? new BN(fraction.padEnd(decimals, '0').slice(0, decimals))
318
+ : new BN(0);
319
+
320
+ return wholeBN.add(fractionBN);
321
+ }