@n1xyz/nord-ts 0.1.12 → 0.3.1

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.
@@ -0,0 +1,379 @@
1
+ import { Connection, PublicKey, Transaction, SendOptions } from "@solana/web3.js";
2
+ import Decimal from "decimal.js";
3
+ import { FillMode, Side, SPLTokenInfo, QuoteSize, TriggerKind } from "../../types";
4
+ import * as proto from "../../gen/nord_pb";
5
+ import { BigIntValue } from "../../utils";
6
+ import { Nord } from "./Nord";
7
+ /**
8
+ * Parameters for creating a NordUser instance
9
+ */
10
+ export interface NordUserParams {
11
+ /** Nord client instance */
12
+ nord: Nord;
13
+ /** User's blockchain address */
14
+ address: string;
15
+ /** Function to sign messages with the user's wallet */
16
+ walletSignFn: (x: Uint8Array) => Promise<Uint8Array>;
17
+ /** Function to sign messages with the user's session key */
18
+ sessionSignFn: (x: Uint8Array) => Promise<Uint8Array>;
19
+ /** Function to sign transactions with the user's wallet (optional) */
20
+ transactionSignFn: <T extends Transaction>(tx: T) => Promise<T>;
21
+ /** Solana connection (optional) */
22
+ connection?: Connection;
23
+ /** Session ID (optional) */
24
+ sessionId?: bigint;
25
+ /** Session public key (required) */
26
+ sessionPubKey: Uint8Array;
27
+ /** Session public key (required) */
28
+ publicKey: PublicKey;
29
+ }
30
+ /**
31
+ * Parameters for transferring tokens between accounts
32
+ */
33
+ export interface TransferParams {
34
+ /** Recipient user */
35
+ to: NordUser;
36
+ /** Token ID to transfer */
37
+ tokenId: number;
38
+ /** Amount to transfer */
39
+ amount: Decimal.Value;
40
+ /** Source account ID */
41
+ fromAccountId: number;
42
+ /** Destination account ID */
43
+ toAccountId: number;
44
+ }
45
+ /**
46
+ * Parameters for individual atomic subactions (user-friendly version)
47
+ */
48
+ export interface UserAtomicSubaction {
49
+ /** The type of action to perform. */
50
+ kind: "place" | "cancel";
51
+ /** The market ID to place the order in. */
52
+ marketId?: number;
53
+ /** The order ID to cancel. */
54
+ orderId?: BigIntValue;
55
+ /** Order side (bid or ask) */
56
+ side?: Side;
57
+ /** Fill mode (limit, market, etc.) */
58
+ fillMode?: FillMode;
59
+ /** Whether the order is reduce-only. */
60
+ isReduceOnly?: boolean;
61
+ /** The size of the order. */
62
+ size?: Decimal.Value;
63
+ /** Order price */
64
+ price?: Decimal.Value;
65
+ /** Quote size object (for market-style placement) */
66
+ quoteSize?: QuoteSize;
67
+ /** The client order ID of the order. */
68
+ clientOrderId?: BigIntValue;
69
+ }
70
+ /**
71
+ * User class for interacting with the Nord protocol
72
+ */
73
+ export declare class NordUser {
74
+ private readonly nord;
75
+ private readonly address;
76
+ private readonly walletSignFn;
77
+ private readonly sessionSignFn;
78
+ private readonly transactionSignFn;
79
+ private connection;
80
+ private sessionId?;
81
+ private sessionPubKey;
82
+ private publicKey;
83
+ private nonce;
84
+ /** User balances by token symbol */
85
+ balances: {
86
+ [key: string]: {
87
+ accountId: number;
88
+ balance: number;
89
+ symbol: string;
90
+ }[];
91
+ };
92
+ /** User positions by account ID */
93
+ positions: {
94
+ [key: string]: {
95
+ marketId: number;
96
+ openOrders: number;
97
+ perp?: {
98
+ baseSize: number;
99
+ price: number;
100
+ updatedFundingRateIndex: number;
101
+ fundingPaymentPnl: number;
102
+ sizePricePnl: number;
103
+ isLong: boolean;
104
+ };
105
+ actionId: number;
106
+ }[];
107
+ };
108
+ /** User margins by account ID */
109
+ margins: {
110
+ [key: string]: {
111
+ omf: number;
112
+ mf: number;
113
+ imf: number;
114
+ cmf: number;
115
+ mmf: number;
116
+ pon: number;
117
+ pn: number;
118
+ bankruptcy: boolean;
119
+ };
120
+ };
121
+ /** User's account IDs */
122
+ accountIds?: number[];
123
+ /** SPL token information */
124
+ splTokenInfos: SPLTokenInfo[];
125
+ /**
126
+ * Create a new NordUser instance
127
+ *
128
+ * @param address - User's Solana address (base58)
129
+ * @param nord - Shared Nord client instance
130
+ * @param publicKey - Engine account key belonging to the user
131
+ * @param sessionPubKey - Delegated session key used for actions
132
+ * @param walletSignFn - Signs wallet-scoped messages (create/revoke session)
133
+ * @param sessionSignFn - Signs delegated actions
134
+ * @param transactionSignFn - Signs raw Solana transactions (deposits, SPL ops)
135
+ * @param connection - Optional Solana connection to reuse
136
+ * @param sessionId - Optional existing session identifier
137
+ * @throws {NordError} If required parameters are missing
138
+ */
139
+ constructor({ address, nord, publicKey, sessionPubKey, sessionSignFn, transactionSignFn, walletSignFn, connection, sessionId, }: NordUserParams);
140
+ /**
141
+ * Create a NordUser from a private key
142
+ *
143
+ * @param nord - Nord instance
144
+ * @param privateKey - Private key as string or Uint8Array
145
+ * @param connection - Solana connection (optional)
146
+ * @returns NordUser instance
147
+ * @throws {NordError} If the private key is invalid
148
+ */
149
+ static fromPrivateKey(nord: Nord, privateKey: string | Uint8Array, connection?: Connection): NordUser;
150
+ /**
151
+ * Get the associated token account for a token mint
152
+ *
153
+ * @param mint - Token mint address
154
+ * @returns Associated token account address
155
+ * @throws {NordError} If required parameters are missing or operation fails
156
+ */
157
+ getAssociatedTokenAccount(mint: PublicKey): Promise<PublicKey>;
158
+ /**
159
+ * Deposit SPL tokens to the app
160
+ *
161
+ * @param amount - Amount to deposit
162
+ * @param tokenId - Token ID
163
+ * @param recipient - Recipient address; defaults to the user's address
164
+ * @returns Transaction signature
165
+ * @deprecated Use deposit instead
166
+ * @throws {NordError} If required parameters are missing or operation fails
167
+ */
168
+ depositSpl(amount: number, tokenId: number, recipient?: PublicKey): Promise<string>;
169
+ /**
170
+ * Deposit SPL tokens to the app
171
+ *
172
+ * @param amount - Amount to deposit
173
+ * @param tokenId - Token ID
174
+ * @param recipient - Recipient address; defaults to the user's address
175
+ * @param sendOptions - Send options for .sendTransaction
176
+ * @returns Transaction signature
177
+ * @throws {NordError} If required parameters are missing or operation fails
178
+ */
179
+ deposit({ amount, tokenId, recipient, sendOptions, }: Readonly<{
180
+ amount: number;
181
+ tokenId: number;
182
+ recipient?: PublicKey;
183
+ sendOptions?: SendOptions;
184
+ }>): Promise<string>;
185
+ /**
186
+ * Get a new nonce for actions
187
+ *
188
+ * @returns Nonce as number
189
+ */
190
+ getNonce(): number;
191
+ private submitSessionAction;
192
+ /**
193
+ * Update account IDs for this user
194
+ *
195
+ * @throws {NordError} If the operation fails
196
+ */
197
+ updateAccountId(): Promise<void>;
198
+ /**
199
+ * Fetch user information including balances and orders
200
+ *
201
+ * @throws {NordError} If the operation fails
202
+ */
203
+ fetchInfo(): Promise<void>;
204
+ /**
205
+ * Refresh the user's session
206
+ *
207
+ * @throws {NordError} If the operation fails
208
+ */
209
+ refreshSession(): Promise<void>;
210
+ /**
211
+ * Revoke a session
212
+ *
213
+ * @param sessionId - Session ID to revoke
214
+ * @throws {NordError} If the operation fails
215
+ */
216
+ revokeSession(sessionId: BigIntValue): Promise<void>;
217
+ /**
218
+ * Checks if the session is valid
219
+ * @private
220
+ * @throws {NordError} If the session is not valid
221
+ */
222
+ private checkSessionValidity;
223
+ /**
224
+ * Withdraw tokens from the exchange
225
+ *
226
+ * @param tokenId - Token ID to withdraw
227
+ * @param amount - Amount to withdraw
228
+ * @throws {NordError} If the operation fails
229
+ */
230
+ withdraw({ amount, tokenId, }: Readonly<{
231
+ tokenId: number;
232
+ amount: number;
233
+ }>): Promise<{
234
+ actionId: bigint;
235
+ }>;
236
+ /**
237
+ * Place an order on the exchange
238
+ *
239
+ * @param marketId - Market in which to place the order
240
+ * @param side - Bid or ask side
241
+ * @param fillMode - Limit/PO/IOC/FOK fill mode
242
+ * @param isReduceOnly - Whether the order can only reduce position
243
+ * @param size - Optional base size (Decimal)
244
+ * @param price - Optional limit price (Decimal)
245
+ * @param quoteSize - Optional quote-size helper for market orders
246
+ * @param accountId - Optional account identifier to debit
247
+ * @param clientOrderId - Optional client tracking id
248
+ * @returns Object containing actionId, orderId (if posted), fills, and clientOrderId
249
+ * @throws {NordError} If the operation fails
250
+ */
251
+ placeOrder(params: Readonly<{
252
+ marketId: number;
253
+ side: Side;
254
+ fillMode: FillMode;
255
+ isReduceOnly: boolean;
256
+ size?: Decimal.Value;
257
+ price?: Decimal.Value;
258
+ quoteSize?: QuoteSize;
259
+ accountId?: number;
260
+ clientOrderId?: BigIntValue;
261
+ }>): Promise<{
262
+ actionId: bigint;
263
+ orderId?: bigint;
264
+ fills: proto.Receipt_Trade[];
265
+ }>;
266
+ /**
267
+ * Cancel an order
268
+ *
269
+ * @param orderId - Order ID to cancel
270
+ * @param providedAccountId - Account ID that placed the order
271
+ * @returns Object containing actionId, cancelled orderId, and accountId
272
+ * @throws {NordError} If the operation fails
273
+ */
274
+ cancelOrder(orderId: BigIntValue, providedAccountId?: number): Promise<{
275
+ actionId: bigint;
276
+ orderId: bigint;
277
+ accountId: number;
278
+ }>;
279
+ /**
280
+ * Add a trigger for the current session
281
+ *
282
+ * @param marketId - Target market identifier
283
+ * @param side - Bid/ask direction the trigger will execute
284
+ * @param kind - Stop-loss or take-profit trigger kind
285
+ * @param triggerPrice - Price that arms the trigger (Decimal)
286
+ * @param limitPrice - Optional limit price used once armed
287
+ * @param accountId - Account identifier to use
288
+ * @returns Object containing the actionId of the submitted trigger
289
+ * @throws {NordError} If the operation fails
290
+ */
291
+ addTrigger(params: Readonly<{
292
+ marketId: number;
293
+ side: Side;
294
+ kind: TriggerKind;
295
+ triggerPrice: Decimal.Value;
296
+ limitPrice?: Decimal.Value;
297
+ accountId: number;
298
+ }>): Promise<{
299
+ actionId: bigint;
300
+ }>;
301
+ /**
302
+ * Remove a trigger for the current session
303
+ *
304
+ * @param marketId - Target market
305
+ * @param side - Bid/ask side of the trigger
306
+ * @param kind - Trigger kind to remove
307
+ * @param accountId - Optional account identifier to scope removal
308
+ * @returns Object containing the actionId of the removal action
309
+ * @throws {NordError} If the operation fails
310
+ */
311
+ removeTrigger(params: Readonly<{
312
+ marketId: number;
313
+ side: Side;
314
+ kind: TriggerKind;
315
+ accountId?: number;
316
+ }>): Promise<{
317
+ actionId: bigint;
318
+ }>;
319
+ /**
320
+ * Transfer tokens to another account
321
+ *
322
+ * @param to - Recipient NordUser
323
+ * @param tokenId - Token identifier to transfer
324
+ * @param amount - Amount to transfer (Decimal)
325
+ * @param fromAccountId - Account id debited
326
+ * @param toAccountId - Account id credited
327
+ * @throws {NordError} If the operation fails
328
+ */
329
+ transferToAccount(params: TransferParams): Promise<void>;
330
+ /**
331
+ * Execute up to four place/cancel operations atomically.
332
+ * Per Market:
333
+ * 1. cancels can only be in the start (one cannot predict future order ids)
334
+ * 2. intermediate trades can trade only
335
+ * 3. placements go last
336
+ *
337
+ * Across Markets, order action can be any
338
+ *
339
+ * @param userActions array of user-friendly subactions
340
+ * @param providedAccountId optional account performing the action (defaults to first account)
341
+ */
342
+ atomic(userActions: UserAtomicSubaction[], providedAccountId?: number): Promise<{
343
+ actionId: bigint;
344
+ results: proto.Receipt_AtomicSubactionResultKind[];
345
+ }>;
346
+ /**
347
+ * Helper function to retry a promise with exponential backoff
348
+ *
349
+ * @param fn - Function to retry
350
+ * @param maxRetries - Maximum number of retries
351
+ * @param initialDelay - Initial delay in milliseconds
352
+ * @returns Promise result
353
+ */
354
+ private retryWithBackoff;
355
+ /**
356
+ * Get user's token balances on Solana chain using mintAddr
357
+ *
358
+ * @param options - Optional parameters
359
+ * @param options.includeZeroBalances - Whether to include tokens with zero balance (default: true)
360
+ * @param options.includeTokenAccounts - Whether to include token account addresses in the result (default: false)
361
+ * @param options.maxConcurrent - Maximum number of concurrent requests (default: 5)
362
+ * @param options.maxRetries - Maximum number of retries for rate-limited requests (default: 3)
363
+ * @returns Object with token balances and optional token account addresses
364
+ * @throws {NordError} If required parameters are missing or operation fails
365
+ */
366
+ getSolanaBalances(options?: {
367
+ includeZeroBalances?: boolean;
368
+ includeTokenAccounts?: boolean;
369
+ maxConcurrent?: number;
370
+ maxRetries?: number;
371
+ }): Promise<{
372
+ balances: {
373
+ [symbol: string]: number;
374
+ };
375
+ tokenAccounts?: {
376
+ [symbol: string]: string;
377
+ };
378
+ }>;
379
+ }