@n1xyz/nord-ts 0.0.19 → 0.0.21

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 (52) hide show
  1. package/dist/const.d.ts +8 -0
  2. package/dist/const.js +30 -0
  3. package/dist/gen/nord.d.ts +882 -0
  4. package/dist/gen/nord.js +6520 -0
  5. package/dist/gen/openapi.d.ts +2244 -0
  6. package/dist/gen/openapi.js +6 -0
  7. package/dist/index.d.ts +5 -0
  8. package/dist/index.js +21 -0
  9. package/dist/nord/api/actions.d.ts +135 -0
  10. package/dist/nord/api/actions.js +313 -0
  11. package/dist/nord/api/core.d.ts +16 -0
  12. package/dist/nord/api/core.js +81 -0
  13. package/dist/nord/api/metrics.d.ts +67 -0
  14. package/dist/nord/api/metrics.js +229 -0
  15. package/dist/nord/client/Nord.d.ts +282 -0
  16. package/dist/nord/client/Nord.js +528 -0
  17. package/dist/nord/client/NordUser.d.ts +340 -0
  18. package/dist/nord/client/NordUser.js +652 -0
  19. package/dist/nord/index.d.ts +7 -0
  20. package/dist/nord/index.js +31 -0
  21. package/dist/nord/models/Subscriber.d.ts +37 -0
  22. package/dist/nord/models/Subscriber.js +25 -0
  23. package/dist/nord/utils/NordError.d.ts +35 -0
  24. package/dist/nord/utils/NordError.js +49 -0
  25. package/dist/types.d.ts +251 -0
  26. package/dist/types.js +101 -0
  27. package/dist/utils.d.ts +98 -0
  28. package/dist/utils.js +237 -0
  29. package/dist/websocket/NordWebSocketClient.d.ts +57 -0
  30. package/dist/websocket/NordWebSocketClient.js +251 -0
  31. package/dist/websocket/events.d.ts +19 -0
  32. package/dist/websocket/events.js +2 -0
  33. package/dist/websocket/index.d.ts +2 -0
  34. package/dist/websocket/index.js +5 -0
  35. package/package.json +8 -2
  36. package/src/gen/.gitkeep +0 -0
  37. package/src/gen/nord.ts +7593 -0
  38. package/src/gen/openapi.ts +2245 -0
  39. package/src/nord/api/core.ts +1 -16
  40. package/src/nord/client/Nord.ts +7 -11
  41. package/src/types.ts +0 -11
  42. package/src/websocket/NordWebSocketClient.ts +0 -113
  43. package/.claude/settings.local.json +0 -11
  44. package/.local/qa.ts +0 -77
  45. package/.local/test-atomic.ts +0 -112
  46. package/.prettierignore +0 -2
  47. package/check.sh +0 -4
  48. package/default.nix +0 -47
  49. package/eslint.config.mjs +0 -66
  50. package/tests/utils.spec.ts +0 -121
  51. package/tsconfig.eslint.json +0 -12
  52. package/tsconfig.json +0 -24
