@n1xyz/nord-ts 0.2.0 → 0.3.2

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.
@@ -1,362 +0,0 @@
1
- import { create } from "@bufbuild/protobuf";
2
- import * as proto from "../gen/nord_pb";
3
- import { decodeHex, signAdminPayload } from "../utils";
4
- import { createAction, sendAction, expectReceiptKind } from "../actions";
5
- import { NordError } from "../error";
6
- // NOTE: keep in sync with `acl.rs`.
7
- export var AclRole;
8
- (function (AclRole) {
9
- // note: use 2 ** n instead of 1 << n since js internally
10
- // casts number to a signed int for bitwise ops. when merging
11
- // these roles, make sure to use += instead of |=. this will
12
- // only work when the roles are powers of two.
13
- AclRole[AclRole["FEE_MANAGER"] = 1] = "FEE_MANAGER";
14
- AclRole[AclRole["MARKET_MANAGER"] = 2] = "MARKET_MANAGER";
15
- AclRole[AclRole["ADMIN"] = 2147483648] = "ADMIN";
16
- })(AclRole || (AclRole = {}));
17
- /**
18
- * Administrative client capable of submitting privileged configuration actions.
19
- */
20
- export class NordAdmin {
21
- nord;
22
- admin;
23
- signFn;
24
- constructor({ nord, admin, signFn, }) {
25
- this.nord = nord;
26
- this.admin = admin;
27
- this.signFn = signFn;
28
- }
29
- /** Create a new admin client.
30
- *
31
- * @param nord - Nord instance
32
- * @param admin - The user that will be signing actions.
33
- * @param signFn - Function to sign messages with the admin's wallet.
34
- */
35
- static async new({ nord, admin, signFn, }) {
36
- return new NordAdmin({
37
- nord,
38
- admin,
39
- signFn,
40
- });
41
- }
42
- /**
43
- * Submit an action and append the admin signature before sending it to Nord.
44
- *
45
- * @param kind - Action payload describing the admin request
46
- * @throws {NordError} If signing or submission fails
47
- */
48
- async submitAction(kind) {
49
- const timestamp = await this.nord.getTimestamp();
50
- const action = createAction(timestamp, 0, kind);
51
- return sendAction(this.nord.httpClient, async (xs) => {
52
- const signature = await signAdminPayload({
53
- payload: xs,
54
- user: this.admin,
55
- signTransaction: this.signFn,
56
- });
57
- return Uint8Array.from([...xs, ...signature]);
58
- }, action);
59
- }
60
- /** Set acl permissions for a given user.
61
- *
62
- * If all roles are removed, the user is removed from the acl.
63
- *
64
- * @param target - User to update.
65
- * @param addRoles - Roles to add to the user.
66
- * @param removeRoles - Reles to remove from the user.
67
- */
68
- async updateAcl({ target, addRoles, removeRoles, }) {
69
- const allRoles = addRoles.concat(removeRoles);
70
- if (allRoles.length !== new Set(allRoles).size) {
71
- throw new NordError("duplicate roles in acl update; must be unique");
72
- }
73
- let mask = 0;
74
- let values = 0;
75
- // using += instead of |= to avoid the internal cast to i32 >:(
76
- // this works because our roles are powers of two.
77
- for (const role of allRoles)
78
- mask += role;
79
- for (const role of addRoles)
80
- values += role;
81
- const receipt = await this.submitAction({
82
- case: "updateAcl",
83
- value: create(proto.Action_UpdateAclSchema, {
84
- aclPubkey: this.admin.toBytes(),
85
- targetPubkey: target.toBytes(),
86
- rolesValue: values,
87
- rolesMask: mask,
88
- }),
89
- });
90
- expectReceiptKind(receipt, "aclUpdated", "update acl");
91
- return { ...receipt.kind.value, actionId: receipt.actionId };
92
- }
93
- /**
94
- * Register a new token that can be listed on Nord.
95
- *
96
- * @param tokenDecimals - Decimal shift used when parsing deposits/withdrawals
97
- * @param weightBps - Risk weight in basis points applied in account value calculations
98
- * @param viewSymbol - Symbol surfaced to Nord clients
99
- * @param oracleSymbol - Symbol resolved by the oracle adapter
100
- * @param mintAddr - Solana mint backing this token
101
- * @returns Action identifier and resulting token metadata
102
- * @throws {NordError} If the action submission fails
103
- */
104
- async createToken({ tokenDecimals, weightBps, viewSymbol, oracleSymbol, mintAddr, }) {
105
- const receipt = await this.submitAction({
106
- case: "createToken",
107
- value: create(proto.Action_CreateTokenSchema, {
108
- aclPubkey: this.admin.toBytes(),
109
- tokenDecimals,
110
- weightBps,
111
- viewSymbol,
112
- oracleSymbol,
113
- solAddr: mintAddr.toBytes(),
114
- }),
115
- });
116
- expectReceiptKind(receipt, "insertTokenResult", "create token");
117
- return { actionId: receipt.actionId, ...receipt.kind.value };
118
- }
119
- /**
120
- * Open a new market with the provided trading parameters.
121
- *
122
- * @param sizeDecimals - Decimal shift for contract sizes
123
- * @param priceDecimals - Decimal shift for price ticks
124
- * @param imfBps - Base initial margin fraction (IMF) in basis points, see docs/MARKETS.md
125
- * @param cmfBps - Cancel margin fraction (CMF) in basis points, see docs/MARKETS.md
126
- * @param mmfBps - Maintenance margin fraction (MMF) in basis points, see docs/MARKETS.md
127
- * @param marketType - Spot or perpetual market type
128
- * @param viewSymbol - Symbol exposed to Nord clients
129
- * @param oracleSymbol - Symbol resolved by the oracle adapter
130
- * @param baseTokenId - Registered base token backing this market
131
- * @returns Action identifier and resulting market metadata
132
- * @throws {NordError} If the action submission fails
133
- */
134
- async createMarket({ sizeDecimals, priceDecimals, imfBps, cmfBps, mmfBps, marketType, viewSymbol, oracleSymbol, baseTokenId, }) {
135
- const receipt = await this.submitAction({
136
- case: "createMarket",
137
- value: create(proto.Action_CreateMarketSchema, {
138
- aclPubkey: this.admin.toBytes(),
139
- sizeDecimals,
140
- priceDecimals,
141
- imfBps,
142
- cmfBps,
143
- mmfBps,
144
- marketType,
145
- viewSymbol,
146
- oracleSymbol,
147
- baseTokenId,
148
- }),
149
- });
150
- expectReceiptKind(receipt, "insertMarketResult", "create market");
151
- return { actionId: receipt.actionId, ...receipt.kind.value };
152
- }
153
- /**
154
- * Update the Pyth guardian set used for verifying Wormhole messages.
155
- *
156
- * Each address must decode from a 20-byte hex string (with or without a
157
- * leading `0x` prefix). The engine validates the supplied guardian set index
158
- * before applying the update.
159
- *
160
- * @param guardianSetIndex - Wormhole guardian set index that must already exist
161
- * @param addresses - 20-byte hex-encoded guardian addresses
162
- * @returns Action identifier and guardian update receipt
163
- * @throws {NordError} If the action submission fails
164
- */
165
- async pythSetWormholeGuardians({ guardianSetIndex, addresses, }) {
166
- const parsedAddresses = addresses.map((address) => {
167
- try {
168
- const decoded = decodeHex(address);
169
- if (decoded.length !== 20) {
170
- throw new Error("guardian address must be 20 bytes");
171
- }
172
- return decoded;
173
- }
174
- catch (e) {
175
- throw new NordError("invalid guardian address; must be a 20 byte hex address", { cause: e });
176
- }
177
- });
178
- const receipt = await this.submitAction({
179
- case: "pythSetWormholeGuardians",
180
- value: create(proto.Action_PythSetWormholeGuardiansSchema, {
181
- aclPubkey: this.admin.toBytes(),
182
- guardianSetIndex,
183
- addresses: parsedAddresses,
184
- }),
185
- });
186
- expectReceiptKind(receipt, "updateGuardianSetResult", "update wormhole guardians");
187
- return { actionId: receipt.actionId, ...receipt.kind.value };
188
- }
189
- /**
190
- * Link an oracle symbol to a specific Pyth price feed.
191
- *
192
- * The price feed identifier must decode to 32 bytes (with or without a
193
- * leading `0x` prefix). Use this call to create or update the mapping used
194
- * by the oracle integration.
195
- *
196
- * @param oracleSymbol - Symbol resolved by the oracle adapter
197
- * @param priceFeedId - 32-byte hex-encoded Pyth price feed identifier
198
- * @returns Action identifier and symbol feed receipt
199
- * @throws {NordError} If the action submission fails
200
- */
201
- async pythSetSymbolFeed({ oracleSymbol, priceFeedId: priceFeedIdHex, }) {
202
- let priceFeedId;
203
- try {
204
- priceFeedId = decodeHex(priceFeedIdHex);
205
- if (priceFeedId.length !== 32) {
206
- throw new Error("price feed id must be 32 bytes");
207
- }
208
- }
209
- catch (e) {
210
- throw new NordError("invalid price feed id; must be a 32 byte hex id", {
211
- cause: e,
212
- });
213
- }
214
- const receipt = await this.submitAction({
215
- case: "pythSetSymbolFeed",
216
- value: create(proto.Action_PythSetSymbolFeedSchema, {
217
- aclPubkey: this.admin.toBytes(),
218
- oracleSymbol,
219
- priceFeedId,
220
- }),
221
- });
222
- expectReceiptKind(receipt, "oracleSymbolFeedResult", "set symbol feed");
223
- return { actionId: receipt.actionId, ...receipt.kind.value };
224
- }
225
- /**
226
- * Pause all trading activity on the exchange.
227
- *
228
- * @returns Action identifier confirming the pause
229
- * @throws {NordError} If the action submission fails
230
- */
231
- async pause() {
232
- const receipt = await this.submitAction({
233
- case: "pause",
234
- value: create(proto.Action_PauseSchema, {
235
- aclPubkey: this.admin.toBytes(),
236
- }),
237
- });
238
- expectReceiptKind(receipt, "paused", "pause");
239
- return { actionId: receipt.actionId };
240
- }
241
- /**
242
- * Resume trading activity after a pause.
243
- *
244
- * @returns Action identifier confirming the unpause
245
- * @throws {NordError} If the action submission fails
246
- */
247
- async unpause() {
248
- const receipt = await this.submitAction({
249
- case: "unpause",
250
- value: create(proto.Action_UnpauseSchema, {
251
- aclPubkey: this.admin.toBytes(),
252
- }),
253
- });
254
- expectReceiptKind(receipt, "unpaused", "unpause");
255
- return { actionId: receipt.actionId };
256
- }
257
- /**
258
- * Freeze an individual market, preventing new trades and orders.
259
- *
260
- * @param marketId - Target market identifier
261
- * @returns Action identifier and freeze receipt
262
- * @throws {NordError} If the action submission fails
263
- */
264
- async freezeMarket({ marketId, }) {
265
- const receipt = await this.submitAction({
266
- case: "freezeMarket",
267
- value: create(proto.Action_FreezeMarketSchema, {
268
- marketId,
269
- aclPubkey: this.admin.toBytes(),
270
- }),
271
- });
272
- expectReceiptKind(receipt, "marketFreezeUpdated", "freeze market");
273
- return { actionId: receipt.actionId, ...receipt.kind.value };
274
- }
275
- /**
276
- * Unfreeze a market that was previously halted.
277
- *
278
- * @param marketId - Target market identifier
279
- * @returns Action identifier and freeze receipt
280
- * @throws {NordError} If the action submission fails
281
- */
282
- async unfreezeMarket({ marketId, }) {
283
- const receipt = await this.submitAction({
284
- case: "unfreezeMarket",
285
- value: create(proto.Action_UnfreezeMarketSchema, {
286
- marketId,
287
- aclPubkey: this.admin.toBytes(),
288
- }),
289
- });
290
- expectReceiptKind(receipt, "marketFreezeUpdated", "unfreeze market");
291
- return { actionId: receipt.actionId, ...receipt.kind.value };
292
- }
293
- /**
294
- * Append a new fee tier to the account bracket configuration.
295
- *
296
- * - The engine supports at most 16 tiers (ids 0–15). Tier 0 is reserved for
297
- * the default Nord fees; use `updateFeeTier` if you need to change it.
298
- * - The first appended tier receives id 1, and subsequent tiers increment the id.
299
- *
300
- * @param config - Fee tier configuration to insert
301
- * @returns Action identifier and fee tier addition receipt
302
- * @throws {NordError} If the action submission fails or the new tier exceeds the maximum range (0-15).
303
- */
304
- async addFeeTier({ config, }) {
305
- const receipt = await this.submitAction({
306
- case: "addFeeTier",
307
- value: create(proto.Action_AddFeeTierSchema, {
308
- aclPubkey: this.admin.toBytes(),
309
- config: create(proto.FeeTierConfigSchema, config),
310
- }),
311
- });
312
- expectReceiptKind(receipt, "feeTierAdded", "add fee tier");
313
- return { actionId: receipt.actionId, ...receipt.kind.value };
314
- }
315
- /**
316
- * Update an existing fee tier with new maker/taker rates.
317
- *
318
- * Tier identifiers must already exist; attempting to update a missing tier
319
- * causes the action to fail.
320
- *
321
- * @param tierId - Existing fee tier identifier to update
322
- * @param config - Replacement configuration for the tier
323
- * @returns Action identifier and fee tier update receipt
324
- * @throws {NordError} If the action submission fails or the tier ID exceeds the configured range.
325
- */
326
- async updateFeeTier({ tierId, config, }) {
327
- const receipt = await this.submitAction({
328
- case: "updateFeeTier",
329
- value: create(proto.Action_UpdateFeeTierSchema, {
330
- aclPubkey: this.admin.toBytes(),
331
- id: tierId,
332
- config: create(proto.FeeTierConfigSchema, config),
333
- }),
334
- });
335
- expectReceiptKind(receipt, "feeTierUpdated", "update fee tier");
336
- return { actionId: receipt.actionId, ...receipt.kind.value };
337
- }
338
- /**
339
- * Assign a fee tier to one or more accounts.
340
- *
341
- * The tier id must be within the configured range (0–15). Every account starts
342
- * on tier 0; assigning it to another tier requires that tier to exist already.
343
- * Invalid account ids or tier ids cause the action to fail.
344
- *
345
- * @param accounts - Account IDs to update
346
- * @param tierId - Target fee tier identifier
347
- * @returns Action identifier and accounts-tier receipt
348
- * @throws {NordError} If the tier id exceeds the configured range or an account id is invalid.
349
- */
350
- async updateAccountsTier(accounts, tierId) {
351
- const receipt = await this.submitAction({
352
- case: "updateAccountsTier",
353
- value: create(proto.Action_UpdateAccountsTierSchema, {
354
- aclPubkey: this.admin.toBytes(),
355
- accounts,
356
- tierId,
357
- }),
358
- });
359
- expectReceiptKind(receipt, "accountsTierUpdated", "update accounts tier");
360
- return { actionId: receipt.actionId, ...receipt.kind.value };
361
- }
362
- }