@n1xyz/nord-ts 0.0.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.
Files changed (141) hide show
  1. package/.eslintignore +1 -0
  2. package/.eslintrc.js +20 -0
  3. package/.prettierignore +1 -0
  4. package/README.md +110 -0
  5. package/dist/abis/ERC20_ABI.d.ts +39 -0
  6. package/dist/abis/ERC20_ABI.js +313 -0
  7. package/dist/abis/NORD_GETTERS_FACET_ABI.d.ts +34 -0
  8. package/dist/abis/NORD_GETTERS_FACET_ABI.js +195 -0
  9. package/dist/abis/NORD_RAMP_FACET_ABI.d.ts +35 -0
  10. package/dist/abis/NORD_RAMP_FACET_ABI.js +144 -0
  11. package/dist/abis/index.d.ts +3 -0
  12. package/dist/abis/index.js +9 -0
  13. package/dist/const.d.ts +11 -0
  14. package/dist/const.js +34 -0
  15. package/dist/gen/common.d.ts +63 -0
  16. package/dist/gen/common.js +205 -0
  17. package/dist/gen/nord.d.ts +705 -0
  18. package/dist/gen/nord.js +4784 -0
  19. package/dist/index.d.ts +5 -0
  20. package/dist/index.js +21 -0
  21. package/dist/nord/Nord.d.ts +76 -0
  22. package/dist/nord/Nord.js +376 -0
  23. package/dist/nord/NordImpl.d.ts +7 -0
  24. package/dist/nord/NordImpl.js +6 -0
  25. package/dist/nord/NordUser.d.ts +77 -0
  26. package/dist/nord/NordUser.js +249 -0
  27. package/dist/nord/actions.d.ts +101 -0
  28. package/dist/nord/actions.js +254 -0
  29. package/dist/nord/index.d.ts +2 -0
  30. package/dist/nord/index.js +9 -0
  31. package/dist/types.d.ts +343 -0
  32. package/dist/types.js +92 -0
  33. package/dist/utils.d.ts +114 -0
  34. package/dist/utils.js +257 -0
  35. package/docs/.nojekyll +1 -0
  36. package/docs/assets/highlight.css +92 -0
  37. package/docs/assets/icons.js +15 -0
  38. package/docs/assets/icons.svg +1 -0
  39. package/docs/assets/main.js +59 -0
  40. package/docs/assets/navigation.js +1 -0
  41. package/docs/assets/search.js +1 -0
  42. package/docs/assets/style.css +1415 -0
  43. package/docs/classes/Nord.html +44 -0
  44. package/docs/classes/NordUser.html +35 -0
  45. package/docs/classes/Subscriber.html +6 -0
  46. package/docs/enums/FillMode.html +5 -0
  47. package/docs/enums/KeyType.html +4 -0
  48. package/docs/enums/PeakTpsPeriodUnit.html +15 -0
  49. package/docs/enums/Side.html +3 -0
  50. package/docs/functions/assert.html +1 -0
  51. package/docs/functions/bigIntToProtoU128.html +4 -0
  52. package/docs/functions/checkPubKeyLength.html +1 -0
  53. package/docs/functions/checkedFetch.html +6 -0
  54. package/docs/functions/createWebSocketSubscription.html +12 -0
  55. package/docs/functions/decodeLengthDelimited.html +10 -0
  56. package/docs/functions/encodeLengthDelimited.html +6 -0
  57. package/docs/functions/fillModeToProtoFillMode.html +5 -0
  58. package/docs/functions/findMarket.html +1 -0
  59. package/docs/functions/findToken.html +1 -0
  60. package/docs/functions/makeWalletSignFn.html +6 -0
  61. package/docs/functions/optExpect.html +5 -0
  62. package/docs/functions/optMap.html +5 -0
  63. package/docs/functions/optUnwrap.html +2 -0
  64. package/docs/functions/panic.html +1 -0
  65. package/docs/functions/signAction.html +6 -0
  66. package/docs/functions/toScaledU128.html +8 -0
  67. package/docs/functions/toScaledU64.html +8 -0
  68. package/docs/index.html +21 -0
  69. package/docs/interfaces/Account.html +8 -0
  70. package/docs/interfaces/ActionInfo.html +8 -0
  71. package/docs/interfaces/ActionQuery.html +4 -0
  72. package/docs/interfaces/ActionResponse.html +8 -0
  73. package/docs/interfaces/ActionsExtendedInfo.html +10 -0
  74. package/docs/interfaces/ActionsQuery.html +5 -0
  75. package/docs/interfaces/ActionsResponse.html +6 -0
  76. package/docs/interfaces/AggregateMetrics.html +12 -0
  77. package/docs/interfaces/BlockQuery.html +6 -0
  78. package/docs/interfaces/BlockResponse.html +6 -0
  79. package/docs/interfaces/BlockSummary.html +8 -0
  80. package/docs/interfaces/BlockSummaryResponse.html +6 -0
  81. package/docs/interfaces/DeltaEvent.html +6 -0
  82. package/docs/interfaces/ERC20TokenInfo.html +5 -0
  83. package/docs/interfaces/Info.html +3 -0
  84. package/docs/interfaces/Market.html +6 -0
  85. package/docs/interfaces/MarketStats.html +7 -0
  86. package/docs/interfaces/MarketsStatsResponse.html +2 -0
  87. package/docs/interfaces/NordConfig.html +5 -0
  88. package/docs/interfaces/Order.html +6 -0
  89. package/docs/interfaces/OrderInfo.html +6 -0
  90. package/docs/interfaces/OrderbookOrder.html +6 -0
  91. package/docs/interfaces/OrderbookResponse.html +10 -0
  92. package/docs/interfaces/PerpMarketStats.html +5 -0
  93. package/docs/interfaces/RollmanActionExtendedInfo.html +4 -0
  94. package/docs/interfaces/RollmanActionInfo.html +4 -0
  95. package/docs/interfaces/RollmanActionResponse.html +4 -0
  96. package/docs/interfaces/RollmanActionsResponse.html +2 -0
  97. package/docs/interfaces/RollmanBlockResponse.html +3 -0
  98. package/docs/interfaces/SubscriberConfig.html +3 -0
  99. package/docs/interfaces/Token.html +5 -0
  100. package/docs/interfaces/Trade.html +5 -0
  101. package/docs/interfaces/TradeInfo.html +20 -0
  102. package/docs/interfaces/Trades.html +5 -0
  103. package/docs/interfaces/TradesQueryParams.html +10 -0
  104. package/docs/interfaces/TradesResponse.html +12 -0
  105. package/docs/modules.html +77 -0
  106. package/docs/types/BigIntValue.html +2 -0
  107. package/docs/variables/DEBUG_KEYS.html +1 -0
  108. package/docs/variables/DEFAULT_FUNDING_AMOUNTS.html +1 -0
  109. package/docs/variables/DEV_CONTRACT_ADDRESS.html +1 -0
  110. package/docs/variables/DEV_TOKEN_INFOS.html +1 -0
  111. package/docs/variables/DEV_URL.html +1 -0
  112. package/docs/variables/ERC20_ABI.html +1 -0
  113. package/docs/variables/EVM_DEV_URL.html +1 -0
  114. package/docs/variables/FAUCET_PRIVATE_ADDRESS.html +1 -0
  115. package/docs/variables/MAX_BUFFER_LEN.html +1 -0
  116. package/docs/variables/NORD_GETTERS_FACET_ABI.html +1 -0
  117. package/docs/variables/NORD_RAMP_FACET_ABI.html +1 -0
  118. package/docs/variables/SESSION_TTL.html +1 -0
  119. package/docs/variables/WEBSERVER_DEV_URL.html +1 -0
  120. package/docs/variables/ZERO_DECIMAL.html +1 -0
  121. package/jest.config.ts +9 -0
  122. package/nodemon.json +4 -0
  123. package/package.json +61 -0
  124. package/protoc-generate.sh +23 -0
  125. package/src/abis/ERC20_ABI.ts +310 -0
  126. package/src/abis/NORD_GETTERS_FACET_ABI.ts +192 -0
  127. package/src/abis/NORD_RAMP_FACET_ABI.ts +141 -0
  128. package/src/abis/index.ts +3 -0
  129. package/src/const.ts +39 -0
  130. package/src/gen/common.ts +280 -0
  131. package/src/gen/nord.ts +5666 -0
  132. package/src/index.ts +5 -0
  133. package/src/nord/Nord.ts +504 -0
  134. package/src/nord/NordImpl.ts +8 -0
  135. package/src/nord/NordUser.ts +469 -0
  136. package/src/nord/actions.ts +484 -0
  137. package/src/nord/index.ts +2 -0
  138. package/src/types.ts +393 -0
  139. package/src/utils.ts +300 -0
  140. package/tests/utils.spec.ts +154 -0
  141. package/tsconfig.json +24 -0