@@ -0,0 +1,652 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.NordUser = void 0;
37
+ const spl_token_1 = require("@solana/spl-token");
38
+ const web3_js_1 = require("@solana/web3.js");
39
+ const ed = __importStar(require("@noble/ed25519"));
40
+ const sha512_1 = require("@noble/hashes/sha512");
41
+ ed.etc.sha512Sync = sha512_1.sha512;
42
+ const proton_1 = require("@n1xyz/proton");
43
+ const utils_1 = require("../../utils");
44
+ const actions_1 = require("../api/actions");
45
+ const NordError_1 = require("../utils/NordError");
46
+ /**
47
+ * User class for interacting with the Nord protocol
48
+ */
49
+ class NordUser {
50
+ /**
51
+ * Create a new NordUser instance
52
+ *
53
+ * @param params - Parameters for creating a NordUser
54
+ * @throws {NordError} If required parameters are missing
55
+ */
56
+ constructor({ address, nord, publicKey, sessionPubKey, sessionSignFn, transactionSignFn, walletSignFn, connection, sessionId, }) {
57
+ /** User balances by token symbol */
58
+ this.balances = {};
59
+ /** User positions by account ID */
60
+ this.positions = {};
61
+ /** User margins by account ID */
62
+ this.margins = {};
63
+ /** Last timestamp used */
64
+ this.lastTs = 0;
65
+ /** Last nonce used */
66
+ this.lastNonce = 0;
67
+ /** SPL token information */
68
+ this.splTokenInfos = [];
69
+ if (!walletSignFn) {
70
+ throw new NordError_1.NordError("Wallet sign function is required");
71
+ }
72
+ if (!sessionSignFn) {
73
+ throw new NordError_1.NordError("Session sign function is required");
74
+ }
75
+ if (!sessionPubKey) {
76
+ throw new NordError_1.NordError("Session public key is required");
77
+ }
78
+ try {
79
+ this.address = new web3_js_1.PublicKey(address);
80
+ }
81
+ catch (error) {
82
+ throw new NordError_1.NordError("Invalid Solana address", { cause: error });
83
+ }
84
+ this.nord = nord;
85
+ this.walletSignFn = walletSignFn;
86
+ this.sessionSignFn = sessionSignFn;
87
+ this.transactionSignFn = transactionSignFn;
88
+ this.sessionPubKey = sessionPubKey;
89
+ this.publicKey = publicKey;
90
+ this.connection =
91
+ connection ||
92
+ new web3_js_1.Connection(nord.solanaUrl, {
93
+ commitment: "confirmed",
94
+ });
95
+ // Set sessionId if provided
96
+ if (sessionId !== undefined) {
97
+ this.sessionId = sessionId;
98
+ }
99
+ // Convert tokens from info endpoint to SPLTokenInfo
100
+ if (this.nord.tokens && this.nord.tokens.length > 0) {
101
+ this.splTokenInfos = this.nord.tokens.map((token) => ({
102
+ mint: token.mintAddr, // Use mintAddr as mint
103
+ precision: token.decimals,
104
+ tokenId: token.tokenId,
105
+ name: token.symbol,
106
+ }));
107
+ }
108
+ }
109
+ /**
110
+ * Create a clone of this NordUser instance
111
+ *
112
+ * @returns A new NordUser instance with the same properties
113
+ */
114
+ clone() {
115
+ const cloned = new NordUser({
116
+ nord: this.nord,
117
+ address: this.address.toBase58(),
118
+ walletSignFn: this.walletSignFn,
119
+ sessionSignFn: this.sessionSignFn,
120
+ transactionSignFn: this.transactionSignFn,
121
+ connection: this.connection,
122
+ sessionPubKey: this.sessionPubKey,
123
+ publicKey: this.publicKey,
124
+ });
125
+ // Copy other properties
126
+ cloned.balances = { ...this.balances };
127
+ cloned.positions = { ...this.positions };
128
+ cloned.margins = { ...this.margins };
129
+ cloned.accountIds = this.accountIds ? [...this.accountIds] : undefined;
130
+ cloned.sessionId = this.sessionId;
131
+ cloned.publicKey = this.publicKey;
132
+ cloned.lastTs = this.lastTs;
133
+ cloned.lastNonce = this.lastNonce;
134
+ cloned.splTokenInfos = [...this.splTokenInfos];
135
+ return cloned;
136
+ }
137
+ /**
138
+ * Create a NordUser from a private key
139
+ *
140
+ * @param nord - Nord instance
141
+ * @param privateKey - Private key as string or Uint8Array
142
+ * @param connection - Solana connection (optional)
143
+ * @returns NordUser instance
144
+ * @throws {NordError} If the private key is invalid
145
+ */
146
+ static fromPrivateKey(nord, privateKey, connection) {
147
+ try {
148
+ const keypair = (0, utils_1.keypairFromPrivateKey)(privateKey);
149
+ const publicKey = keypair.publicKey;
150
+ // Create a signing function that uses the keypair but doesn't expose it
151
+ const walletSignFn = async (message) => {
152
+ function toHex(buffer) {
153
+ return Array.from(buffer)
154
+ .map((byte) => byte.toString(16).padStart(2, "0"))
155
+ .join("");
156
+ }
157
+ const messageBuffer = new TextEncoder().encode(toHex(message));
158
+ // Use ed25519 to sign the message
159
+ const signature = ed.sign(messageBuffer, keypair.secretKey.slice(0, 32));
160
+ return signature;
161
+ };
162
+ const sessionSignFn = async (message) => {
163
+ // Use ed25519 to sign the message
164
+ return ed.sign(message, keypair.secretKey.slice(0, 32));
165
+ };
166
+ // Create a transaction signing function
167
+ const transactionSignFn = async (transaction) => {
168
+ // This is a basic implementation - actual implementation would depend on the transaction type
169
+ if (transaction.sign) {
170
+ // Solana transaction
171
+ transaction.sign(keypair);
172
+ return transaction;
173
+ }
174
+ // For other transaction types, would need specific implementation
175
+ throw new NordError_1.NordError("Unsupported transaction type for signing");
176
+ };
177
+ return new NordUser({
178
+ nord,
179
+ address: publicKey.toBase58(),
180
+ walletSignFn,
181
+ sessionSignFn,
182
+ transactionSignFn,
183
+ connection,
184
+ publicKey,
185
+ sessionPubKey: publicKey.toBytes(), // Use the public key derived from the private key as the session public key
186
+ });
187
+ }
188
+ catch (error) {
189
+ throw new NordError_1.NordError("Failed to create NordUser from private key", {
190
+ cause: error,
191
+ });
192
+ }
193
+ }
194
+ /**
195
+ * Get the associated token account for a token mint
196
+ *
197
+ * @param mint - Token mint address
198
+ * @returns Associated token account address
199
+ * @throws {NordError} If required parameters are missing or operation fails
200
+ */
201
+ async getAssociatedTokenAccount(mint) {
202
+ if (!this.getSolanaPublicKey()) {
203
+ throw new NordError_1.NordError("Solana public key is required to get associated token account");
204
+ }
205
+ try {
206
+ // Get the token program ID from the mint account
207
+ const mintAccount = await this.connection.getAccountInfo(mint);
208
+ if (!mintAccount) {
209
+ throw new NordError_1.NordError("Mint account not found");
210
+ }
211
+ const tokenProgramId = mintAccount.owner;
212
+ // Validate that the mint is owned by a supported SPL token program
213
+ if (!tokenProgramId.equals(spl_token_1.TOKEN_PROGRAM_ID) &&
214
+ !tokenProgramId.equals(spl_token_1.TOKEN_2022_PROGRAM_ID)) {
215
+ throw new NordError_1.NordError("Mint Account is not owned by a supported SPL token program");
216
+ }
217
+ const associatedTokenAddress = await (0, spl_token_1.getAssociatedTokenAddress)(mint, this.getSolanaPublicKey(), false, tokenProgramId, spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID);
218
+ return associatedTokenAddress;
219
+ }
220
+ catch (error) {
221
+ throw new NordError_1.NordError("Failed to get associated token account", {
222
+ cause: error,
223
+ });
224
+ }
225
+ }
226
+ /**
227
+ * Deposit SPL tokens to the bridge
228
+ *
229
+ * @param amount - Amount to deposit
230
+ * @param tokenId - Token ID
231
+ * @param recipient - Recipient address; defaults to the user's address
232
+ * @returns Transaction signature
233
+ * @deprecated Use deposit instead
234
+ * @throws {NordError} If required parameters are missing or operation fails
235
+ */
236
+ async depositSpl(amount, tokenId, recipient) {
237
+ return this.deposit({ amount, tokenId, recipient });
238
+ }
239
+ /**
240
+ * Deposit SPL tokens to the bridge
241
+ *
242
+ * @param amount - Amount to deposit
243
+ * @param tokenId - Token ID
244
+ * @param recipient - Recipient address; defaults to the user's address
245
+ * @returns Transaction signature
246
+ * @throws {NordError} If required parameters are missing or operation fails
247
+ */
248
+ async deposit({ amount, tokenId, recipient, }) {
249
+ try {
250
+ // Find the token info
251
+ const tokenInfo = this.splTokenInfos.find((t) => t.tokenId === tokenId);
252
+ if (!tokenInfo) {
253
+ throw new NordError_1.NordError(`Token with ID ${tokenId} not found`);
254
+ }
255
+ const mint = new web3_js_1.PublicKey(tokenInfo.mint);
256
+ const fromAccount = await this.getAssociatedTokenAccount(mint);
257
+ const payer = this.getSolanaPublicKey();
258
+ const { ix, extraSigner } = await this.nord.protonClient.buildDepositIx({
259
+ payer,
260
+ recipient: recipient ?? payer,
261
+ quantAmount: (0, proton_1.floatToScaledBigIntLossy)(amount, tokenInfo.precision),
262
+ mint,
263
+ sourceTokenAccount: fromAccount,
264
+ });
265
+ const { blockhash } = await this.connection.getLatestBlockhash("confirmed");
266
+ const tx = new web3_js_1.Transaction();
267
+ tx.add(ix);
268
+ tx.recentBlockhash = blockhash;
269
+ tx.feePayer = payer;
270
+ const signedTx = await this.transactionSignFn(tx);
271
+ signedTx.partialSign(extraSigner);
272
+ const signature = await this.connection.sendRawTransaction(signedTx.serialize());
273
+ return signature;
274
+ }
275
+ catch (error) {
276
+ throw new NordError_1.NordError(`Failed to deposit ${amount} of token ID ${tokenId}`, { cause: error });
277
+ }
278
+ }
279
+ /**
280
+ * Get a new nonce for actions
281
+ *
282
+ * @returns Nonce as number
283
+ */
284
+ getNonce() {
285
+ return ++this.lastNonce;
286
+ }
287
+ /**
288
+ * Update account IDs for this user
289
+ *
290
+ * @throws {NordError} If the operation fails
291
+ */
292
+ async updateAccountId() {
293
+ try {
294
+ if (!this.publicKey) {
295
+ throw new NordError_1.NordError("Public key is required to update account ID");
296
+ }
297
+ const resp = await this.nord.getUser({
298
+ pubkey: this.publicKey.toBase58(),
299
+ });
300
+ if (!resp) {
301
+ throw new NordError_1.NordError(`User ${this.publicKey.toBase58()} not found`);
302
+ }
303
+ this.accountIds = resp.accountIds;
304
+ }
305
+ catch (error) {
306
+ throw new NordError_1.NordError("Failed to update account ID", { cause: error });
307
+ }
308
+ }
309
+ /**
310
+ * Fetch user information including balances and orders
311
+ *
312
+ * @throws {NordError} If the operation fails
313
+ */
314
+ async fetchInfo() {
315
+ if (this.accountIds !== undefined) {
316
+ const accountsData = await Promise.all(this.accountIds.map(async (accountId) => {
317
+ const response = await (0, utils_1.checkedFetch)(`${this.nord.webServerUrl}/account/${accountId}`);
318
+ const accountData = (await response.json());
319
+ // Ensure we have the correct accountId
320
+ return {
321
+ ...accountData,
322
+ accountId,
323
+ };
324
+ }));
325
+ for (const accountData of accountsData) {
326
+ // Process balances
327
+ this.balances[accountData.accountId] = [];
328
+ for (const balance of accountData.balances) {
329
+ this.balances[accountData.accountId].push({
330
+ accountId: accountData.accountId,
331
+ balance: balance.amount,
332
+ symbol: balance.token,
333
+ });
334
+ }
335
+ // Process positions
336
+ this.positions[accountData.accountId] = accountData.positions;
337
+ // Process margins
338
+ this.margins[accountData.accountId] = accountData.margins;
339
+ }
340
+ }
341
+ }
342
+ /**
343
+ * Refresh the user's session
344
+ *
345
+ * @throws {NordError} If the operation fails
346
+ */
347
+ async refreshSession() {
348
+ this.sessionId = await (0, actions_1.createSession)(this.nord.webServerUrl, this.walletSignFn, await this.nord.getTimestamp(), this.getNonce(), {
349
+ userPubkey: (0, utils_1.optExpect)(this.publicKey.toBytes(), "No user's public key"),
350
+ sessionPubkey: this.sessionPubKey,
351
+ });
352
+ }
353
+ /**
354
+ * Revoke a session
355
+ *
356
+ * @param sessionId - Session ID to revoke
357
+ * @throws {NordError} If the operation fails
358
+ */
359
+ async revokeSession(sessionId) {
360
+ try {
361
+ await (0, actions_1.revokeSession)(this.nord.webServerUrl, this.walletSignFn, await this.nord.getTimestamp(), this.getNonce(), {
362
+ sessionId,
363
+ });
364
+ }
365
+ catch (error) {
366
+ throw new NordError_1.NordError(`Failed to revoke session ${sessionId}`, {
367
+ cause: error,
368
+ });
369
+ }
370
+ }
371
+ /**
372
+ * Checks if the session is valid
373
+ * @private
374
+ * @throws {NordError} If the session is not valid
375
+ */
376
+ checkSessionValidity() {
377
+ if (this.sessionId === undefined || this.sessionId === BigInt(0)) {
378
+ throw new NordError_1.NordError("Invalid or empty session ID. Please create or refresh your session.");
379
+ }
380
+ }
381
+ /**
382
+ * Withdraw tokens from the exchange
383
+ *
384
+ * @param tokenId - Token ID to withdraw
385
+ * @param amount - Amount to withdraw
386
+ * @throws {NordError} If the operation fails
387
+ */
388
+ async withdraw({ amount, tokenId, }) {
389
+ try {
390
+ this.checkSessionValidity();
391
+ const { actionId } = await (0, actions_1.withdraw)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.getTimestamp(), this.getNonce(), {
392
+ sizeDecimals: (0, utils_1.findToken)(this.nord.tokens, tokenId).decimals,
393
+ sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
394
+ tokenId: tokenId,
395
+ amount,
396
+ });
397
+ return { actionId };
398
+ }
399
+ catch (error) {
400
+ throw new NordError_1.NordError(`Failed to withdraw ${amount} of token ID ${tokenId}`, { cause: error });
401
+ }
402
+ }
403
+ /**
404
+ * Place an order on the exchange
405
+ *
406
+ * @param params - Order parameters
407
+ * @returns Order ID if successful
408
+ * @throws {NordError} If the operation fails
409
+ */
410
+ async placeOrder(params) {
411
+ try {
412
+ this.checkSessionValidity();
413
+ const market = (0, utils_1.findMarket)(this.nord.markets, params.marketId);
414
+ if (!market) {
415
+ throw new NordError_1.NordError(`Market with ID ${params.marketId} not found`);
416
+ }
417
+ return (0, actions_1.placeOrder)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.getTimestamp(), this.getNonce(), {
418
+ sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
419
+ senderId: params.accountId,
420
+ sizeDecimals: market.sizeDecimals,
421
+ priceDecimals: market.priceDecimals,
422
+ marketId: params.marketId,
423
+ side: params.side,
424
+ fillMode: params.fillMode,
425
+ isReduceOnly: params.isReduceOnly,
426
+ size: params.size,
427
+ price: params.price,
428
+ quoteSize: params.quoteSize,
429
+ });
430
+ }
431
+ catch (error) {
432
+ throw new NordError_1.NordError("Failed to place order", { cause: error });
433
+ }
434
+ }
435
+ /**
436
+ * Cancel an order
437
+ *
438
+ * @param orderId - Order ID to cancel
439
+ * @param providedAccountId - Account ID that placed the order
440
+ * @returns Action ID if successful
441
+ * @throws {NordError} If the operation fails
442
+ */
443
+ async cancelOrder(orderId, providedAccountId) {
444
+ const accountId = providedAccountId != null ? providedAccountId : this.accountIds?.[0];
445
+ try {
446
+ this.checkSessionValidity();
447
+ return (0, actions_1.cancelOrder)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.getTimestamp(), this.getNonce(), {
448
+ sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
449
+ senderId: accountId,
450
+ orderId,
451
+ });
452
+ }
453
+ catch (error) {
454
+ throw new NordError_1.NordError(`Failed to cancel order ${orderId}`, {
455
+ cause: error,
456
+ });
457
+ }
458
+ }
459
+ /**
460
+ * Transfer tokens to another account
461
+ *
462
+ * @param params - Transfer parameters
463
+ * @throws {NordError} If the operation fails
464
+ */
465
+ async transferToAccount(params) {
466
+ try {
467
+ this.checkSessionValidity();
468
+ const token = (0, utils_1.findToken)(this.nord.tokens, params.tokenId);
469
+ await (0, actions_1.transfer)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.getTimestamp(), this.getNonce(), {
470
+ sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
471
+ fromAccountId: (0, utils_1.optExpect)(params.fromAccountId, "No source account"),
472
+ toAccountId: (0, utils_1.optExpect)(params.toAccountId, "No target account"),
473
+ tokenId: params.tokenId,
474
+ tokenDecimals: token.decimals,
475
+ amount: params.amount,
476
+ });
477
+ }
478
+ catch (error) {
479
+ throw new NordError_1.NordError("Failed to transfer tokens", { cause: error });
480
+ }
481
+ }
482
+ /**
483
+ * Execute up to four place/cancel operations atomically.
484
+ * Per Market:
485
+ * 1. cancels can only be in the start (one cannot predict future order ids)
486
+ * 2. intermediate trades can trade only
487
+ * 3. placements go last
488
+ *
489
+ * Across Markets, order action can be any
490
+ *
491
+ * @param userActions array of user-friendly subactions
492
+ * @param providedAccountId optional account performing the action (defaults to first account)
493
+ */
494
+ async atomic(userActions, providedAccountId) {
495
+ try {
496
+ this.checkSessionValidity();
497
+ const accountId = providedAccountId != null ? providedAccountId : this.accountIds?.[0];
498
+ if (accountId == null) {
499
+ throw new NordError_1.NordError("Account ID is undefined. Make sure to call updateAccountId() before atomic operations.");
500
+ }
501
+ const apiActions = userActions.map((act) => {
502
+ if (act.kind === "place") {
503
+ const market = (0, utils_1.findMarket)(this.nord.markets, act.marketId);
504
+ if (!market) {
505
+ throw new NordError_1.NordError(`Market ${act.marketId} not found`);
506
+ }
507
+ return {
508
+ kind: "place",
509
+ marketId: act.marketId,
510
+ side: act.side,
511
+ fillMode: act.fillMode,
512
+ isReduceOnly: act.isReduceOnly,
513
+ sizeDecimals: market.sizeDecimals,
514
+ priceDecimals: market.priceDecimals,
515
+ size: act.size,
516
+ price: act.price,
517
+ quoteSizeSize: act.quoteSize, // treated as quote size; we pass only size component
518
+ quoteSizePrice: undefined,
519
+ clientOrderId: act.clientOrderId,
520
+ };
521
+ }
522
+ return {
523
+ kind: "cancel",
524
+ orderId: act.orderId,
525
+ };
526
+ });
527
+ const result = await (0, actions_1.atomic)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.getTimestamp(), this.getNonce(), {
528
+ sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
529
+ accountId: accountId,
530
+ actions: apiActions,
531
+ });
532
+ return result;
533
+ }
534
+ catch (error) {
535
+ throw new NordError_1.NordError("Atomic operation failed", { cause: error });
536
+ }
537
+ }
538
+ /**
539
+ * Helper function to retry a promise with exponential backoff
540
+ *
541
+ * @param fn - Function to retry
542
+ * @param maxRetries - Maximum number of retries
543
+ * @param initialDelay - Initial delay in milliseconds
544
+ * @returns Promise result
545
+ */
546
+ async retryWithBackoff(fn, maxRetries = 3, initialDelay = 500) {
547
+ let retries = 0;
548
+ let delay = initialDelay;
549
+ while (true) {
550
+ try {
551
+ return await fn();
552
+ }
553
+ catch (error) {
554
+ if (retries >= maxRetries) {
555
+ throw error;
556
+ }
557
+ // Check if error is rate limiting related
558
+ const isRateLimitError = error instanceof Error &&
559
+ (error.message.includes("rate limit") ||
560
+ error.message.includes("429") ||
561
+ error.message.includes("too many requests"));
562
+ if (!isRateLimitError) {
563
+ throw error;
564
+ }
565
+ retries++;
566
+ await new Promise((resolve) => setTimeout(resolve, delay));
567
+ delay *= 2; // Exponential backoff
568
+ }
569
+ }
570
+ }
571
+ /**
572
+ * Get user's token balances on Solana chain using mintAddr
573
+ *
574
+ * @param options - Optional parameters
575
+ * @param options.includeZeroBalances - Whether to include tokens with zero balance (default: true)
576
+ * @param options.includeTokenAccounts - Whether to include token account addresses in the result (default: false)
577
+ * @param options.maxConcurrent - Maximum number of concurrent requests (default: 5)
578
+ * @param options.maxRetries - Maximum number of retries for rate-limited requests (default: 3)
579
+ * @returns Object with token balances and optional token account addresses
580
+ * @throws {NordError} If required parameters are missing or operation fails
581
+ */
582
+ async getSolanaBalances(options = {}) {
583
+ const { includeZeroBalances = true, includeTokenAccounts = false, maxConcurrent = 5, maxRetries = 3, } = options;
584
+ if (!this.connection || !this.getSolanaPublicKey()) {
585
+ throw new NordError_1.NordError("Connection and Solana public key are required to get Solana balances");
586
+ }
587
+ const balances = {};
588
+ const tokenAccounts = {};
589
+ try {
590
+ // Get SOL balance (native token)
591
+ const solBalance = await this.retryWithBackoff(() => this.connection.getBalance(this.getSolanaPublicKey()), maxRetries);
592
+ balances["SOL"] = solBalance / 1e9; // Convert lamports to SOL
593
+ if (includeTokenAccounts) {
594
+ tokenAccounts["SOL"] = this.getSolanaPublicKey().toString();
595
+ }
596
+ // Get SPL token balances using mintAddr from Nord tokens
597
+ if (this.nord.tokens && this.nord.tokens.length > 0) {
598
+ const tokens = this.nord.tokens.filter((token) => !!token.mintAddr);
599
+ // Process tokens in batches to avoid rate limiting
600
+ for (let i = 0; i < tokens.length; i += maxConcurrent) {
601
+ const batch = tokens.slice(i, i + maxConcurrent);
602
+ // Process batch in parallel
603
+ const batchPromises = batch.map(async (token) => {
604
+ try {
605
+ const mint = new web3_js_1.PublicKey(token.mintAddr);
606
+ const associatedTokenAddress = await this.retryWithBackoff(() => (0, spl_token_1.getAssociatedTokenAddress)(mint, this.getSolanaPublicKey()), maxRetries);
607
+ if (includeTokenAccounts) {
608
+ tokenAccounts[token.symbol] = associatedTokenAddress.toString();
609
+ }
610
+ try {
611
+ const tokenBalance = await this.retryWithBackoff(() => this.connection.getTokenAccountBalance(associatedTokenAddress), maxRetries);
612
+ const balance = Number(tokenBalance.value.uiAmount);
613
+ if (balance > 0 || includeZeroBalances) {
614
+ balances[token.symbol] = balance;
615
+ }
616
+ }
617
+ catch {
618
+ // Token account might not exist yet, set balance to 0
619
+ if (includeZeroBalances) {
620
+ balances[token.symbol] = 0;
621
+ }
622
+ }
623
+ }
624
+ catch (error) {
625
+ console.error(`Error getting balance for token ${token.symbol}:`, error);
626
+ if (includeZeroBalances) {
627
+ balances[token.symbol] = 0;
628
+ }
629
+ }
630
+ });
631
+ // Wait for current batch to complete before processing next batch
632
+ await Promise.all(batchPromises);
633
+ }
634
+ }
635
+ return includeTokenAccounts ? { balances, tokenAccounts } : { balances };
636
+ }
637
+ catch (error) {
638
+ throw new NordError_1.NordError("Failed to get Solana token balances", {
639
+ cause: error,
640
+ });
641
+ }
642
+ }
643
+ /**
644
+ * Get the Solana public key derived from the address
645
+ *
646
+ * @returns The Solana public key
647
+ */
648
+ getSolanaPublicKey() {
649
+ return this.address;
650
+ }
651
+ }
652
+ exports.NordUser = NordUser;
@@ -0,0 +1,7 @@
1
+ export { Nord } from "./client/Nord";
2
+ export { NordUser } from "./client/NordUser";
3
+ export { NordError } from "./utils/NordError";
4
+ export * from "./api/core";
5
+ export * from "./api/metrics";
6
+ export * from "./api/actions";
7
+ export * from "./models/Subscriber";
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.NordError = exports.NordUser = exports.Nord = void 0;
18
+ // Export main client classes
19
+ var Nord_1 = require("./client/Nord");
20
+ Object.defineProperty(exports, "Nord", { enumerable: true, get: function () { return Nord_1.Nord; } });
21
+ var NordUser_1 = require("./client/NordUser");
22
+ Object.defineProperty(exports, "NordUser", { enumerable: true, get: function () { return NordUser_1.NordUser; } });
23
+ // Export utility classes
24
+ var NordError_1 = require("./utils/NordError");
25
+ Object.defineProperty(exports, "NordError", { enumerable: true, get: function () { return NordError_1.NordError; } });
26
+ // Export API modules
27
+ __exportStar(require("./api/core"), exports);
28
+ __exportStar(require("./api/metrics"), exports);
29
+ __exportStar(require("./api/actions"), exports);
30
+ // Export models
31
+ __exportStar(require("./models/Subscriber"), exports);