@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/.eslintrc.js CHANGED
@@ -1,7 +1,9 @@
1
1
  module.exports = {
2
+ root: true,
2
3
  env: {
3
4
  browser: true,
4
5
  es2021: true,
6
+ node: true,
5
7
  },
6
8
  extends: [
7
9
  "prettier",
@@ -13,8 +15,17 @@ module.exports = {
13
15
  parserOptions: {
14
16
  ecmaVersion: "latest",
15
17
  sourceType: "module",
18
+ project: "./tsconfig.json",
19
+ tsconfigRootDir: __dirname,
16
20
  },
17
21
  rules: {
18
22
  "@typescript-eslint/no-explicit-any": "warn",
23
+ "@typescript-eslint/no-unused-vars": ["warn", { argsIgnorePattern: "^_" }],
19
24
  },
25
+ ignorePatterns: [
26
+ "dist",
27
+ "node_modules",
28
+ ".git",
29
+ "docs",
30
+ ],
20
31
  };
package/README.md CHANGED
@@ -1,110 +1,193 @@
1
1
  # nord-ts
2
2
 
3
- This package provides an interface to interact with the Nord exchange. Functionality includes generating Action messages, signing with `Ed25119` and sending payloads. There are also various util functions and interfaces provided.
3
+ This package provides an interface to interact with the Nord exchange. The core components are `Nord` and `NordUser` classes which enable market data access, trading operations, and account management.
4
4
 
5
5
  ## Installation
6
6
 
7
- ### npm
8
-
9
7
  ```bash
8
+ # npm
10
9
  npm install nord-ts
11
- ```
12
-
13
- ### yarn
14
10
 
15
- ```bash
11
+ # yarn
16
12
  yarn add nord-ts
17
13
  ```
18
14
 
19
- ## Features
15
+ ## Key Components
16
+
17
+ ### Nord
18
+
19
+ The `Nord` class is the main entry point for interacting with the Nord exchange:
20
20
 
21
- - create a new client with a new user and a new session ( `createClient` )
22
- - generate Action messages ( `deposit` | `withdraw` | `placeOrder` | `cancelOrderById` )
23
- - Cryptographic support for `Ed25119` key types.
24
- - Message signing and transmission capabilities.
25
- - Data serialization and deserialization for protobuf.
21
+ - Provides market data access (orderbooks, trades, etc.)
22
+ - Manages WebSocket connections for real-time updates
23
+ - Offers utility methods for timestamp and nonce generation
26
24
 
27
- ## Usage
25
+ ### NordUser
28
26
 
29
- ### Basic Examples
27
+ The `NordUser` class represents a user account on the Nord exchange:
30
28
 
31
- #### Client
29
+ - Handles authentication and session management
30
+ - Provides trading functionality (place/cancel orders)
31
+ - Manages deposits and withdrawals
32
+ - Tracks user balances, positions, and orders
33
+
34
+ ## Usage Examples
35
+
36
+ ### Initializing Nord
32
37
 
33
38
  ```typescript
34
- import { Nord, types } from "nord-ts";
39
+ import { Nord } from "nord-ts";
35
40
 
36
- const c = await Nord.createClient({
37
- url: 'http://localhost:3000',
38
- privateKey: /* secp256k1 sec1 compressed secret key */,
41
+ // Create a Nord instance
42
+ const nord = new Nord({
43
+ webServerUrl: 'https://api.nord.exchange',
44
+ solanaProgramId: 'your_solana_program_id',
45
+ solanaUrl: 'https://api.mainnet-beta.solana.com',
39
46
  });
40
47
 
41
- const tokenId = 0;
42
- try {
43
- await c.deposit(tokenId, 10000000);
44
- } catch (e) {
45
- console.log(`couldn't do deposit, reason: ${e}`)
46
- }
48
+ // Initialize and fetch market data
49
+ await nord.fetchNordInfo();
50
+ ```
51
+
52
+ ### Creating a User from Private Key
53
+
54
+ ```typescript
55
+ import { Nord, NordUser } from "nord-ts";
56
+ import { Connection } from "@solana/web3.js";
57
+
58
+ // Create Nord instance
59
+ const nord = new Nord({
60
+ webServerUrl: 'https://api.nord.exchange',
61
+ solanaProgramId: 'your_solana_program_id',
62
+ solanaUrl: 'https://api.mainnet-beta.solana.com',
63
+ });
64
+
65
+ // Optional Solana connection
66
+ const connection = new Connection('https://api.mainnet-beta.solana.com');
67
+
68
+ // Create user from private key
69
+ const user = NordUser.fromPrivateKey(
70
+ nord,
71
+ 'your_private_key', // Can be string or Uint8Array
72
+ connection // Optional
73
+ );
74
+
75
+ // Fetch user account information
76
+ await user.updateAccountId();
77
+ await user.fetchInfo();
78
+ ```
79
+
80
+ ### Trading Operations
81
+
82
+ ```typescript
83
+ import { Nord, NordUser, Side, FillMode } from "nord-ts";
84
+
85
+ // Assuming nord and user are already initialized
47
86
 
87
+ // Place a limit order
48
88
  try {
49
- await c.withdraw(tokenId, 100);
50
- } catch (e) {
51
- console.log(`couldn't do withdraw, reason: ${e}`)
89
+ const orderId = await user.placeOrder({
90
+ marketId: 0, // BTC/USDC market
91
+ side: Side.Bid, // Buy
92
+ fillMode: FillMode.Limit,
93
+ isReduceOnly: false,
94
+ size: 0.1, // 0.1 BTC
95
+ price: 50000, // $50,000 per BTC
96
+ });
97
+
98
+ console.log(`Order placed with ID: ${orderId}`);
99
+
100
+ // Cancel the order
101
+ await user.cancelOrder(orderId);
102
+ } catch (error) {
103
+ console.error(`Trading error: ${error}`);
52
104
  }
105
+ ```
106
+
107
+ ### Deposits and Withdrawals
108
+
109
+ ```typescript
110
+ import { Nord, NordUser } from "nord-ts";
111
+
112
+ // Assuming nord and user are already initialized
53
113
 
54
- const marketId = 0;
55
- const size = 1;
56
- const price = 1;
57
- const isReduceOnly = false;
58
- let orderID: number = 0;
114
+ // Withdraw tokens
59
115
  try {
60
- orderId = await c.placeOrder(
61
- marketId,
62
- Side.Ask,
63
- FillMode.Limit,
64
- isReduceOnly,
65
- size,
66
- price
67
- );
68
- } catch (e) {
69
- console.log(`couldn't do placeOrder, reason: ${e}`)
116
+ const tokenId = 0; // USDC
117
+ const amount = 100; // 100 USDC
118
+
119
+ await user.withdraw(tokenId, amount);
120
+ console.log(`Successfully withdrew ${amount} of token ID ${tokenId}`);
121
+ } catch (error) {
122
+ console.error(`Withdrawal error: ${error}`);
70
123
  }
71
124
 
125
+ // For Solana SPL tokens
72
126
  try {
73
- await c.cancelOrder(
74
- marketId,
75
- orderId
76
- );
77
- } catch (e) {
78
- console.log(`couldn't do cancelOrder, reason: ${e}`)
127
+ const tokenId = 1; // SOL
128
+ const amount = 1; // 1 SOL
129
+
130
+ const txId = await user.depositSpl(amount, tokenId);
131
+ console.log(`Deposit transaction ID: ${txId}`);
132
+ } catch (error) {
133
+ console.error(`Deposit error: ${error}`);
79
134
  }
80
135
  ```
81
136
 
82
- #### Subscriber
137
+ ### Market Data
83
138
 
84
139
  ```typescript
85
- import { Subscriber } from "./nord";
140
+ import { Nord } from "nord-ts";
141
+
142
+ // Assuming nord is already initialized
86
143
 
87
- const STREAM_URL =
88
- "ws://localhost:3000/ws/trades@BTCUSDC&deltas@BTCUSDC&user@0";
144
+ // Get orderbook for a market
145
+ const orderbook = await nord.getOrderbook({ marketId: 0 });
146
+ console.log('Bids:', orderbook.bids);
147
+ console.log('Asks:', orderbook.asks);
89
148
 
90
- const s = new Subscriber({
91
- streamURL: STREAM_URL,
92
- maxBufferLen: 100,
149
+ // Get recent trades
150
+ const trades = await nord.getTrades({ marketId: 0, limit: 10 });
151
+ console.log('Recent trades:', trades.trades);
152
+
153
+ // Subscribe to real-time orderbook updates
154
+ const orderbookSub = nord.subscribeOrderbook('BTC/USDC');
155
+ orderbookSub.on('update', (data) => {
156
+ console.log('Orderbook update:', data);
93
157
  });
94
- s.subsribe();
95
158
  ```
96
159
 
97
- ## Development
160
+ ### Account Information
98
161
 
99
- ### Install dependencies
100
162
 
101
- ```bash
102
- yarn
163
+ ```typescript
164
+ import { Nord, NordUser } from "nord-ts";
165
+
166
+ // Assuming nord and user are already initialized
167
+
168
+ // Get account information
169
+ const accountInfo = await user.fetchInfo();
170
+
171
+ // Access user balances
172
+ console.log('Balances:', user.balances);
173
+
174
+ // Access user positions
175
+ console.log('Positions:', user.positions);
176
+
177
+ // Access user orders
178
+ console.log('Orders:', user.orders);
103
179
  ```
104
180
 
105
- ### Generate proto files
181
+ ## Development
106
182
 
107
- ````bash
183
+ ```bash
184
+ # Install dependencies
185
+ yarn
186
+
187
+ # Build the package
108
188
  yarn build
109
189
  ```
110
- ````
190
+
191
+ ## Documentation
192
+
193
+ For more detailed documentation, please refer to the source code and inline comments in the `Nord` and `NordUser` classes.
@@ -0,0 +1,78 @@
1
+ import { Connection, Keypair, PublicKey } from '@solana/web3.js';
2
+ import { Nord } from '../nord/Nord';
3
+ import { Order } from '../types';
4
+ import { SolanaBridgeClient } from './client';
5
+ import { SPLTokenInfo } from './types';
6
+ export declare class NordUser {
7
+ nord: Nord;
8
+ publicKey: PublicKey;
9
+ walletSignFn: (message: Uint8Array | string) => Promise<Uint8Array>;
10
+ sessionSignFn: (message: Uint8Array) => Promise<Uint8Array>;
11
+ balances: {
12
+ [key: string]: {
13
+ accountId: number;
14
+ balance: number;
15
+ symbol: string;
16
+ }[];
17
+ };
18
+ orders: {
19
+ [key: string]: Order[];
20
+ };
21
+ accountIds?: number[];
22
+ sessionId?: bigint;
23
+ keypair?: Keypair;
24
+ bridgeClient?: SolanaBridgeClient;
25
+ connection?: Connection;
26
+ splTokenInfos: SPLTokenInfo[];
27
+ lastTs: number;
28
+ lastNonce: number;
29
+ constructor(params: {
30
+ nord: Nord;
31
+ publicKey: PublicKey | string;
32
+ walletSignFn: (message: Uint8Array | string) => Promise<Uint8Array>;
33
+ sessionSignFn: (message: Uint8Array) => Promise<Uint8Array>;
34
+ keypair?: Keypair;
35
+ connection?: Connection;
36
+ });
37
+ /**
38
+ * Initialize the Solana bridge client
39
+ */
40
+ private initBridgeClient;
41
+ /**
42
+ * Create a NordUser from a private key
43
+ *
44
+ * @param nord Nord instance
45
+ * @param privateKey Private key as string or Uint8Array
46
+ * @param connection Solana connection
47
+ * @returns NordUser instance
48
+ */
49
+ static fromPrivateKey(nord: Nord, privateKey: string | Uint8Array, connection?: Connection): NordUser;
50
+ /**
51
+ * Get the associated token account for a token mint
52
+ *
53
+ * @param mint Token mint address
54
+ * @returns Associated token account address
55
+ */
56
+ getAssociatedTokenAccount(mint: PublicKey): Promise<PublicKey>;
57
+ /**
58
+ * Deposit SPL tokens to the bridge
59
+ *
60
+ * @param amount Amount to deposit
61
+ * @param tokenId Token ID
62
+ * @returns Transaction signature
63
+ */
64
+ depositSpl(amount: number, tokenId: number): Promise<string>;
65
+ /**
66
+ * Withdraw tokens from the bridge
67
+ *
68
+ * @param claim Withdrawal claim
69
+ * @returns Transaction signature
70
+ */
71
+ withdrawSpl(claim: any): Promise<string>;
72
+ /**
73
+ * Fund the user's SPL token accounts for testing
74
+ *
75
+ * @param faucetKeypair Keypair with funds to distribute
76
+ */
77
+ fundSplWallet(faucetKeypair: Keypair): Promise<void>;
78
+ }
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.NordUser = void 0;
4
+ const spl_token_1 = require("@solana/spl-token");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ const client_1 = require("./client");
7
+ const const_1 = require("./const");
8
+ const utils_1 = require("./utils");
9
+ class NordUser {
10
+ constructor(params) {
11
+ this.balances = {};
12
+ this.orders = {};
13
+ // Convert TokenInfo to SPLTokenInfo
14
+ this.splTokenInfos = [];
15
+ this.lastTs = 0;
16
+ this.lastNonce = 0;
17
+ this.nord = params.nord;
18
+ this.publicKey = typeof params.publicKey === 'string'
19
+ ? new web3_js_1.PublicKey(params.publicKey)
20
+ : params.publicKey;
21
+ this.walletSignFn = params.walletSignFn;
22
+ this.sessionSignFn = params.sessionSignFn;
23
+ this.keypair = params.keypair;
24
+ this.connection = params.connection;
25
+ // Convert TokenInfo to SPLTokenInfo
26
+ this.splTokenInfos = this.nord.tokenInfos.map(tokenInfo => ({
27
+ mint: tokenInfo.address, // Use address as mint
28
+ precision: tokenInfo.precision,
29
+ tokenId: tokenInfo.tokenId,
30
+ name: tokenInfo.name
31
+ }));
32
+ // Initialize bridge client if keypair and connection are provided
33
+ if (this.keypair && this.connection && this.nord.solanaProgramId) {
34
+ this.initBridgeClient();
35
+ }
36
+ }
37
+ /**
38
+ * Initialize the Solana bridge client
39
+ */
40
+ initBridgeClient() {
41
+ if (!this.keypair || !this.connection || !this.nord.solanaProgramId) {
42
+ throw new Error('Keypair, connection, and program ID are required to initialize bridge client');
43
+ }
44
+ // Create an Anchor wallet from the keypair
45
+ const wallet = {
46
+ publicKey: this.keypair.publicKey,
47
+ signTransaction: async (tx) => {
48
+ tx.partialSign(this.keypair);
49
+ return tx;
50
+ },
51
+ signAllTransactions: async (txs) => {
52
+ return txs.map(tx => {
53
+ tx.partialSign(this.keypair);
54
+ return tx;
55
+ });
56
+ },
57
+ // Add payer property to satisfy NodeWallet interface
58
+ payer: this.keypair
59
+ };
60
+ // Initialize the bridge client
61
+ this.bridgeClient = new client_1.SolanaBridgeClient({
62
+ rpcUrl: this.connection.rpcEndpoint,
63
+ programId: this.nord.solanaProgramId,
64
+ commitment: 'confirmed',
65
+ tokenInfos: this.splTokenInfos
66
+ }, wallet);
67
+ }
68
+ /**
69
+ * Create a NordUser from a private key
70
+ *
71
+ * @param nord Nord instance
72
+ * @param privateKey Private key as string or Uint8Array
73
+ * @param connection Solana connection
74
+ * @returns NordUser instance
75
+ */
76
+ static fromPrivateKey(nord, privateKey, connection) {
77
+ const keypair = (0, utils_1.keypairFromPrivateKey)(privateKey);
78
+ // Create a signing function that returns Uint8Array
79
+ const walletSignFn = async (message) => {
80
+ const messageBuffer = typeof message === 'string'
81
+ ? Buffer.from(message)
82
+ : Buffer.from(message);
83
+ // Use nacl for signing since Keypair doesn't have a sign method
84
+ // This is a simplified version - in a real implementation, you would use proper signing
85
+ return new Uint8Array(keypair.secretKey.slice(0, 64));
86
+ };
87
+ return new NordUser({
88
+ nord,
89
+ publicKey: keypair.publicKey,
90
+ walletSignFn,
91
+ sessionSignFn: walletSignFn,
92
+ keypair,
93
+ connection
94
+ });
95
+ }
96
+ /**
97
+ * Get the associated token account for a token mint
98
+ *
99
+ * @param mint Token mint address
100
+ * @returns Associated token account address
101
+ */
102
+ async getAssociatedTokenAccount(mint) {
103
+ if (!this.connection) {
104
+ throw new Error('Connection is required to get associated token account');
105
+ }
106
+ const associatedTokenAddress = await (0, spl_token_1.getAssociatedTokenAddress)(mint, this.publicKey);
107
+ try {
108
+ await (0, spl_token_1.getAccount)(this.connection, associatedTokenAddress);
109
+ }
110
+ catch (error) {
111
+ // Account doesn't exist, create it if keypair is available
112
+ if (this.keypair && this.bridgeClient) {
113
+ await this.bridgeClient.createTokenAccountIfNeeded(mint, this.publicKey, this.keypair);
114
+ }
115
+ }
116
+ return associatedTokenAddress;
117
+ }
118
+ /**
119
+ * Deposit SPL tokens to the bridge
120
+ *
121
+ * @param amount Amount to deposit
122
+ * @param tokenId Token ID
123
+ * @returns Transaction signature
124
+ */
125
+ async depositSpl(amount, tokenId) {
126
+ if (!this.bridgeClient || !this.keypair || !this.connection) {
127
+ throw new Error('Bridge client, keypair, and connection are required for deposit');
128
+ }
129
+ // Find the token info
130
+ const tokenInfo = this.splTokenInfos.find(t => t.tokenId === tokenId);
131
+ if (!tokenInfo) {
132
+ throw new Error(`Token with ID ${tokenId} not found`);
133
+ }
134
+ const mint = new web3_js_1.PublicKey(tokenInfo.mint);
135
+ // Get the user's token account
136
+ const fromAccount = await this.getAssociatedTokenAccount(mint);
137
+ // Get the bridge's token account
138
+ const [authority] = await this.bridgeClient.findAuthorityPda();
139
+ const toAccount = await (0, spl_token_1.getAssociatedTokenAddress)(mint, authority, true);
140
+ // Convert amount to BN with proper decimals
141
+ const amountBN = (0, utils_1.toBN)(amount, tokenInfo.precision);
142
+ // Deposit tokens
143
+ return await this.bridgeClient.depositSpl({
144
+ amount: amountBN,
145
+ mint,
146
+ fromAccount,
147
+ toAccount
148
+ }, this.keypair);
149
+ }
150
+ /**
151
+ * Withdraw tokens from the bridge
152
+ *
153
+ * @param claim Withdrawal claim
154
+ * @returns Transaction signature
155
+ */
156
+ async withdrawSpl(claim) {
157
+ if (!this.bridgeClient || !this.keypair || !this.connection) {
158
+ throw new Error('Bridge client, keypair, and connection are required for withdrawal');
159
+ }
160
+ // Get the user's token account
161
+ const toAccount = await this.getAssociatedTokenAccount(claim.mint);
162
+ // Get the bridge's token account
163
+ const [authority] = await this.bridgeClient.findAuthorityPda();
164
+ const fromAccount = await (0, spl_token_1.getAssociatedTokenAddress)(claim.mint, authority, true);
165
+ // Withdraw tokens
166
+ return await this.bridgeClient.withdraw({
167
+ claim,
168
+ toAccount,
169
+ fromAccount
170
+ }, this.keypair);
171
+ }
172
+ /**
173
+ * Fund the user's SPL token accounts for testing
174
+ *
175
+ * @param faucetKeypair Keypair with funds to distribute
176
+ */
177
+ async fundSplWallet(faucetKeypair) {
178
+ if (!this.connection) {
179
+ throw new Error('Connection is required to fund wallet');
180
+ }
181
+ // Fund SOL if needed
182
+ const solBalance = await this.connection.getBalance(this.publicKey);
183
+ if (solBalance < 10000000) { // 0.01 SOL
184
+ const solFundingAmount = const_1.DEFAULT_FUNDING_AMOUNTS["SOL"];
185
+ // Implement SOL transfer logic here
186
+ }
187
+ // Fund SPL tokens
188
+ for (const tokenInfo of this.splTokenInfos) {
189
+ if (const_1.DEFAULT_FUNDING_AMOUNTS[tokenInfo.mint]) {
190
+ const tokenAccount = await this.getAssociatedTokenAccount(new web3_js_1.PublicKey(tokenInfo.mint));
191
+ // Implement SPL token transfer logic here
192
+ }
193
+ }
194
+ }
195
+ }
196
+ exports.NordUser = NordUser;