@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/dist/nord/Nord.js CHANGED
@@ -32,345 +32,357 @@ var __importStar = (this && this.__importStar) || (function () {
32
32
  return result;
33
33
  };
34
34
  })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
35
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.Subscriber = exports.Nord = void 0;
40
- exports.depositOnlyTx = depositOnlyTx;
41
- exports.depositOnlyTxRaw = depositOnlyTxRaw;
42
- exports.createWebSocketSubscription = createWebSocketSubscription;
43
- const ethers_1 = require("ethers");
44
- const ws_1 = __importDefault(require("ws"));
36
+ exports.Nord = void 0;
37
+ const events_1 = require("events");
45
38
  const types_1 = require("../types");
46
- const utils_1 = require("../utils");
47
- const const_1 = require("../const");
48
- const abis_1 = require("../abis");
49
- const proto = __importStar(require("../gen/nord"));
50
- async function depositOnlyTx(privateAddress, publicKey, amount, precision, contractAddress) {
51
- const provider = new ethers_1.ethers.JsonRpcProvider(process.env.SECRET_FAUCET_RPC);
52
- const wallet = new ethers_1.ethers.Wallet(privateAddress, provider);
53
- const nordContract = new ethers_1.ethers.Contract(contractAddress, abis_1.NORD_RAMP_FACET_ABI, wallet);
54
- const depositTx = await nordContract.depositUnchecked(publicKey, BigInt(0), ethers_1.ethers.parseUnits(amount.toString(), precision), {
55
- gasLimit: 1000000,
56
- maxFeePerGas: ethers_1.ethers.parseUnits("100", "gwei"),
57
- maxPriorityFeePerGas: ethers_1.ethers.parseUnits("0.01", "gwei"),
58
- });
59
- return depositTx.hash;
60
- }
61
- async function depositOnlyTxRaw(privateAddress, publicKey, amount, precision, contractAddress) {
62
- const provider = new ethers_1.ethers.JsonRpcProvider(process.env.SECRET_FAUCET_RPC);
63
- const wallet = new ethers_1.ethers.Wallet(privateAddress, provider);
64
- const nordContract = new ethers_1.ethers.Contract(contractAddress, abis_1.NORD_RAMP_FACET_ABI, wallet);
65
- const depositTx = await nordContract.depositUnchecked.populateTransaction(publicKey, BigInt(0), ethers_1.ethers.parseUnits(amount.toString(), precision), {
66
- maxFeePerGas: ethers_1.ethers.parseUnits("0.0003", "gwei"),
67
- maxPriorityFeePerGas: ethers_1.ethers.parseUnits("0.0003", "gwei"),
68
- });
69
- return JSON.stringify(depositTx);
70
- }
71
- function makeNordImpl(nord) {
72
- return {
73
- getTimestamp: () => nord.getTimestamp().then((x) => x + 1n),
74
- };
75
- }
39
+ const NordError_1 = require("./NordError");
40
+ const core = __importStar(require("./core"));
41
+ const metrics = __importStar(require("./metrics"));
42
+ const queries = __importStar(require("./queries"));
43
+ const market = __importStar(require("./market"));
44
+ /**
45
+ * Main Nord client class for interacting with the Nord API
46
+ */
76
47
  class Nord {
77
- constructor({ evmUrl, webServerUrl, tokenInfos, contractAddress, }) {
78
- this.impl = makeNordImpl(this);
79
- this.evmUrl = evmUrl;
80
- this.webServerUrl = webServerUrl;
81
- this.tokenInfos = tokenInfos;
82
- this.contractAddress = contractAddress;
48
+ /**
49
+ * Create a new Nord client instance
50
+ *
51
+ * @param config - Configuration options for the Nord client
52
+ * @throws {Error} If required configuration is missing
53
+ */
54
+ constructor({ webServerUrl, tokenInfos, solanaProgramId, solanaUrl, }) {
55
+ /** Available markets */
83
56
  this.markets = [];
57
+ /** Available tokens */
84
58
  this.tokens = [];
59
+ if (!webServerUrl) {
60
+ throw new NordError_1.NordError("webServerUrl is required");
61
+ }
62
+ this.webServerUrl = webServerUrl;
63
+ this.tokenInfos = tokenInfos || [];
64
+ this.solanaProgramId = solanaProgramId;
65
+ this.solanaUrl = solanaUrl;
66
+ // Initialize WebSocket client
67
+ this.ws = core.initWebSocketClient(webServerUrl);
85
68
  }
69
+ /**
70
+ * Get the current timestamp from the Nord server
71
+ *
72
+ * @returns Current timestamp as a bigint
73
+ * @throws {NordError} If the request fails
74
+ */
86
75
  async getTimestamp() {
87
- const resp = await (await (0, utils_1.checkedFetch)(`${this.webServerUrl}/timestamp`, { method: "GET" })).json();
88
- return BigInt(resp);
76
+ return core.getTimestamp(this.webServerUrl);
89
77
  }
78
+ /**
79
+ * Get the next action nonce from the Nord server
80
+ *
81
+ * @returns Next action nonce
82
+ * @throws {NordError} If the request fails
83
+ */
90
84
  async getActionNonce() {
91
- const resp = await (await (0, utils_1.checkedFetch)(`${this.webServerUrl}/action_nonce`, { method: "GET" })).json();
92
- return resp;
85
+ return core.getActionNonce(this.webServerUrl);
93
86
  }
87
+ /**
88
+ * Fetch information about Nord markets and tokens
89
+ *
90
+ * @throws {NordError} If the request fails
91
+ */
94
92
  async fetchNordInfo() {
95
- const response = await (0, utils_1.checkedFetch)(`${this.webServerUrl}/info`, {
96
- method: "GET",
97
- });
98
- const info = await response.json();
99
- this.markets = info.markets;
100
- this.tokens = info.tokens;
93
+ try {
94
+ const info = await core.getInfo(this.webServerUrl);
95
+ this.markets = info.markets;
96
+ this.tokens = info.tokens;
97
+ }
98
+ catch (error) {
99
+ throw new NordError_1.NordError("Failed to fetch Nord info", { cause: error });
100
+ }
101
101
  }
102
+ /**
103
+ * Initialize a new Nord client
104
+ *
105
+ * @param nordConfig - Configuration options for the Nord client
106
+ * @returns Initialized Nord client
107
+ * @throws {NordError} If initialization fails
108
+ */
102
109
  static async initNord(nordConfig) {
103
110
  const nord = new Nord(nordConfig);
104
111
  await nord.fetchNordInfo();
105
112
  return nord;
106
113
  }
107
- static async initDevNord() {
108
- const nord = new Nord({
109
- evmUrl: const_1.EVM_DEV_URL,
110
- webServerUrl: const_1.WEBSERVER_DEV_URL,
111
- tokenInfos: const_1.DEV_TOKEN_INFOS,
112
- contractAddress: const_1.DEV_CONTRACT_ADDRESS,
113
- });
114
- await nord.fetchNordInfo();
115
- return nord;
116
- }
114
+ /**
115
+ * Get market statistics
116
+ *
117
+ * @returns Market statistics response
118
+ * @throws {NordError} If the request fails
119
+ */
117
120
  async marketsStats() {
118
- const response = await (0, utils_1.checkedFetch)(`${this.webServerUrl}/stats`, {
119
- method: "GET",
120
- });
121
- const stats = await response.json();
122
- return stats;
121
+ return market.marketsStats(this.webServerUrl);
123
122
  }
124
- // Query the block info from rollman.
123
+ /**
124
+ * Query a specific block
125
+ *
126
+ * @param query - Block query parameters
127
+ * @returns Block response
128
+ * @throws {NordError} If the request fails
129
+ */
125
130
  async queryBlock(query) {
126
- const rollmanResponse = await this.blockQueryRollman(query);
127
- const queryResponse = {
128
- block_number: rollmanResponse.block_number,
129
- actions: [],
130
- };
131
- for (const rollmanAction of rollmanResponse.actions) {
132
- const blockAction = {
133
- action_id: rollmanAction.action_id,
134
- action: (0, utils_1.decodeLengthDelimited)(new Uint8Array(rollmanAction.action_pb), proto.Action),
135
- exec_timestamp: rollmanAction.exec_timestamp,
136
- };
137
- queryResponse.actions.push(blockAction);
138
- }
139
- return queryResponse;
131
+ return queries.queryBlock(this.webServerUrl, query);
140
132
  }
141
- // Query the block info from rollman.
133
+ /**
134
+ * Query the last N blocks
135
+ *
136
+ * @returns Block response for the last N blocks
137
+ * @throws {NordError} If the request fails
138
+ */
142
139
  async queryLastNBlocks() {
143
- const rollmanResponse = await this.blockQueryRollman({});
144
- const queryResponse = {
145
- block_number: rollmanResponse.block_number,
146
- actions: [],
147
- };
148
- for (const rollmanAction of rollmanResponse.actions) {
149
- const blockAction = {
150
- action_id: rollmanAction.action_id,
151
- action: (0, utils_1.decodeLengthDelimited)(rollmanAction.action_pb, proto.Action),
152
- exec_timestamp: rollmanAction.exec_timestamp,
153
- };
154
- queryResponse.actions.push(blockAction);
155
- }
156
- return queryResponse;
140
+ return queries.queryLastNBlocks(this.webServerUrl);
157
141
  }
158
- // Query the block summary of recent blocks from rollman.
142
+ /**
143
+ * Query recent blocks
144
+ *
145
+ * @param last_n - Number of recent blocks to query
146
+ * @returns Block summary response
147
+ * @throws {NordError} If the request fails
148
+ */
159
149
  async queryRecentBlocks(last_n) {
160
- const response = await this.blockSummaryQueryRollman(last_n);
161
- return response;
150
+ return queries.queryRecentBlocks(this.webServerUrl, last_n);
162
151
  }
163
- // Query the action info from rollman.
152
+ /**
153
+ * Query a specific action
154
+ *
155
+ * @param query - Action query parameters
156
+ * @returns Action response
157
+ * @throws {NordError} If the request fails
158
+ */
164
159
  async queryAction(query) {
165
- const rollmanResponse = await this.actionQueryRollman(query);
166
- return {
167
- block_number: rollmanResponse.block_number,
168
- action: (0, utils_1.decodeLengthDelimited)(rollmanResponse.action_pb, proto.Action),
169
- };
160
+ return queries.queryAction(this.webServerUrl, query);
170
161
  }
171
- // Query the recent transactions from rollman.
162
+ /**
163
+ * Query recent actions
164
+ *
165
+ * @param last_n - Number of recent actions to query
166
+ * @returns Actions response
167
+ * @throws {NordError} If the request fails
168
+ */
172
169
  async queryRecentActions(last_n) {
173
- const rollmanResponse = await this.actionsQueryRollman(last_n);
174
- const queryResponse = {
175
- actions: [],
176
- };
177
- for (const rollmanExtendedAction of rollmanResponse.actions) {
178
- const extendedActionInfo = {
179
- block_number: rollmanExtendedAction.block_number,
180
- action_id: rollmanExtendedAction.action_id,
181
- action: (0, utils_1.decodeLengthDelimited)(rollmanExtendedAction.action_pb, proto.Action),
182
- };
183
- queryResponse.actions.push(extendedActionInfo);
184
- }
185
- return queryResponse;
170
+ return queries.queryRecentActions(this.webServerUrl, last_n);
186
171
  }
187
- // Query the aggregate metrics across nord and rollman.
172
+ /**
173
+ * Fetch aggregate metrics from the Nord API
174
+ *
175
+ * @param txPeakTpsPeriod - Period for peak TPS calculation
176
+ * @param txPeakTpsPeriodUnit - Unit for peak TPS period
177
+ * @returns Aggregate metrics
178
+ * @throws {NordError} If the request fails
179
+ */
188
180
  async aggregateMetrics(txPeakTpsPeriod = 1, txPeakTpsPeriodUnit = types_1.PeakTpsPeriodUnit.Day) {
189
- // Get the latest block number for L2 blocks.
190
- const blockQuery = {};
191
- const rollmanResponse = await this.blockQueryRollman(blockQuery);
192
- const period = txPeakTpsPeriod.toString() + txPeakTpsPeriodUnit;
193
- const query = `max_over_time(rate(nord_requests_ok_count[1m])[${period}:1m])`;
194
- return {
195
- blocks_total: rollmanResponse.block_number,
196
- tx_total: await this.queryPrometheus("nord_requests_ok_count"),
197
- tx_tps: await this.getCurrentTps(),
198
- tx_tps_peak: await this.queryPrometheus(query),
199
- request_latency_average: await this.queryPrometheus('nord_requests_ok_latency{quantile="0.5"}'),
200
- };
181
+ return metrics.aggregateMetrics(this.webServerUrl, txPeakTpsPeriod, txPeakTpsPeriodUnit);
201
182
  }
183
+ /**
184
+ * Get current transactions per second
185
+ *
186
+ * @param period - Time period for the query
187
+ * @returns Current TPS value
188
+ * @throws {NordError} If the request fails
189
+ */
202
190
  async getCurrentTps(period = "1m") {
203
- return await this.queryPrometheus("rate(nord_requests_ok_count[" + period + "])");
191
+ return metrics.getCurrentTps(this.webServerUrl, period);
204
192
  }
193
+ /**
194
+ * Get peak transactions per second
195
+ *
196
+ * @param period - Time period for the query
197
+ * @returns Peak TPS value
198
+ * @throws {NordError} If the request fails
199
+ */
205
200
  async getPeakTps(period = "24h") {
206
- return await this.queryPrometheus("max_over_time(rate(nord_requests_ok_count[30s])[" + period + ":])");
201
+ return metrics.getPeakTps(this.webServerUrl, period);
207
202
  }
203
+ /**
204
+ * Get median transaction latency
205
+ *
206
+ * @param period - Time period for the query
207
+ * @returns Median latency in milliseconds
208
+ * @throws {NordError} If the request fails
209
+ */
208
210
  async getMedianLatency(period = "1m") {
209
- return await this.queryPrometheus(`avg_over_time(nord_requests_ok_latency{quantile="0.5"}[${period}])`);
211
+ return metrics.getMedianLatency(this.webServerUrl, period);
210
212
  }
213
+ /**
214
+ * Get total transaction count
215
+ *
216
+ * @returns Total transaction count
217
+ * @throws {NordError} If the request fails
218
+ */
211
219
  async getTotalTransactions() {
212
- return await (await (0, utils_1.checkedFetch)(this.webServerUrl + "/last_actionid")).text();
220
+ return metrics.getTotalTransactions(this.webServerUrl);
213
221
  }
214
- // Helper to query rollman for block info.
222
+ /**
223
+ * Query a block from Rollman
224
+ *
225
+ * @param query - Block query parameters
226
+ * @returns Rollman block response
227
+ * @throws {NordError} If the request fails
228
+ */
215
229
  async blockQueryRollman(query) {
216
- let url = this.webServerUrl + "/block_query";
217
- if (query.block_number != null) {
218
- url = url + "?block_number=" + query.block_number;
219
- }
220
- const response = await (0, utils_1.checkedFetch)(url);
221
- if (!response.ok) {
222
- throw new Error("Rollman query failed " + url);
223
- }
224
- return await response.json();
230
+ return queries.blockQueryRollman(this.webServerUrl, query);
225
231
  }
226
- // Helper to query rollman for recent block summary.
232
+ /**
233
+ * Query block summaries from Rollman
234
+ *
235
+ * @param last_n - Number of recent blocks to query
236
+ * @returns Block summary response
237
+ * @throws {NordError} If the request fails
238
+ */
227
239
  async blockSummaryQueryRollman(last_n) {
228
- const url = this.webServerUrl + "/last_n_blocks?last_n=" + last_n;
229
- const response = await (0, utils_1.checkedFetch)(url);
230
- if (!response.ok) {
231
- throw new Error("Rollman query failed " + url);
232
- }
233
- return await response.json();
240
+ return queries.blockSummaryQueryRollman(this.webServerUrl, last_n);
234
241
  }
235
- // Helper to query rollman for action info.
242
+ /**
243
+ * Query an action from Rollman
244
+ *
245
+ * @param query - Action query parameters
246
+ * @returns Rollman action response
247
+ * @throws {NordError} If the request fails
248
+ */
236
249
  async actionQueryRollman(query) {
237
- const url = this.webServerUrl + "/tx_query?action_id=" + query.action_id;
238
- const response = await (0, utils_1.checkedFetch)(url);
239
- if (!response.ok) {
240
- throw new Error("Rollman query failed " + url);
241
- }
242
- return await response.json();
250
+ return queries.actionQueryRollman(this.webServerUrl, query);
243
251
  }
244
- // Helper to query rollman for recent actions.
252
+ /**
253
+ * Query actions from Rollman
254
+ *
255
+ * @param last_n - Number of recent actions to query
256
+ * @returns Rollman actions response
257
+ * @throws {NordError} If the request fails
258
+ */
245
259
  async actionsQueryRollman(last_n) {
246
- const url = this.webServerUrl + "/last_n_actions?last_n=" + last_n;
247
- const response = await (0, utils_1.checkedFetch)(url);
248
- if (!response.ok) {
249
- throw new Error("Rollman query failed " + url);
250
- }
251
- return await response.json();
260
+ return queries.actionsQueryRollman(this.webServerUrl, last_n);
252
261
  }
253
- // Helper to query prometheus.
262
+ /**
263
+ * Query Prometheus metrics
264
+ *
265
+ * @param params - Prometheus query parameters
266
+ * @returns Query result as a number
267
+ * @throws {NordError} If the request fails
268
+ */
254
269
  async queryPrometheus(params) {
255
- const url = this.webServerUrl + "/prometheus_query?query=" + params;
256
- const response = await (0, utils_1.checkedFetch)(url);
257
- if (!response.ok) {
258
- throw new Error("Prometheus query failed " + url);
259
- }
260
- const json = await response.json();
261
- // Prometheus HTTP API: https://prometheus.io/docs/prometheus/latest/querying/api/
262
- return Number(json.data.result[0].value[1]);
270
+ return metrics.queryPrometheus(this.webServerUrl, params);
263
271
  }
264
- static async approveTx(privateAddress, erc20address, contractAddress) {
265
- const provider = new ethers_1.ethers.JsonRpcProvider(process.env.SECRET_FAUCET_RPC);
266
- const wallet = new ethers_1.ethers.Wallet(privateAddress, provider);
267
- const erc20Contract = new ethers_1.ethers.Contract(erc20address, abis_1.ERC20_ABI, wallet);
268
- const maxUint256 = ethers_1.ethers.MaxUint256;
269
- const approveTx = await erc20Contract.approve(contractAddress, maxUint256.toString(), {
270
- maxFeePerGas: ethers_1.ethers.parseUnits("30", "gwei"),
271
- maxPriorityFeePerGas: ethers_1.ethers.parseUnits("0.001", "gwei"),
272
- });
273
- return approveTx.hash;
272
+ /**
273
+ * Get the WebSocket client
274
+ *
275
+ * @returns WebSocket client
276
+ */
277
+ getWebSocketClient() {
278
+ return this.ws;
274
279
  }
275
280
  /**
276
- * Fetches a sequence of actions between specified action IDs
277
- * @param fromActionId - Starting action ID
278
- * @param toActionId - Ending action ID
279
- * @returns A promise that resolves to an ActionsResponse
281
+ * Subscribe to orderbook updates for a market
282
+ *
283
+ * @param symbol - Market symbol
284
+ * @returns Orderbook subscription
280
285
  */
281
- async getActions(fromActionId, toActionId) {
282
- const response = await (0, utils_1.checkedFetch)(`${this.webServerUrl}/actions?from=${fromActionId}&to=${toActionId}`, { method: "GET" });
283
- const rawResponse = await response.json();
284
- const queryResponse = {
285
- actions: [],
286
+ subscribeOrderbook(symbol) {
287
+ const subscription = new events_1.EventEmitter();
288
+ const handleDelta = (update) => {
289
+ if (update.market_symbol === symbol) {
290
+ subscription.emit("message", {
291
+ asks: update.asks,
292
+ bids: update.bids,
293
+ market_symbol: update.market_symbol,
294
+ last_update_id: update.last_update_id,
295
+ });
296
+ }
297
+ };
298
+ this.ws.on("delta", handleDelta);
299
+ this.ws.subscribe([`deltas@${symbol}`]);
300
+ subscription.close = () => {
301
+ this.ws.unsubscribe([`deltas@${symbol}`]);
302
+ this.ws.removeAllListeners("delta");
303
+ subscription.removeAllListeners();
286
304
  };
287
- if (Array.isArray(rawResponse.actions)) {
288
- for (const action of rawResponse.actions) {
289
- const extendedActionInfo = {
290
- block_number: action.block_number,
291
- action_id: action.action_id,
292
- action: (0, utils_1.decodeLengthDelimited)(action.action_pb, proto.Action),
293
- };
294
- queryResponse.actions.push(extendedActionInfo);
305
+ return subscription;
306
+ }
307
+ /**
308
+ * Subscribe to trade updates for a market
309
+ *
310
+ * @param symbol - Market symbol
311
+ * @returns Trade subscription
312
+ */
313
+ subscribeTrades(symbol) {
314
+ const subscription = new events_1.EventEmitter();
315
+ const handleTrade = (update) => {
316
+ if (update.market_symbol === symbol) {
317
+ subscription.emit("message", update.trades);
295
318
  }
296
- }
297
- return queryResponse;
319
+ };
320
+ this.ws.on("trade", handleTrade);
321
+ this.ws.subscribe([`trades@${symbol}`]);
322
+ subscription.close = () => {
323
+ this.ws.unsubscribe([`trades@${symbol}`]);
324
+ this.ws.removeAllListeners("trade");
325
+ subscription.removeAllListeners();
326
+ };
327
+ return subscription;
298
328
  }
299
329
  /**
300
- * Fetches trades for a specified account
301
- * @param params - Query parameters for fetching trades
302
- * @returns A promise that resolves to a TradesResponse
330
+ * Get trades for a market
331
+ *
332
+ * @param query - Trades query parameters
333
+ * @returns Trades response
334
+ * @throws {NordError} If the request fails
303
335
  */
304
- async getTrades(params) {
305
- const { accountId, since, until, pageId } = params;
306
- let url = `${this.webServerUrl}/trades?accountId=${accountId}`;
307
- if (since) {
308
- url += `&since=${encodeURIComponent(since)}`;
309
- }
310
- if (until) {
311
- url += `&until=${encodeURIComponent(until)}`;
312
- }
313
- if (pageId) {
314
- url += `&pageId=${encodeURIComponent(pageId)}`;
315
- }
316
- const response = await (0, utils_1.checkedFetch)(url, { method: "GET" });
317
- const tradesResponse = await response.json();
318
- return tradesResponse;
336
+ async getTrades(query) {
337
+ return market.getTrades(this.webServerUrl, query);
319
338
  }
320
339
  /**
321
- * Fetches the orderbook for a specified market
322
- * @param symbol - Market symbol
323
- * @returns A promise that resolves to an OrderbookResponse
340
+ * Get user account IDs
341
+ *
342
+ * @param query - User account IDs query parameters
343
+ * @returns User account IDs response
344
+ * @throws {NordError} If the request fails
324
345
  */
325
- async getOrderbook(symbol) {
326
- const response = await (0, utils_1.checkedFetch)(`${this.webServerUrl}/orderbook?symbol=${encodeURIComponent(symbol)}`, { method: "GET" });
327
- const orderbook = await response.json();
328
- return orderbook;
346
+ async getUserAccountIds(query) {
347
+ return market.getUserAccountIds(this.webServerUrl, query);
329
348
  }
330
- }
331
- exports.Nord = Nord;
332
- class Subscriber {
333
- constructor(config) {
334
- this.streamURL = config.streamURL;
335
- this.buffer = [];
336
- this.maxBufferLen = config.maxBufferLen || utils_1.MAX_BUFFER_LEN;
349
+ /**
350
+ * Get orderbook for a market
351
+ *
352
+ * @param query - Orderbook query parameters
353
+ * @returns Orderbook response
354
+ * @throws {NordError} If the request fails
355
+ */
356
+ async getOrderbook(query) {
357
+ return market.getOrderbook(this.webServerUrl, query);
337
358
  }
338
- subscribe() {
339
- const ws = new ws_1.default(this.streamURL);
340
- ws.on("message", (data) => {
341
- try {
342
- const parsed = JSON.parse(data.toString());
343
- this.buffer.push(parsed);
344
- if (this.buffer.length > this.maxBufferLen) {
345
- this.buffer.shift();
346
- }
347
- }
348
- catch (e) {
349
- console.error("Failed to parse websocket message", e);
350
- }
351
- });
359
+ /**
360
+ * Get information about the Nord server
361
+ *
362
+ * @returns Information about markets and tokens
363
+ * @throws {NordError} If the request fails
364
+ */
365
+ async getInfo() {
366
+ return core.getInfo(this.webServerUrl);
367
+ }
368
+ /**
369
+ * Get account information
370
+ *
371
+ * @param accountId - Account ID to get information for
372
+ * @returns Account information
373
+ * @throws {NordError} If the request fails
374
+ */
375
+ async getAccount(accountId) {
376
+ return core.getAccount(this.webServerUrl, accountId);
377
+ }
378
+ /**
379
+ * Get market statistics (alias for marketsStats for backward compatibility)
380
+ *
381
+ * @deprecated Use marketsStats instead
382
+ * @returns Market statistics response
383
+ */
384
+ async getMarketStats() {
385
+ return this.marketsStats();
352
386
  }
353
387
  }
354
- exports.Subscriber = Subscriber;
355
- /**
356
- * Creates a WebSocket subscription to specified streams
357
- * @param baseUrl - Base URL of the API
358
- * @param streams - Array of streams to subscribe to
359
- * @returns A Subscriber instance
360
- *
361
- * Syntax for streams:
362
- * - trades@<symbol>: Subscribe to trades for a market
363
- * - deltas@<symbol>: Subscribe to orderbook deltas for a market
364
- * - user@<user id>: Subscribe to user account updates
365
- *
366
- * Example: createWebSocketSubscription('https://alpha-api.layern.network', ['trades@BTCUSDC', 'deltas@BTCUSDC', 'user@0'])
367
- */
368
- function createWebSocketSubscription(baseUrl, streams) {
369
- const streamPath = streams.join('&');
370
- const wsUrl = baseUrl.replace(/^http/, 'ws') + `/ws/${streamPath}`;
371
- const subscriber = new Subscriber({
372
- streamURL: wsUrl,
373
- });
374
- subscriber.subscribe();
375
- return subscriber;
376
- }
388
+ exports.Nord = Nord;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Custom error class for Nord-related errors
3
+ * Extends the standard Error class with additional context
4
+ */
5
+ export declare class NordError extends Error {
6
+ /** The original error that caused this error, if any */
7
+ readonly cause?: unknown;
8
+ /**
9
+ * Create a new NordError
10
+ *
11
+ * @param message - Error message
12
+ * @param options - Additional error options
13
+ */
14
+ constructor(message: string, options?: {
15
+ cause?: unknown;
16
+ });
17
+ /**
18
+ * Get a string representation of the error including the cause if available
19
+ *
20
+ * @returns String representation of the error
21
+ */
22
+ toString(): string;
23
+ }