@n1xyz/nord-ts 0.0.4 → 0.0.7

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 (306) hide show
  1. package/dist/bridge/client.d.ts +4 -4
  2. package/dist/bridge/client.js +4 -4
  3. package/dist/bridge/const.d.ts +2 -2
  4. package/dist/bridge/const.js +22 -22
  5. package/dist/bridge/index.d.ts +4 -4
  6. package/dist/bridge/types.d.ts +3 -3
  7. package/dist/bridge/utils.d.ts +4 -4
  8. package/dist/bridge/utils.js +10 -10
  9. package/dist/const.d.ts +1 -1
  10. package/dist/const.js +17 -17
  11. package/dist/gen/nord.d.ts +1 -4
  12. package/dist/idl/bridge.d.ts +1 -1
  13. package/dist/idl/bridge.js +185 -185
  14. package/dist/index.d.ts +8 -8
  15. package/dist/nord/api/actions.d.ts +3 -3
  16. package/dist/nord/api/actions.js +21 -21
  17. package/dist/nord/api/core.d.ts +3 -3
  18. package/dist/nord/api/core.js +12 -12
  19. package/dist/nord/api/market.d.ts +1 -1
  20. package/dist/nord/api/market.js +12 -12
  21. package/dist/nord/api/metrics.d.ts +1 -1
  22. package/dist/nord/api/metrics.js +6 -6
  23. package/dist/nord/api/queries.d.ts +1 -1
  24. package/dist/nord/api/queries.js +9 -9
  25. package/dist/nord/client/Nord.d.ts +4 -4
  26. package/dist/nord/client/Nord.js +18 -18
  27. package/dist/nord/client/NordUser.d.ts +7 -7
  28. package/dist/nord/client/NordUser.js +45 -49
  29. package/dist/nord/index.d.ts +9 -9
  30. package/dist/nord/models/Subscriber.d.ts +6 -6
  31. package/dist/nord/models/Subscriber.js +1 -5
  32. package/dist/nord/utils/NordError.js +2 -2
  33. package/dist/types.d.ts +1 -1
  34. package/dist/types.js +1 -1
  35. package/dist/utils.d.ts +6 -6
  36. package/dist/utils.js +8 -8
  37. package/dist/websocket/NordWebSocketClient.d.ts +2 -2
  38. package/dist/websocket/NordWebSocketClient.js +38 -38
  39. package/dist/websocket/events.d.ts +1 -1
  40. package/dist/websocket/index.d.ts +2 -2
  41. package/docs/assets/hierarchy.js +1 -0
  42. package/docs/assets/highlight.css +16 -16
  43. package/docs/assets/icons.js +17 -14
  44. package/docs/assets/icons.svg +1 -1
  45. package/docs/assets/main.js +5 -4
  46. package/docs/assets/navigation.js +1 -1
  47. package/docs/assets/search.js +1 -1
  48. package/docs/assets/style.css +1423 -1227
  49. package/docs/classes/Nord.html +190 -31
  50. package/docs/classes/NordError.html +24 -0
  51. package/docs/classes/NordUser.html +120 -35
  52. package/docs/classes/NordWebSocketClient.html +335 -0
  53. package/docs/classes/SolanaBridgeClient.html +86 -0
  54. package/docs/classes/Subscriber.html +10 -0
  55. package/docs/enums/FillMode.html +5 -5
  56. package/docs/enums/KeyType.html +4 -4
  57. package/docs/enums/MetricPeriod.html +9 -0
  58. package/docs/enums/PdaSeedType.html +9 -0
  59. package/docs/enums/PeakTpsPeriodUnit.html +7 -7
  60. package/docs/enums/Side.html +3 -3
  61. package/docs/enums/WebSocketMessageType.html +7 -0
  62. package/docs/functions/actionQueryRollman.html +6 -0
  63. package/docs/functions/actionsQueryRollman.html +6 -0
  64. package/docs/functions/aggregateMetrics-1.html +7 -0
  65. package/docs/functions/assert.html +1 -1
  66. package/docs/functions/bigIntToProtoU128.html +3 -3
  67. package/docs/functions/blockQueryRollman.html +6 -0
  68. package/docs/functions/blockSummaryQueryRollman.html +6 -0
  69. package/docs/functions/bridgeToBN.html +5 -0
  70. package/docs/functions/bufferToHex.html +4 -0
  71. package/docs/functions/cancelOrder.html +1 -0
  72. package/docs/functions/checkPubKeyLength.html +1 -1
  73. package/docs/functions/checkedFetch.html +4 -4
  74. package/docs/functions/createSession.html +1 -0
  75. package/docs/functions/decodeLengthDelimited.html +7 -6
  76. package/docs/functions/encodeLengthDelimited.html +4 -4
  77. package/docs/functions/fillModeToProtoFillMode.html +4 -4
  78. package/docs/functions/findMarket.html +1 -1
  79. package/docs/functions/findPda.html +6 -0
  80. package/docs/functions/findToken.html +1 -1
  81. package/docs/functions/fromBN.html +5 -0
  82. package/docs/functions/getAccount.html +6 -0
  83. package/docs/functions/getActionNonce.html +5 -0
  84. package/docs/functions/getCurrentTps.html +6 -0
  85. package/docs/functions/getInfo.html +5 -0
  86. package/docs/functions/getMedianLatency.html +6 -0
  87. package/docs/functions/getOrderbook.html +6 -0
  88. package/docs/functions/getPeakTps.html +6 -0
  89. package/docs/functions/getTimestamp.html +5 -0
  90. package/docs/functions/getTotalTransactions.html +5 -0
  91. package/docs/functions/getTrades.html +6 -0
  92. package/docs/functions/getUserAccountIds.html +6 -0
  93. package/docs/functions/hexToBuffer.html +4 -0
  94. package/docs/functions/initWebSocketClient.html +12 -0
  95. package/docs/functions/keypairFromPrivateKey.html +4 -0
  96. package/docs/functions/makeSigningFunction.html +4 -0
  97. package/docs/functions/makeWalletSignFn.html +5 -5
  98. package/docs/functions/marketsStats.html +5 -0
  99. package/docs/functions/optExpect.html +4 -4
  100. package/docs/functions/optMap.html +5 -5
  101. package/docs/functions/optUnwrap.html +2 -2
  102. package/docs/functions/panic.html +1 -1
  103. package/docs/functions/placeOrder.html +1 -0
  104. package/docs/functions/queryAction.html +6 -0
  105. package/docs/functions/queryBlock.html +6 -0
  106. package/docs/functions/queryLastNBlocks.html +5 -0
  107. package/docs/functions/queryPrometheus.html +6 -0
  108. package/docs/functions/queryRecentActions.html +6 -0
  109. package/docs/functions/queryRecentBlocks.html +6 -0
  110. package/docs/functions/revokeSession.html +1 -0
  111. package/docs/functions/shortenPublicKey.html +5 -0
  112. package/docs/functions/signAction.html +2 -2
  113. package/docs/functions/toBN.html +5 -0
  114. package/docs/functions/toScaledU128.html +5 -5
  115. package/docs/functions/toScaledU64.html +5 -5
  116. package/docs/functions/transfer.html +1 -0
  117. package/docs/functions/withdraw.html +1 -0
  118. package/docs/hierarchy.html +1 -0
  119. package/docs/index.html +39 -20
  120. package/docs/interfaces/Account.html +8 -8
  121. package/docs/interfaces/ActionInfo.html +8 -8
  122. package/docs/interfaces/ActionNonceResponse.html +3 -0
  123. package/docs/interfaces/ActionQuery.html +4 -4
  124. package/docs/interfaces/ActionResponse.html +8 -8
  125. package/docs/interfaces/ActionsExtendedInfo.html +10 -10
  126. package/docs/interfaces/ActionsQuery.html +5 -5
  127. package/docs/interfaces/ActionsResponse.html +6 -6
  128. package/docs/interfaces/AggregateMetrics.html +12 -12
  129. package/docs/interfaces/BlockFacts.html +10 -0
  130. package/docs/interfaces/BlockQuery.html +6 -6
  131. package/docs/interfaces/BlockResponse.html +6 -6
  132. package/docs/interfaces/BlockSummary.html +8 -8
  133. package/docs/interfaces/BlockSummaryResponse.html +6 -6
  134. package/docs/interfaces/DeltaEvent.html +6 -6
  135. package/docs/interfaces/DepositSplParams.html +10 -0
  136. package/docs/interfaces/Info.html +3 -3
  137. package/docs/interfaces/Market.html +8 -6
  138. package/docs/interfaces/MarketStats.html +7 -7
  139. package/docs/interfaces/MarketsStatsResponse.html +2 -2
  140. package/docs/interfaces/NordConfig.html +14 -5
  141. package/docs/interfaces/NordWebSocketClientEvents.html +4 -0
  142. package/docs/interfaces/NordWebSocketEvents.html +8 -0
  143. package/docs/interfaces/Order.html +6 -6
  144. package/docs/interfaces/OrderInfo.html +6 -6
  145. package/docs/interfaces/OrderbookEntry.html +4 -0
  146. package/docs/interfaces/OrderbookQuery.html +6 -0
  147. package/docs/interfaces/OrderbookResponse.html +6 -0
  148. package/docs/interfaces/OrderbookSubscription.html +159 -0
  149. package/docs/interfaces/PerpMarketStats.html +5 -5
  150. package/docs/interfaces/RollmanActionExtendedInfo.html +4 -4
  151. package/docs/interfaces/RollmanActionInfo.html +4 -4
  152. package/docs/interfaces/RollmanActionResponse.html +4 -4
  153. package/docs/interfaces/RollmanActionsResponse.html +2 -2
  154. package/docs/interfaces/RollmanBlockResponse.html +3 -3
  155. package/docs/interfaces/SPLTokenInfo.html +10 -0
  156. package/docs/interfaces/SolanaBridgeConfig.html +10 -0
  157. package/docs/interfaces/StateFacts.html +10 -0
  158. package/docs/interfaces/SubscriberConfig.html +3 -3
  159. package/docs/interfaces/TimestampResponse.html +3 -0
  160. package/docs/interfaces/Token.html +5 -5
  161. package/docs/interfaces/TokenInfo.html +5 -0
  162. package/docs/interfaces/Trade.html +5 -5
  163. package/docs/interfaces/TradeSubscription.html +159 -0
  164. package/docs/interfaces/Trades.html +5 -5
  165. package/docs/interfaces/TradesQuery.html +6 -0
  166. package/docs/interfaces/TradesResponse.html +7 -0
  167. package/docs/interfaces/TransferParams.html +8 -0
  168. package/docs/interfaces/UserAccountIdsQuery.html +3 -0
  169. package/docs/interfaces/UserAccountIdsResponse.html +3 -0
  170. package/docs/interfaces/WebSocketDeltaUpdate.html +9 -0
  171. package/docs/interfaces/WebSocketSubscription.html +4 -0
  172. package/docs/interfaces/WebSocketTradeUpdate.html +6 -0
  173. package/docs/interfaces/WebSocketUserUpdate.html +6 -0
  174. package/docs/interfaces/WithdrawalClaim.html +14 -0
  175. package/docs/interfaces/WithdrawalParams.html +8 -0
  176. package/docs/modules.html +1 -70
  177. package/docs/types/BigIntValue.html +2 -2
  178. package/docs/types/WebSocketMessage.html +1 -0
  179. package/docs/variables/DEBUG_KEYS.html +1 -1
  180. package/docs/variables/DEFAULT_FUNDING_AMOUNTS.html +1 -1
  181. package/docs/variables/DEV_TOKEN_INFOS.html +1 -1
  182. package/docs/variables/DEV_URL.html +1 -1
  183. package/docs/variables/MAX_BUFFER_LEN.html +1 -1
  184. package/docs/variables/SESSION_TTL.html +1 -1
  185. package/docs/variables/WEBSERVER_DEV_URL.html +1 -1
  186. package/docs/variables/ZERO_DECIMAL.html +1 -1
  187. package/docs/variables/_private.html +2 -0
  188. package/eslint.config.mjs +66 -0
  189. package/package.json +12 -13
  190. package/src/bridge/client.ts +10 -10
  191. package/src/bridge/const.ts +24 -24
  192. package/src/bridge/index.ts +4 -4
  193. package/src/bridge/types.ts +10 -10
  194. package/src/bridge/utils.ts +14 -14
  195. package/src/const.ts +18 -18
  196. package/src/gen/nord.ts +1 -4
  197. package/src/idl/bridge.ts +186 -186
  198. package/src/index.ts +8 -8
  199. package/src/nord/api/actions.ts +25 -25
  200. package/src/nord/api/core.ts +16 -16
  201. package/src/nord/api/market.ts +15 -15
  202. package/src/nord/api/metrics.ts +129 -22
  203. package/src/nord/api/queries.ts +12 -12
  204. package/src/nord/client/Nord.ts +27 -27
  205. package/src/nord/client/NordUser.ts +59 -63
  206. package/src/nord/index.ts +9 -9
  207. package/src/nord/models/Subscriber.ts +11 -12
  208. package/src/nord/utils/NordError.ts +2 -2
  209. package/src/types.ts +12 -12
  210. package/src/utils.ts +20 -20
  211. package/src/websocket/NordWebSocketClient.ts +42 -42
  212. package/src/websocket/events.ts +1 -1
  213. package/src/websocket/index.ts +2 -2
  214. package/tests/utils.spec.ts +24 -24
  215. package/tsconfig.eslint.json +12 -0
  216. package/.eslintignore +0 -1
  217. package/.eslintrc.js +0 -31
  218. package/dist/abis/ERC20_ABI.d.ts +0 -39
  219. package/dist/abis/ERC20_ABI.js +0 -313
  220. package/dist/abis/NORD_GETTERS_FACET_ABI.d.ts +0 -34
  221. package/dist/abis/NORD_GETTERS_FACET_ABI.js +0 -195
  222. package/dist/abis/NORD_RAMP_FACET_ABI.d.ts +0 -35
  223. package/dist/abis/NORD_RAMP_FACET_ABI.js +0 -144
  224. package/dist/abis/index.d.ts +0 -3
  225. package/dist/abis/index.js +0 -9
  226. package/dist/bridge/NordUser.d.ts +0 -78
  227. package/dist/bridge/NordUser.js +0 -196
  228. package/dist/client.d.ts +0 -70
  229. package/dist/client.js +0 -129
  230. package/dist/constants/endpoints.d.ts +0 -65
  231. package/dist/constants/endpoints.js +0 -68
  232. package/dist/models/account.d.ts +0 -58
  233. package/dist/models/account.js +0 -6
  234. package/dist/models/index.d.ts +0 -8
  235. package/dist/models/index.js +0 -28
  236. package/dist/models/market.d.ts +0 -137
  237. package/dist/models/market.js +0 -6
  238. package/dist/models/order.d.ts +0 -211
  239. package/dist/models/order.js +0 -6
  240. package/dist/models/token.d.ts +0 -50
  241. package/dist/models/token.js +0 -6
  242. package/dist/nord/Nord.d.ts +0 -249
  243. package/dist/nord/Nord.js +0 -388
  244. package/dist/nord/NordError.d.ts +0 -23
  245. package/dist/nord/NordError.js +0 -48
  246. package/dist/nord/NordImpl.d.ts +0 -11
  247. package/dist/nord/NordImpl.js +0 -26
  248. package/dist/nord/NordUser.d.ts +0 -243
  249. package/dist/nord/NordUser.js +0 -481
  250. package/dist/nord/Subscriber.d.ts +0 -37
  251. package/dist/nord/Subscriber.js +0 -29
  252. package/dist/nord/actions.d.ts +0 -101
  253. package/dist/nord/actions.js +0 -254
  254. package/dist/nord/api/index.d.ts +0 -1
  255. package/dist/nord/api/index.js +0 -17
  256. package/dist/nord/api/orderFunctions.d.ts +0 -168
  257. package/dist/nord/api/orderFunctions.js +0 -133
  258. package/dist/nord/core.d.ts +0 -48
  259. package/dist/nord/core.js +0 -97
  260. package/dist/nord/market.d.ts +0 -36
  261. package/dist/nord/market.js +0 -90
  262. package/dist/nord/metrics.d.ts +0 -67
  263. package/dist/nord/metrics.js +0 -124
  264. package/dist/nord/queries.d.ts +0 -81
  265. package/dist/nord/queries.js +0 -181
  266. package/dist/nord/types.d.ts +0 -88
  267. package/dist/nord/types.js +0 -2
  268. package/dist/nord/websocket.d.ts +0 -49
  269. package/dist/nord/websocket.js +0 -107
  270. package/dist/operations/account.d.ts +0 -58
  271. package/dist/operations/account.js +0 -112
  272. package/dist/operations/market.d.ts +0 -65
  273. package/dist/operations/market.js +0 -131
  274. package/dist/operations/orders.d.ts +0 -57
  275. package/dist/operations/orders.js +0 -129
  276. package/dist/solana/NordUser.d.ts +0 -78
  277. package/dist/solana/NordUser.js +0 -196
  278. package/dist/solana/client.d.ts +0 -139
  279. package/dist/solana/client.js +0 -360
  280. package/dist/solana/const.d.ts +0 -23
  281. package/dist/solana/const.js +0 -47
  282. package/dist/solana/index.d.ts +0 -5
  283. package/dist/solana/index.js +0 -23
  284. package/dist/solana/types.d.ts +0 -118
  285. package/dist/solana/types.js +0 -16
  286. package/dist/solana/utils.d.ts +0 -64
  287. package/dist/solana/utils.js +0 -131
  288. package/dist/types/api.d.ts +0 -152
  289. package/dist/types/api.js +0 -6
  290. package/dist/types/config.d.ts +0 -34
  291. package/dist/types/config.js +0 -6
  292. package/dist/utils/errors.d.ts +0 -96
  293. package/dist/utils/errors.js +0 -132
  294. package/dist/utils/http.d.ts +0 -35
  295. package/dist/utils/http.js +0 -105
  296. package/dist/websocket/client.d.ts +0 -93
  297. package/dist/websocket/client.js +0 -222
  298. package/dist/websocket.d.ts +0 -55
  299. package/dist/websocket.js +0 -211
  300. package/docs/interfaces/ERC20TokenInfo.html +0 -5
  301. package/docs/variables/DEV_CONTRACT_ADDRESS.html +0 -1
  302. package/docs/variables/ERC20_ABI.html +0 -1
  303. package/docs/variables/EVM_DEV_URL.html +0 -1
  304. package/docs/variables/FAUCET_PRIVATE_ADDRESS.html +0 -1
  305. package/docs/variables/NORD_GETTERS_FACET_ABI.html +0 -1
  306. package/docs/variables/NORD_RAMP_FACET_ABI.html +0 -1