@@ -0,0 +1,249 @@
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.NordUser = void 0;
7
+ const ethers_1 = require("ethers");
8
+ const secp256k1_1 = __importDefault(require("secp256k1"));
9
+ const const_1 = require("../const");
10
+ const utils_1 = require("../utils");
11
+ const abis_1 = require("../abis");
12
+ const actions_1 = require("./actions");
13
+ class NordUser {
14
+ constructor(params) {
15
+ this.balances = {};
16
+ this.orders = {};
17
+ this.lastTs = 0;
18
+ this.lastNonce = 0;
19
+ this.nord = params.nord;
20
+ this.address = params.address;
21
+ this.walletSignFn = params.walletSignFn;
22
+ this.sessionSignFn = params.sessionSignFn;
23
+ }
24
+ clone() {
25
+ const newUser = new NordUser({
26
+ nord: this.nord,
27
+ address: this.address,
28
+ walletSignFn: this.walletSignFn,
29
+ sessionSignFn: this.sessionSignFn,
30
+ });
31
+ newUser.publicKey = this.publicKey;
32
+ newUser.lastTs = this.lastTs;
33
+ newUser.lastNonce = this.lastNonce;
34
+ newUser.accountIds = this.accountIds;
35
+ newUser.sessionId = this.sessionId;
36
+ return newUser;
37
+ }
38
+ /**
39
+ * Generates a nonce based on the current timestamp.
40
+ * @returns Generated nonce as a number.
41
+ */
42
+ getNonce() {
43
+ const ts = Date.now() / 1000;
44
+ if (ts === this.lastTs) {
45
+ this.lastNonce += 1;
46
+ }
47
+ else {
48
+ this.lastTs = ts;
49
+ this.lastNonce = 0;
50
+ }
51
+ return this.lastNonce;
52
+ }
53
+ async updateAccountId() {
54
+ const hexPubkey = ethers_1.ethers
55
+ .hexlify((0, utils_1.optExpect)(this.publicKey, "No user public key"))
56
+ .slice(2);
57
+ const accountIds_ = await (await (0, utils_1.checkedFetch)(`${this.nord.webServerUrl}/user_account_ids?pubkey=${hexPubkey}`)).json();
58
+ (0, utils_1.assert)(Array.isArray(accountIds_), "Unexpected response");
59
+ const accountIds = accountIds_;
60
+ this.accountIds = accountIds;
61
+ }
62
+ async fetchInfo() {
63
+ if (this.accountIds !== undefined) {
64
+ // todo:implement class
65
+ const accountsData = await Promise.all(this.accountIds.map(async (accountId) => {
66
+ const response = await (0, utils_1.checkedFetch)(`${this.nord.webServerUrl}/account?account_id=${accountId}`);
67
+ return {
68
+ accountId,
69
+ ...(await response.json()),
70
+ };
71
+ }));
72
+ for (const accountData of accountsData) {
73
+ this.balances[accountData.accountId] = [];
74
+ for (const balance of accountData.balances) {
75
+ this.balances[accountData.accountId].push({
76
+ accountId: accountData.accountId,
77
+ balance: balance.amount,
78
+ symbol: balance.token,
79
+ });
80
+ }
81
+ this.orders[accountData.accountId] = accountData.orders.map((order) => {
82
+ return {
83
+ orderId: order.orderId,
84
+ isLong: order.side === "bid",
85
+ size: order.size,
86
+ price: order.price,
87
+ marketId: order.marketId,
88
+ };
89
+ });
90
+ }
91
+ }
92
+ }
93
+ async setPublicKey() {
94
+ const message = "Layer N - Nord";
95
+ const msgHash = ethers_1.ethers.hashMessage(message);
96
+ const msgHashBytes = ethers_1.ethers.getBytes(msgHash);
97
+ const signature = await this.walletSignFn(message);
98
+ const recoveredPubKey = ethers_1.SigningKey.recoverPublicKey(msgHashBytes, signature);
99
+ const publicKeyBuffer = Buffer.from(recoveredPubKey.slice(2), "hex");
100
+ this.publicKey = secp256k1_1.default.publicKeyConvert(publicKeyBuffer, true);
101
+ }
102
+ async fundEthWallet() {
103
+ const provider = new ethers_1.ethers.JsonRpcProvider(this.nord.evmUrl);
104
+ const wallet = new ethers_1.ethers.Wallet(const_1.FAUCET_PRIVATE_ADDRESS, provider);
105
+ (0, utils_1.assert)(const_1.DEFAULT_FUNDING_AMOUNTS["ETH"] != null);
106
+ const ethTx = await wallet.sendTransaction({
107
+ to: this.address,
108
+ value: ethers_1.ethers.parseEther(const_1.DEFAULT_FUNDING_AMOUNTS["ETH"][0]),
109
+ });
110
+ await ethTx.wait();
111
+ }
112
+ async fundErc20Wallet() {
113
+ const provider = new ethers_1.ethers.JsonRpcProvider(this.nord.evmUrl);
114
+ const wallet = new ethers_1.ethers.Wallet(const_1.FAUCET_PRIVATE_ADDRESS, provider);
115
+ (0, utils_1.assert)(const_1.DEFAULT_FUNDING_AMOUNTS["ETH"] != null);
116
+ for (const tokenInfo of this.nord.tokenInfos) {
117
+ const erc20Contract = new ethers_1.ethers.Contract(tokenInfo.address, abis_1.ERC20_ABI, wallet);
118
+ if (const_1.DEFAULT_FUNDING_AMOUNTS[tokenInfo.address]) {
119
+ const defaultFundingAmount = const_1.DEFAULT_FUNDING_AMOUNTS[tokenInfo.address];
120
+ const tokenTx = await erc20Contract.transfer(this.address, ethers_1.ethers.parseUnits(defaultFundingAmount[0], defaultFundingAmount[1]), {
121
+ maxFeePerGas: ethers_1.ethers.parseUnits("30", "gwei"),
122
+ maxPriorityFeePerGas: ethers_1.ethers.parseUnits("0.001", "gwei"),
123
+ });
124
+ await tokenTx.wait();
125
+ }
126
+ }
127
+ }
128
+ async refreshSession(sessionPk) {
129
+ this.sessionId = await (0, actions_1.createSession)(this.nord.webServerUrl, this.walletSignFn, await this.nord.impl.getTimestamp(), this.getNonce(), {
130
+ userPubkey: (0, utils_1.optExpect)(this.publicKey, "No user's public key"),
131
+ sessionPubkey: sessionPk,
132
+ });
133
+ }
134
+ /**
135
+ * Revokes session previously created by user
136
+ *
137
+ * @param sessionId - session identifier
138
+ */
139
+ async revokeSession(sessionId) {
140
+ return (0, actions_1.revokeSession)(this.nord.webServerUrl, this.walletSignFn, await this.nord.impl.getTimestamp(), this.getNonce(), {
141
+ sessionId,
142
+ });
143
+ }
144
+ async deposit(provider, amount, tokenId) {
145
+ const erc20 = this.nord.tokenInfos[tokenId];
146
+ const erc20Contract = new ethers_1.ethers.Contract(erc20.address, abis_1.ERC20_ABI, await provider.getSigner());
147
+ const approveTx = await erc20Contract.approve(this.nord.contractAddress, ethers_1.MaxUint256, {
148
+ maxFeePerGas: ethers_1.ethers.parseUnits("30", "gwei"),
149
+ maxPriorityFeePerGas: ethers_1.ethers.parseUnits("0.001", "gwei"),
150
+ });
151
+ await approveTx.wait();
152
+ const nordContract = new ethers_1.ethers.Contract(this.nord.contractAddress, abis_1.NORD_RAMP_FACET_ABI, await provider.getSigner());
153
+ const depositTx = await nordContract.depositUnchecked(this.publicKey, BigInt(0), ethers_1.ethers.parseUnits(amount.toString(), erc20.precision), {
154
+ maxFeePerGas: ethers_1.ethers.parseUnits("30", "gwei"),
155
+ maxPriorityFeePerGas: ethers_1.ethers.parseUnits("0.001", "gwei"),
156
+ });
157
+ await depositTx.wait();
158
+ }
159
+ async depositApproveTx(provider, amount, tokenId) {
160
+ const erc20 = this.nord.tokenInfos[tokenId];
161
+ const erc20Contract = new ethers_1.ethers.Contract(erc20.address, abis_1.ERC20_ABI, await provider.getSigner());
162
+ const approveTx = await erc20Contract.approve(this.nord.contractAddress, ethers_1.MaxUint256, {
163
+ maxFeePerGas: ethers_1.ethers.parseUnits("30", "gwei"),
164
+ maxPriorityFeePerGas: ethers_1.ethers.parseUnits("0.001", "gwei"),
165
+ });
166
+ return approveTx.hash;
167
+ }
168
+ async depositOnlyTx(provider, amount, tokenId) {
169
+ const erc20 = this.nord.tokenInfos[tokenId];
170
+ const nordContract = new ethers_1.ethers.Contract(this.nord.contractAddress, abis_1.NORD_RAMP_FACET_ABI, await provider.getSigner());
171
+ const depositTx = await nordContract.depositUnchecked(this.publicKey, BigInt(0), ethers_1.ethers.parseUnits(amount.toString(), erc20.precision), {
172
+ maxFeePerGas: ethers_1.ethers.parseUnits("30", "gwei"),
173
+ maxPriorityFeePerGas: ethers_1.ethers.parseUnits("0.001", "gwei"),
174
+ });
175
+ return depositTx.hash;
176
+ }
177
+ async depositEth(provider, amount, tokenId) {
178
+ if (tokenId || tokenId == 0) {
179
+ const nordContract = new ethers_1.ethers.Contract(this.nord.contractAddress, abis_1.NORD_RAMP_FACET_ABI, await provider.getSigner());
180
+ const depositTx = await nordContract.depositUnchecked(this.publicKey, BigInt(1), ethers_1.ethers.parseUnits(amount.toString(), 18), {
181
+ maxFeePerGas: ethers_1.ethers.parseUnits("30", "gwei"),
182
+ maxPriorityFeePerGas: ethers_1.ethers.parseUnits("0.001", "gwei"),
183
+ });
184
+ await depositTx.wait();
185
+ }
186
+ else {
187
+ // todo:implement eth deposits
188
+ }
189
+ }
190
+ async withdraw(tokenId, amount) {
191
+ (0, actions_1.withdraw)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.impl.getTimestamp(), this.getNonce(), {
192
+ sizeDecimals: (0, utils_1.findToken)(this.nord.tokens, tokenId).decimals,
193
+ sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
194
+ tokenId: tokenId,
195
+ amount,
196
+ });
197
+ }
198
+ async placeOrder(params) {
199
+ const market = (0, utils_1.findMarket)(this.nord.markets, params.marketId);
200
+ return (0, actions_1.placeOrder)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.impl.getTimestamp(), this.getNonce(), {
201
+ sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
202
+ senderId: params.accountId,
203
+ sizeDecimals: market.sizeDecimals,
204
+ priceDecimals: market.priceDecimals,
205
+ marketId: params.marketId,
206
+ side: params.side,
207
+ fillMode: params.fillMode,
208
+ isReduceOnly: params.isReduceOnly,
209
+ size: params.size,
210
+ price: params.price,
211
+ quoteSize: params.quoteSize,
212
+ });
213
+ }
214
+ async cancelOrder(orderId, accountId) {
215
+ return (0, actions_1.cancelOrder)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.impl.getTimestamp(), this.getNonce(), {
216
+ sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
217
+ senderId: accountId,
218
+ orderId,
219
+ });
220
+ }
221
+ async transferToAccount(params) {
222
+ const token = (0, utils_1.findToken)(this.nord.tokens, params.tokenId);
223
+ await (0, actions_1.transfer)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.impl.getTimestamp(), this.getNonce(), {
224
+ sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
225
+ fromAccountId: (0, utils_1.optExpect)(params.fromAccountId, "No source account"),
226
+ toAccountId: (0, utils_1.optExpect)(params.toAccountId, "No target account"),
227
+ tokenId: params.tokenId,
228
+ tokenDecimals: token.decimals,
229
+ amount: params.amount,
230
+ });
231
+ }
232
+ async createAccount(params) {
233
+ const token = (0, utils_1.findToken)(this.nord.tokens, params.tokenId);
234
+ const maybeToAccountId = await (0, actions_1.transfer)(this.nord.webServerUrl, this.sessionSignFn, await this.nord.impl.getTimestamp(), this.getNonce(), {
235
+ sessionId: (0, utils_1.optExpect)(this.sessionId, "No session"),
236
+ fromAccountId: (0, utils_1.optExpect)(this.accountIds?.[0], "No source account"),
237
+ toAccountId: undefined,
238
+ tokenId: params.tokenId,
239
+ tokenDecimals: token.decimals,
240
+ amount: params.amount,
241
+ });
242
+ const toAccountId = (0, utils_1.optExpect)(maybeToAccountId, "New account should have been created");
243
+ const newUser = this.clone();
244
+ newUser.accountIds?.push(toAccountId);
245
+ await newUser.fetchInfo();
246
+ return newUser;
247
+ }
248
+ }
249
+ exports.NordUser = NordUser;
@@ -0,0 +1,101 @@
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 {};
@@ -0,0 +1,254 @@
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._private = void 0;
37
+ exports.createSession = createSession;
38
+ exports.revokeSession = revokeSession;
39
+ exports.withdraw = withdraw;
40
+ exports.placeOrder = placeOrder;
41
+ exports.cancelOrder = cancelOrder;
42
+ exports.transfer = transfer;
43
+ const ethers_1 = require("ethers");
44
+ const types_1 = require("../types");
45
+ const utils_1 = require("../utils");
46
+ const proto = __importStar(require("../gen/nord"));
47
+ async function sessionSign(signFn, message) {
48
+ const signature = await signFn(message);
49
+ return new Uint8Array([...message, ...signature]);
50
+ }
51
+ async function walletSign(walletSignFn, message) {
52
+ const signature = await walletSignFn(message);
53
+ return new Uint8Array([
54
+ ...message,
55
+ ...ethers_1.ethers.getBytes(signature.slice(0, -2)),
56
+ ]);
57
+ }
58
+ function makeSendHttp(serverUrl) {
59
+ return async (body) => {
60
+ const response = await (0, utils_1.checkedFetch)(`${serverUrl}/action`, {
61
+ method: "POST",
62
+ headers: {
63
+ "Content-Type": "application/json",
64
+ },
65
+ body,
66
+ });
67
+ return new Uint8Array(await response.arrayBuffer());
68
+ };
69
+ }
70
+ async function sendAction(sendFn, makeSignedMessage, action, actionErrorDesc) {
71
+ const encoded = (0, utils_1.encodeLengthDelimited)(action, proto.Action);
72
+ const body = await makeSignedMessage(encoded);
73
+ const rawResp = await sendFn(body);
74
+ const resp = (0, utils_1.decodeLengthDelimited)(rawResp, proto.Receipt);
75
+ if (resp.kind?.$case === "err") {
76
+ throw new Error(`Could not ${actionErrorDesc}, reason: ${proto.errorToJSON(resp.kind.value)}`);
77
+ }
78
+ return resp;
79
+ }
80
+ async function createSessionImpl(sendFn, walletSignFn, currentTimestamp, nonce, params) {
81
+ (0, utils_1.checkPubKeyLength)(types_1.KeyType.Secp256k1, params.userPubkey.length);
82
+ (0, utils_1.checkPubKeyLength)(types_1.KeyType.Ed25519, params.sessionPubkey.length);
83
+ let expiry = 0n;
84
+ if (params.expiryTimestamp !== undefined) {
85
+ expiry = params.expiryTimestamp;
86
+ (0, utils_1.assert)(expiry > currentTimestamp, "Cannot set expiry timestamp in the past");
87
+ }
88
+ else {
89
+ expiry = currentTimestamp + utils_1.SESSION_TTL;
90
+ }
91
+ const action = {
92
+ currentTimestamp,
93
+ nonce,
94
+ kind: {
95
+ $case: "createSession",
96
+ value: {
97
+ userPubkey: params.userPubkey,
98
+ blstPubkey: params.sessionPubkey,
99
+ expiryTimestamp: expiry,
100
+ },
101
+ },
102
+ };
103
+ const resp = await sendAction(sendFn, (m) => walletSign(walletSignFn, m), action, "create a new session");
104
+ if (resp.kind?.$case === "createSessionResult") {
105
+ return resp.kind.value.sessionId;
106
+ }
107
+ else {
108
+ throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
109
+ }
110
+ }
111
+ async function createSession(serverUrl, walletSignFn, currentTimestamp, nonce, params) {
112
+ return createSessionImpl(makeSendHttp(serverUrl), walletSignFn, currentTimestamp, nonce, params);
113
+ }
114
+ async function revokeSessionImpl(sendFn, walletSignFn, currentTimestamp, nonce, params) {
115
+ const action = {
116
+ currentTimestamp,
117
+ nonce,
118
+ kind: {
119
+ $case: "revokeSession",
120
+ value: {
121
+ sessionId: BigInt(params.sessionId),
122
+ },
123
+ },
124
+ };
125
+ await sendAction(sendFn, (m) => walletSign(walletSignFn, m), action, "create a new session");
126
+ }
127
+ async function revokeSession(serverUrl, walletSignFn, currentTimestamp, nonce, params) {
128
+ return revokeSessionImpl(makeSendHttp(serverUrl), walletSignFn, currentTimestamp, nonce, params);
129
+ }
130
+ async function withdrawImpl(sendFn, signFn, currentTimestamp, nonce, params) {
131
+ const amount = (0, utils_1.toScaledU64)(params.amount, params.sizeDecimals);
132
+ if (amount <= 0) {
133
+ throw new Error("Withdraw amount must be positive");
134
+ }
135
+ const action = {
136
+ currentTimestamp,
137
+ nonce,
138
+ kind: {
139
+ $case: "withdraw",
140
+ value: {
141
+ sessionId: BigInt(params.sessionId),
142
+ tokenId: params.tokenId,
143
+ amount,
144
+ },
145
+ },
146
+ };
147
+ await sendAction(sendFn, (m) => sessionSign(signFn, m), action, "withdraw");
148
+ }
149
+ async function withdraw(serverUrl, signFn, currentTimestamp, nonce, params) {
150
+ return withdrawImpl(makeSendHttp(serverUrl), signFn, currentTimestamp, nonce, params);
151
+ }
152
+ async function placeOrderImpl(sendFn, signFn, currentTimestamp, nonce, params) {
153
+ const price = (0, utils_1.toScaledU64)(params.price ?? 0, params.priceDecimals);
154
+ const size = (0, utils_1.toScaledU64)(params.size ?? 0, params.sizeDecimals);
155
+ const quoteSize = (0, utils_1.toScaledU128)(params.quoteSize ?? 0, params.priceDecimals + params.sizeDecimals);
156
+ // Compose action object
157
+ const action = {
158
+ currentTimestamp,
159
+ nonce,
160
+ kind: {
161
+ $case: "placeOrder",
162
+ value: {
163
+ sessionId: BigInt(params.sessionId),
164
+ senderAccountId: params.senderId,
165
+ marketId: params.marketId,
166
+ side: params.side === types_1.Side.Bid ? proto.Side.BID : proto.Side.ASK,
167
+ fillMode: (0, types_1.fillModeToProtoFillMode)(params.fillMode),
168
+ isReduceOnly: params.isReduceOnly,
169
+ price,
170
+ size,
171
+ quoteSize: (0, utils_1.bigIntToProtoU128)(quoteSize),
172
+ clientOrderId: (0, utils_1.optMap)(params.clientOrderId, (x) => BigInt(x)),
173
+ delegatorAccountId: params.liquidateeId,
174
+ },
175
+ },
176
+ };
177
+ const resp = await sendAction(sendFn, (m) => sessionSign(signFn, m), action, "place the order");
178
+ if (resp.kind?.$case === "placeOrderResult") {
179
+ return resp.kind.value.posted?.orderId;
180
+ }
181
+ else {
182
+ throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
183
+ }
184
+ }
185
+ async function placeOrder(serverUrl, signFn, currentTimestamp, nonce, params) {
186
+ return placeOrderImpl(makeSendHttp(serverUrl), signFn, currentTimestamp, nonce, params);
187
+ }
188
+ async function cancelOrderImpl(sendFn, signFn, currentTimestamp, nonce, params) {
189
+ const action = {
190
+ currentTimestamp,
191
+ nonce: nonce,
192
+ kind: {
193
+ $case: "cancelOrderById",
194
+ value: {
195
+ orderId: BigInt(params.orderId),
196
+ sessionId: BigInt(params.sessionId),
197
+ senderAccountId: params.senderId,
198
+ delegatorAccountId: params.liquidateeId,
199
+ },
200
+ },
201
+ };
202
+ const resp = await sendAction(sendFn, (m) => sessionSign(signFn, m), action, "cancel the order");
203
+ if (resp.kind?.$case === "cancelOrderResult") {
204
+ return resp.kind.value.orderId;
205
+ }
206
+ else {
207
+ throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
208
+ }
209
+ }
210
+ async function cancelOrder(serverUrl, signFn, currentTimestamp, nonce, params) {
211
+ return cancelOrderImpl(makeSendHttp(serverUrl), signFn, currentTimestamp, nonce, params);
212
+ }
213
+ async function transferImpl(sendFn, signFn, currentTimestamp, nonce, params) {
214
+ const action = {
215
+ currentTimestamp,
216
+ nonce: nonce,
217
+ kind: {
218
+ $case: "transfer",
219
+ value: {
220
+ sessionId: BigInt(params.sessionId),
221
+ fromAccountId: params.fromAccountId,
222
+ toAccountId: params.toAccountId,
223
+ tokenId: params.tokenId,
224
+ amount: (0, utils_1.toScaledU64)(params.amount ?? 0, params.tokenDecimals),
225
+ },
226
+ },
227
+ };
228
+ const resp = await sendAction(sendFn, (m) => sessionSign(signFn, m), action, "transfer asset to other account");
229
+ if (resp.kind?.$case === "transferred") {
230
+ if (resp.kind.value.accountCreated) {
231
+ return resp.kind.value.toAccountId;
232
+ }
233
+ else {
234
+ return undefined;
235
+ }
236
+ }
237
+ else {
238
+ throw new Error(`Unexpected receipt kind ${resp.kind?.$case}`);
239
+ }
240
+ }
241
+ async function transfer(serverUrl, signFn, currentTimestamp, nonce, params) {
242
+ return transferImpl(makeSendHttp(serverUrl), signFn, currentTimestamp, nonce, params);
243
+ }
244
+ /**
245
+ * For testing purposes
246
+ */
247
+ exports._private = {
248
+ createSessionImpl,
249
+ revokeSessionImpl,
250
+ withdrawImpl,
251
+ placeOrderImpl,
252
+ cancelOrderImpl,
253
+ transferImpl,
254
+ };
@@ -0,0 +1,2 @@
1
+ export { NordUser } from "./NordUser";
2
+ export { Nord, createWebSocketSubscription, Subscriber } from "./Nord";
@@ -0,0 +1,9 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Subscriber = exports.createWebSocketSubscription = exports.Nord = exports.NordUser = void 0;
4
+ var NordUser_1 = require("./NordUser");
5
+ Object.defineProperty(exports, "NordUser", { enumerable: true, get: function () { return NordUser_1.NordUser; } });
6
+ var Nord_1 = require("./Nord");
7
+ Object.defineProperty(exports, "Nord", { enumerable: true, get: function () { return Nord_1.Nord; } });
8
+ Object.defineProperty(exports, "createWebSocketSubscription", { enumerable: true, get: function () { return Nord_1.createWebSocketSubscription; } });
9
+ Object.defineProperty(exports, "Subscriber", { enumerable: true, get: function () { return Nord_1.Subscriber; } });