@@ -1,481 +0,0 @@
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 utils_1 = require("../utils");
7
- const actions_1 = require("./actions");
8
- const client_1 = require("../bridge/client");
9
- const utils_2 = require("../bridge/utils");
10
- const NordError_1 = require("./NordError");
11
- /**
12
- * User class for interacting with the Nord protocol
13
- */
14
- class NordUser {
15
- /**
16
- * Create a new NordUser instance
17
- *
18
- * @param params - Parameters for creating a NordUser
19
- * @throws {NordError} If required parameters are missing
20
- */
21
- constructor(params) {
22
- /** User balances by token symbol */
23
- this.balances = {};
24
- /** User orders by market symbol */
25
- this.orders = {};
26
- /** Last timestamp used */
27
- this.lastTs = 0;
28
- /** Last nonce used */
29
- this.lastNonce = 0;
30
- /** SPL token information */
31
- this.splTokenInfos = [];
32
- if (!params.nord) {
33
- throw new NordError_1.NordError("Nord instance is required");
34
- }
35
- if (!params.address) {
36
- throw new NordError_1.NordError("Address is required");
37
- }
38
- if (!params.walletSignFn) {
39
- throw new NordError_1.NordError("Wallet sign function is required");
40
- }
41
- if (!params.sessionSignFn) {
42
- throw new NordError_1.NordError("Session sign function is required");
43
- }
44
- this.nord = params.nord;
45
- this.address = params.address;
46
- this.walletSignFn = params.walletSignFn;
47
- this.sessionSignFn = params.sessionSignFn;
48
- // Initialize Solana-specific properties if provided
49
- if (params.solanaPublicKey) {
50
- this.solanaPublicKey = typeof params.solanaPublicKey === 'string'
51
- ? new web3_js_1.PublicKey(params.solanaPublicKey)
52
- : params.solanaPublicKey;
53
- }
54
- this.keypair = params.keypair;
55
- this.connection = params.connection;
56
- // Convert TokenInfo to SPLTokenInfo if nord has tokenInfos
57
- if (this.nord.tokenInfos) {
58
- this.splTokenInfos = this.nord.tokenInfos.map(tokenInfo => ({
59
- mint: tokenInfo.address, // Use address as mint
60
- precision: tokenInfo.precision,
61
- tokenId: tokenInfo.tokenId,
62
- name: tokenInfo.name
63
- }));
64
- }
65
- // Initialize bridge client if keypair and connection are provided
66
- if (this.keypair && this.connection && this.nord.solanaProgramId) {
67
- this.initBridgeClient();
68
- }
69
- }
70
- /**
71
- * Create a clone of this NordUser instance
72
- *
73
- * @returns A new NordUser instance with the same properties
74
- */
75
- clone() {
76
- const newUser = new NordUser({
77
- nord: this.nord,
78
- address: this.address,
79
- walletSignFn: this.walletSignFn,
80
- sessionSignFn: this.sessionSignFn,
81
- solanaPublicKey: this.solanaPublicKey,
82
- keypair: this.keypair,
83
- connection: this.connection
84
- });
85
- newUser.publicKey = this.publicKey;
86
- newUser.lastTs = this.lastTs;
87
- newUser.lastNonce = this.lastNonce;
88
- newUser.accountIds = this.accountIds ? [...this.accountIds] : undefined;
89
- newUser.sessionId = this.sessionId;
90
- newUser.splTokenInfos = [...this.splTokenInfos];
91
- // Deep clone balances and orders
92
- newUser.balances = JSON.parse(JSON.stringify(this.balances));
93
- newUser.orders = JSON.parse(JSON.stringify(this.orders));
94
- return newUser;
95
- }
96
- /**
97
- * Initialize the Solana bridge client
98
- *
99
- * @private
100
- * @throws {NordError} If required parameters are missing
101
- */
102
- initBridgeClient() {
103
- if (!this.keypair || !this.connection || !this.nord.solanaProgramId) {
104
- throw new NordError_1.NordError('Keypair, connection, and program ID are required to initialize bridge client');
105
- }
106
- // Create an Anchor wallet from the keypair
107
- const wallet = {
108
- publicKey: this.keypair.publicKey,
109
- signTransaction: async (tx) => {
110
- tx.partialSign(this.keypair);
111
- return tx;
112
- },
113
- signAllTransactions: async (txs) => {
114
- return txs.map(tx => {
115
- tx.partialSign(this.keypair);
116
- return tx;
117
- });
118
- },
119
- // Add payer property to satisfy NodeWallet interface
120
- payer: this.keypair
121
- };
122
- // Initialize the bridge client
123
- this.bridgeClient = new client_1.SolanaBridgeClient({
124
- rpcUrl: this.connection.rpcEndpoint,
125
- programId: this.nord.solanaProgramId,
126
- commitment: 'confirmed',
127
- tokenInfos: this.splTokenInfos
128
- }, wallet);
129
- }
130
- /**
131
- * Create a NordUser from a private key
132
- *
133
- * @param nord - Nord instance
134
- * @param privateKey - Private key as string or Uint8Array
135
- * @param connection - Solana connection (optional)
136
- * @returns NordUser instance
137
- * @throws {NordError} If the private key is invalid
138
- */
139
- static fromPrivateKey(nord, privateKey, connection) {
140
- try {
141
- const keypair = (0, utils_2.keypairFromPrivateKey)(privateKey);
142
- // Create a signing function that returns Uint8Array
143
- const walletSignFn = async (message) => {
144
- const messageBuffer = typeof message === 'string'
145
- ? Buffer.from(message)
146
- : Buffer.from(message);
147
- // Use nacl for signing since Keypair doesn't have a sign method
148
- // This is a simplified version - in a real implementation, you would use proper signing
149
- return Buffer.from(keypair.secretKey.slice(0, 64)).toString('hex');
150
- };
151
- const sessionSignFn = async (message) => {
152
- // This is a simplified version - in a real implementation, you would use proper signing
153
- return new Uint8Array(keypair.secretKey.slice(0, 64));
154
- };
155
- return new NordUser({
156
- nord,
157
- address: keypair.publicKey.toBase58(),
158
- walletSignFn,
159
- sessionSignFn,
160
- solanaPublicKey: keypair.publicKey,
161
- keypair,
162
- connection
163
- });
164
- }
165
- catch (error) {
166
- throw new NordError_1.NordError("Failed to create NordUser from private key", { cause: error });
167
- }
168
- }
169
- /**
170
- * Get the associated token account for a token mint
171
- *
172
- * @param mint - Token mint address
173
- * @returns Associated token account address
174
- * @throws {NordError} If required parameters are missing or operation fails
175
- */
176
- async getAssociatedTokenAccount(mint) {
177
- if (!this.connection || !this.solanaPublicKey) {
178
- throw new NordError_1.NordError('Connection and Solana public key are required to get associated token account');
179
- }
180
- try {
181
- const associatedTokenAddress = await (0, spl_token_1.getAssociatedTokenAddress)(mint, this.solanaPublicKey);
182
- try {
183
- await (0, spl_token_1.getAccount)(this.connection, associatedTokenAddress);
184
- }
185
- catch (error) {
186
- // Account doesn't exist, create it if keypair is available
187
- if (this.keypair && this.bridgeClient) {
188
- await this.bridgeClient.createTokenAccountIfNeeded(mint, this.solanaPublicKey, this.keypair);
189
- }
190
- }
191
- return associatedTokenAddress;
192
- }
193
- catch (error) {
194
- throw new NordError_1.NordError(`Failed to get associated token account for mint ${mint.toString()}`, { cause: error });
195
- }
196
- }
197
- /**
198
- * Deposit SPL tokens to the bridge
199
- *
200
- * @param amount - Amount to deposit
201
- * @param tokenId - Token ID
202
- * @returns Transaction signature
203
- * @throws {NordError} If required parameters are missing or operation fails
204
- */
205
- async depositSpl(amount, tokenId) {
206
- if (!this.bridgeClient || !this.keypair || !this.connection || !this.solanaPublicKey) {
207
- throw new NordError_1.NordError('Bridge client, keypair, connection, and Solana public key are required for deposit');
208
- }
209
- try {
210
- // Find the token info
211
- const tokenInfo = this.splTokenInfos.find(t => t.tokenId === tokenId);
212
- if (!tokenInfo) {
213
- throw new NordError_1.NordError(`Token with ID ${tokenId} not found`);
214
- }
215
- const mint = new web3_js_1.PublicKey(tokenInfo.mint);
216
- // Get the user's token account
217
- const fromAccount = await this.getAssociatedTokenAccount(mint);
218
- // Get the bridge's token account
219
- const [authority] = await this.bridgeClient.findAuthorityPda();
220
- const toAccount = await (0, spl_token_1.getAssociatedTokenAddress)(mint, authority, true);
221
- // Convert amount to BN with proper decimals
222
- const amountBN = (0, utils_1.toBN)(amount, tokenInfo.precision);
223
- // Deposit tokens
224
- return await this.bridgeClient.depositSpl({
225
- amount: amountBN,
226
- mint,
227
- fromAccount,
228
- toAccount
229
- }, this.keypair);
230
- }
231
- catch (error) {
232
- throw new NordError_1.NordError(`Failed to deposit ${amount} of token ID ${tokenId}`, { cause: error });
233
- }
234
- }
235
- /**
236
- * Withdraw SPL tokens from the bridge
237
- *
238
- * @param claim - Claim data
239
- * @returns Transaction signature
240
- * @throws {NordError} If required parameters are missing or operation fails
241
- */
242
- async withdrawSpl(claim) {
243
- if (!this.bridgeClient || !this.keypair || !this.connection || !this.solanaPublicKey) {
244
- throw new NordError_1.NordError('Bridge client, keypair, connection, and Solana public key are required for withdrawal');
245
- }
246
- try {
247
- // Find the token info
248
- const tokenInfo = this.splTokenInfos.find(t => t.tokenId === claim.tokenId);
249
- if (!tokenInfo) {
250
- throw new NordError_1.NordError(`Token with ID ${claim.tokenId} not found`);
251
- }
252
- const mint = new web3_js_1.PublicKey(tokenInfo.mint);
253
- // Get the user's token account
254
- const toAccount = await this.getAssociatedTokenAccount(mint);
255
- // Get the bridge's token account
256
- const [authority] = await this.bridgeClient.findAuthorityPda();
257
- const fromAccount = await (0, spl_token_1.getAssociatedTokenAddress)(mint, authority, true);
258
- // Withdraw tokens
259
- return await this.bridgeClient.withdraw({
260
- claim,
261
- fromAccount,
262
- toAccount
263
- }, this.keypair);
264
- }
265
- catch (error) {
266
- throw new NordError_1.NordError("Failed to withdraw SPL tokens", { cause: error });
267
- }
268
- }
269
- /**
270
- * Get a new nonce for actions
271
- *
272
- * @returns Nonce as number
273
- */
274
- getNonce() {
275
- return ++this.lastNonce;
276
- }
277
- /**
278
- * Update account IDs for this user
279
- *
280
- * @throws {NordError} If the operation fails
281
- */
282
- async updateAccountId() {
283
- try {
284
- if (!this.publicKey) {
285
- throw new NordError_1.NordError("Public key is required to update account ID");
286
- }
287
- const resp = await this.nord.getUserAccountIds({
288
- pubkey: Buffer.from(this.publicKey).toString('hex')
289
- });
290
- this.accountIds = resp.accountIds;
291
- }
292
- catch (error) {
293
- throw new NordError_1.NordError("Failed to update account ID", { cause: error });
294
- }
295
- }
296
- /**
297
- * Fetch user information including balances and orders
298
- *
299
- * @throws {NordError} If the operation fails
300
- */
301
- async fetchInfo() {
302
- if (this.accountIds !== undefined) {
303
- // todo:implement class
304
- const accountsData = await Promise.all(this.accountIds.map(async (accountId) => {
305
- const response = await (0, utils_1.checkedFetch)(`${this.nord.webServerUrl}/account?account_id=${accountId}`);
306
- return {
307
- accountId,
308
- ...(await response.json()),
309
- };
310
- }));
311
- for (const accountData of accountsData) {
312
- this.balances[accountData.accountId] = [];
313
- for (const balance of accountData.balances) {
314
- this.balances[accountData.accountId].push({
315
- accountId: accountData.accountId,
316
- balance: balance.amount,
317
- symbol: balance.token,
318
- });
319
- }
320
- this.orders[accountData.accountId] = accountData.orders.map((order) => {
321
- return {
322
- orderId: order.orderId,
323
- isLong: order.side === "bid",
324
- size: order.size,
325
- price: order.price,
326
- marketId: order.marketId,
327
- };
328
- });
329
- }
330
- }
331
- }
332
- /**
333
- * Refresh the user's session
334
- *
335
- * @param sessionPk - Session public key
336
- * @throws {NordError} If the operation fails
337
- */
338
- async refreshSession(sessionPk) {
339
- this.sessionId = await (0, actions_1.createSession)(this.nord.webServerUrl, this.walletSignFn, await this.nord.getTimestamp(), this.getNonce(), {
340
- userPubkey: (0, utils_1.optExpect)(this.publicKey, "No user's public key"),
341
- sessionPubkey: sessionPk,
342
- });
343
- }
344
- /**
345
- * Revoke a session
346
- *
347
- * @param sessionId - Session ID to revoke
348
- * @throws {NordError} If the operation fails
349
- */
350
- async revokeSession(sessionId) {
351
- try {
352
- await (0, actions_1.revokeSession)(this.nord.webServerUrl, this.walletSignFn, await this.nord.getTimestamp(), this.getNonce(), {
353
- sessionId
354
- });
355
- }
356
- catch (error) {
357
- throw new NordError_1.NordError(`Failed to revoke session ${sessionId}`, { cause: error });
358
- }
359
- }
360
- /**
361
- * Withdraw tokens from the exchange
362
- *
363
- * @param tokenId - Token ID to withdraw
364
- * @param amount - Amount to withdraw
365
- * @throws {NordError} If the operation fails
366
- */
367
- async withdraw(tokenId, amount) {
368
- try {
369
- await (0, actions_1.withdraw)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.getTimestamp(), this.getNonce(), {
370
- sizeDecimals: (0, utils_1.findToken)(this.nord.tokens, tokenId).decimals,
371
- sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
372
- tokenId: tokenId,
373
- amount,
374
- });
375
- }
376
- catch (error) {
377
- throw new NordError_1.NordError(`Failed to withdraw ${amount} of token ID ${tokenId}`, { cause: error });
378
- }
379
- }
380
- /**
381
- * Place an order on the exchange
382
- *
383
- * @param params - Order parameters
384
- * @returns Order ID if successful
385
- * @throws {NordError} If the operation fails
386
- */
387
- async placeOrder(params) {
388
- try {
389
- const market = (0, utils_1.findMarket)(this.nord.markets, params.marketId);
390
- if (!market) {
391
- throw new NordError_1.NordError(`Market with ID ${params.marketId} not found`);
392
- }
393
- return (0, actions_1.placeOrder)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.getTimestamp(), this.getNonce(), {
394
- sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
395
- senderId: params.accountId,
396
- sizeDecimals: market.sizeDecimals,
397
- priceDecimals: market.priceDecimals,
398
- marketId: params.marketId,
399
- side: params.side,
400
- fillMode: params.fillMode,
401
- isReduceOnly: params.isReduceOnly,
402
- size: params.size,
403
- price: params.price,
404
- quoteSize: params.quoteSize,
405
- });
406
- }
407
- catch (error) {
408
- throw new NordError_1.NordError("Failed to place order", { cause: error });
409
- }
410
- }
411
- /**
412
- * Cancel an order
413
- *
414
- * @param orderId - Order ID to cancel
415
- * @param accountId - Account ID that placed the order
416
- * @returns Action ID if successful
417
- * @throws {NordError} If the operation fails
418
- */
419
- async cancelOrder(orderId, accountId) {
420
- try {
421
- return (0, actions_1.cancelOrder)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.getTimestamp(), this.getNonce(), {
422
- sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
423
- senderId: accountId,
424
- orderId,
425
- });
426
- }
427
- catch (error) {
428
- throw new NordError_1.NordError(`Failed to cancel order ${orderId}`, { cause: error });
429
- }
430
- }
431
- /**
432
- * Transfer tokens to another account
433
- *
434
- * @param params - Transfer parameters
435
- * @throws {NordError} If the operation fails
436
- */
437
- async transferToAccount(params) {
438
- try {
439
- const token = (0, utils_1.findToken)(this.nord.tokens, params.tokenId);
440
- await (0, actions_1.transfer)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.getTimestamp(), this.getNonce(), {
441
- sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
442
- fromAccountId: (0, utils_1.optExpect)(params.fromAccountId, "No source account"),
443
- toAccountId: (0, utils_1.optExpect)(params.toAccountId, "No target account"),
444
- tokenId: params.tokenId,
445
- tokenDecimals: token.decimals,
446
- amount: params.amount,
447
- });
448
- }
449
- catch (error) {
450
- throw new NordError_1.NordError("Failed to transfer tokens", { cause: error });
451
- }
452
- }
453
- /**
454
- * Create a new account
455
- *
456
- * @param params - Account creation parameters
457
- * @returns New NordUser instance
458
- * @throws {NordError} If the operation fails
459
- */
460
- async createAccount(params) {
461
- try {
462
- // Create a new keypair for the account
463
- const keypair = web3_js_1.Keypair.generate();
464
- // Create a new NordUser
465
- const newUser = NordUser.fromPrivateKey(this.nord, keypair.secretKey, this.connection);
466
- // Transfer initial funds
467
- await this.transferToAccount({
468
- to: newUser,
469
- tokenId: params.tokenId,
470
- amount: params.amount,
471
- fromAccountId: (0, utils_1.optExpect)(this.accountIds?.[0], "No account ID"),
472
- toAccountId: (0, utils_1.optExpect)(newUser.accountIds?.[0], "No account ID for new user"),
473
- });
474
- return newUser;
475
- }
476
- catch (error) {
477
- throw new NordError_1.NordError("Failed to create account", { cause: error });
478
- }
479
- }
480
- }
481
- exports.NordUser = NordUser;
@@ -1,37 +0,0 @@
1
- import { EventEmitter } from "events";
2
- import { DeltaEvent, Trades, Account, SubscriberConfig, OrderbookResponse, Trade } from "../types";
3
- /**
4
- * Subscriber class for handling WebSocket subscriptions
5
- */
6
- export declare class Subscriber {
7
- streamURL: string;
8
- buffer: (DeltaEvent | Trades | Account)[];
9
- maxBufferLen: number;
10
- /**
11
- * Create a new Subscriber instance
12
- * @param config Subscriber configuration
13
- */
14
- constructor(config: SubscriberConfig);
15
- /**
16
- * Subscribe to WebSocket events
17
- */
18
- subscribe(): void;
19
- }
20
- /**
21
- * Interface for orderbook subscription
22
- */
23
- export interface OrderbookSubscription extends EventEmitter {
24
- on(event: 'message', listener: (data: OrderbookResponse) => void): this;
25
- on(event: 'error', listener: (error: Error) => void): this;
26
- close(): void;
27
- removeAllListeners(event?: string): this;
28
- }
29
- /**
30
- * Interface for trade subscription
31
- */
32
- export interface TradeSubscription extends EventEmitter {
33
- on(event: 'message', listener: (data: Trade[]) => void): this;
34
- on(event: 'error', listener: (error: Error) => void): this;
35
- close(): void;
36
- removeAllListeners(event?: string): this;
37
- }
@@ -1,29 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.Subscriber = void 0;
7
- const ws_1 = __importDefault(require("ws"));
8
- const utils_1 = require("../utils");
9
- /**
10
- * Subscriber class for handling WebSocket subscriptions
11
- */
12
- class Subscriber {
13
- /**
14
- * Create a new Subscriber instance
15
- * @param config Subscriber configuration
16
- */
17
- constructor(config) {
18
- this.streamURL = config.streamURL;
19
- this.buffer = [];
20
- this.maxBufferLen = config.maxBufferLen ?? utils_1.MAX_BUFFER_LEN;
21
- }
22
- /**
23
- * Subscribe to WebSocket events
24
- */
25
- subscribe() {
26
- const ws = new ws_1.default(this.streamURL);
27
- }
28
- }
29
- exports.Subscriber = Subscriber;
@@ -1,101 +0,0 @@
1
- import { FillMode, Side } from "../types";
2
- import { BigIntValue } from "../utils";
3
- import Decimal from "decimal.js";
4
- declare function createSessionImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, walletSignFn: (message: string | Uint8Array) => Promise<string>, currentTimestamp: bigint, nonce: number, params: {
5
- userPubkey: Uint8Array;
6
- sessionPubkey: Uint8Array;
7
- expiryTimestamp?: bigint;
8
- }): Promise<bigint>;
9
- export declare function createSession(serverUrl: string, walletSignFn: (message: string | Uint8Array) => Promise<string>, currentTimestamp: bigint, nonce: number, params: {
10
- userPubkey: Uint8Array;
11
- sessionPubkey: Uint8Array;
12
- expiryTimestamp?: bigint;
13
- }): Promise<bigint>;
14
- declare function revokeSessionImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, walletSignFn: (message: string | Uint8Array) => Promise<string>, currentTimestamp: bigint, nonce: number, params: {
15
- sessionId: BigIntValue;
16
- }): Promise<void>;
17
- export declare function revokeSession(serverUrl: string, walletSignFn: (message: string | Uint8Array) => Promise<string>, currentTimestamp: bigint, nonce: number, params: {
18
- sessionId: BigIntValue;
19
- }): Promise<void>;
20
- declare function withdrawImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
21
- sizeDecimals: number;
22
- sessionId: BigIntValue;
23
- tokenId: number;
24
- amount: Decimal.Value;
25
- }): Promise<void>;
26
- export declare function withdraw(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
27
- sizeDecimals: number;
28
- sessionId: BigIntValue;
29
- tokenId: number;
30
- amount: number;
31
- }): Promise<void>;
32
- declare function placeOrderImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
33
- sessionId: BigIntValue;
34
- senderId?: number;
35
- liquidateeId?: number;
36
- sizeDecimals: number;
37
- priceDecimals: number;
38
- marketId: number;
39
- side: Side;
40
- fillMode: FillMode;
41
- isReduceOnly: boolean;
42
- size?: Decimal.Value;
43
- price?: Decimal.Value;
44
- quoteSize?: Decimal.Value;
45
- clientOrderId?: BigIntValue;
46
- }): Promise<bigint | undefined>;
47
- export declare function placeOrder(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
48
- sessionId: BigIntValue;
49
- senderId?: number;
50
- sizeDecimals: number;
51
- priceDecimals: number;
52
- marketId: number;
53
- side: Side;
54
- fillMode: FillMode;
55
- isReduceOnly: boolean;
56
- size?: Decimal.Value;
57
- price?: Decimal.Value;
58
- quoteSize?: Decimal.Value;
59
- liquidateeId?: number;
60
- clientOrderId?: BigIntValue;
61
- }): Promise<bigint | undefined>;
62
- declare function cancelOrderImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
63
- sessionId: BigIntValue;
64
- senderId?: number;
65
- orderId: BigIntValue;
66
- liquidateeId?: number;
67
- }): Promise<bigint>;
68
- export declare function cancelOrder(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
69
- sessionId: BigIntValue;
70
- senderId?: number;
71
- orderId: BigIntValue;
72
- liquidateeId?: number;
73
- }): Promise<bigint>;
74
- declare function transferImpl(sendFn: (encoded: Uint8Array) => Promise<Uint8Array>, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
75
- sessionId: BigIntValue;
76
- fromAccountId: number;
77
- toAccountId?: number;
78
- tokenId: number;
79
- tokenDecimals: number;
80
- amount: Decimal.Value;
81
- }): Promise<number | undefined>;
82
- export declare function transfer(serverUrl: string, signFn: (message: Uint8Array) => Promise<Uint8Array>, currentTimestamp: bigint, nonce: number, params: {
83
- sessionId: BigIntValue;
84
- fromAccountId: number;
85
- toAccountId?: number;
86
- tokenId: number;
87
- tokenDecimals: number;
88
- amount: Decimal.Value;
89
- }): Promise<number | undefined>;
90
- /**
91
- * For testing purposes
92
- */
93
- export declare const _private: {
94
- createSessionImpl: typeof createSessionImpl;
95
- revokeSessionImpl: typeof revokeSessionImpl;
96
- withdrawImpl: typeof withdrawImpl;
97
- placeOrderImpl: typeof placeOrderImpl;
98
- cancelOrderImpl: typeof cancelOrderImpl;
99
- transferImpl: typeof transferImpl;
100
- };
101
- export {};