@n1xyz/nord-ts 0.1.6 → 0.1.8

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 (85) hide show
  1. package/dist/actions.d.ts +57 -0
  2. package/dist/actions.js +186 -0
  3. package/dist/bundle.js +79181 -0
  4. package/dist/{nord/client → client}/Nord.d.ts +90 -107
  5. package/dist/{nord/client → client}/Nord.js +157 -218
  6. package/dist/{nord/client → client}/NordAdmin.d.ts +68 -102
  7. package/dist/{nord/client → client}/NordAdmin.js +109 -140
  8. package/dist/{nord/client → client}/NordUser.d.ts +86 -98
  9. package/dist/{nord/client → client}/NordUser.js +204 -271
  10. package/dist/const.js +5 -8
  11. package/dist/{nord/utils/NordError.js → error.js} +7 -5
  12. package/dist/gen/nord_pb.js +88 -92
  13. package/dist/gen/openapi.d.ts +39 -0
  14. package/dist/gen/openapi.js +1 -2
  15. package/dist/index.d.ts +6 -1
  16. package/dist/index.js +10 -21
  17. package/dist/types.d.ts +5 -50
  18. package/dist/types.js +21 -83
  19. package/dist/utils.d.ts +8 -11
  20. package/dist/utils.js +55 -90
  21. package/dist/websocket/NordWebSocketClient.js +12 -17
  22. package/dist/{nord/models → websocket}/Subscriber.d.ts +1 -1
  23. package/dist/{nord/models → websocket}/Subscriber.js +6 -7
  24. package/dist/websocket/events.js +1 -2
  25. package/dist/websocket/index.d.ts +19 -2
  26. package/dist/websocket/index.js +80 -5
  27. package/package.json +2 -3
  28. package/dist/api/client.d.ts +0 -14
  29. package/dist/api/client.js +0 -45
  30. package/dist/bridge/client.d.ts +0 -151
  31. package/dist/bridge/client.js +0 -434
  32. package/dist/bridge/const.d.ts +0 -23
  33. package/dist/bridge/const.js +0 -47
  34. package/dist/bridge/index.d.ts +0 -4
  35. package/dist/bridge/index.js +0 -23
  36. package/dist/bridge/types.d.ts +0 -120
  37. package/dist/bridge/types.js +0 -18
  38. package/dist/bridge/utils.d.ts +0 -64
  39. package/dist/bridge/utils.js +0 -131
  40. package/dist/gen/common.d.ts +0 -68
  41. package/dist/gen/common.js +0 -215
  42. package/dist/gen/nord.d.ts +0 -882
  43. package/dist/gen/nord.js +0 -6520
  44. package/dist/idl/bridge.d.ts +0 -569
  45. package/dist/idl/bridge.js +0 -8
  46. package/dist/idl/bridge.json +0 -1506
  47. package/dist/idl/index.d.ts +0 -607
  48. package/dist/idl/index.js +0 -8
  49. package/dist/nord/api/actions.d.ts +0 -126
  50. package/dist/nord/api/actions.js +0 -397
  51. package/dist/nord/api/core.d.ts +0 -16
  52. package/dist/nord/api/core.js +0 -81
  53. package/dist/nord/api/market.d.ts +0 -36
  54. package/dist/nord/api/market.js +0 -96
  55. package/dist/nord/api/metrics.d.ts +0 -67
  56. package/dist/nord/api/metrics.js +0 -229
  57. package/dist/nord/api/queries.d.ts +0 -46
  58. package/dist/nord/api/queries.js +0 -109
  59. package/dist/nord/api/triggers.d.ts +0 -7
  60. package/dist/nord/api/triggers.js +0 -38
  61. package/dist/nord/client/NordClient.d.ts +0 -33
  62. package/dist/nord/client/NordClient.js +0 -45
  63. package/dist/nord/index.d.ts +0 -11
  64. package/dist/nord/index.js +0 -36
  65. package/src/const.ts +0 -34
  66. package/src/gen/.gitkeep +0 -0
  67. package/src/gen/nord_pb.ts +0 -5053
  68. package/src/gen/openapi.ts +0 -2864
  69. package/src/index.ts +0 -5
  70. package/src/nord/api/actions.ts +0 -648
  71. package/src/nord/api/core.ts +0 -96
  72. package/src/nord/api/metrics.ts +0 -269
  73. package/src/nord/client/Nord.ts +0 -937
  74. package/src/nord/client/NordAdmin.ts +0 -514
  75. package/src/nord/client/NordClient.ts +0 -79
  76. package/src/nord/client/NordUser.ts +0 -1211
  77. package/src/nord/index.ts +0 -25
  78. package/src/nord/models/Subscriber.ts +0 -56
  79. package/src/nord/utils/NordError.ts +0 -76
  80. package/src/types.ts +0 -377
  81. package/src/utils.ts +0 -269
  82. package/src/websocket/NordWebSocketClient.ts +0 -316
  83. package/src/websocket/events.ts +0 -31
  84. package/src/websocket/index.ts +0 -2
  85. /package/dist/{nord/utils/NordError.d.ts → error.d.ts} +0 -0
@@ -1231,6 +1231,41 @@ export interface paths {
1231
1231
  patch?: never;
1232
1232
  trace?: never;
1233
1233
  };
1234
+ "/admin": {
1235
+ parameters: {
1236
+ query?: never;
1237
+ header?: never;
1238
+ path?: never;
1239
+ cookie?: never;
1240
+ };
1241
+ /** @description List of assigned admins. */
1242
+ get: {
1243
+ parameters: {
1244
+ query?: never;
1245
+ header?: never;
1246
+ path?: never;
1247
+ cookie?: never;
1248
+ };
1249
+ requestBody?: never;
1250
+ responses: {
1251
+ 200: {
1252
+ headers: {
1253
+ [name: string]: unknown;
1254
+ };
1255
+ content: {
1256
+ "application/json": components["schemas"]["AdminInfo"][];
1257
+ };
1258
+ };
1259
+ };
1260
+ };
1261
+ put?: never;
1262
+ post?: never;
1263
+ delete?: never;
1264
+ options?: never;
1265
+ head?: never;
1266
+ patch?: never;
1267
+ trace?: never;
1268
+ };
1234
1269
  "/tv": {
1235
1270
  parameters: {
1236
1271
  query?: never;
@@ -2688,6 +2723,10 @@ export interface components {
2688
2723
  accountId: number;
2689
2724
  feeTier: components["schemas"]["FeeTierId"];
2690
2725
  };
2726
+ AdminInfo: {
2727
+ key: string;
2728
+ roles: string[];
2729
+ };
2691
2730
  /** @description TV config query response https://www.tradingview.com/charting-library-docs/latest/connecting_data/UDF/#data-feed-configuration-data */
2692
2731
  TvConfigResponse: {
2693
2732
  supported_resolutions: components["schemas"]["Resolution"][];
@@ -1,6 +1,5 @@
1
- "use strict";
2
1
  /**
3
2
  * This file was auto-generated by openapi-typescript.
4
3
  * Do not make direct changes to the file.
5
4
  */
6
- Object.defineProperty(exports, "__esModule", { value: true });
5
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  export * from "./types";
2
2
  export * from "./utils";
3
3
  export * from "./const";
4
- export * from "./nord";
4
+ export * from "./error";
5
5
  export * from "./websocket/index";
6
+ export * from "./client/Nord";
7
+ export * from "./client/NordUser";
8
+ export * from "./client/NordAdmin";
9
+ export * as proto from "./gen/nord_pb";
10
+ export * as openapi from "./gen/openapi";
package/dist/index.js CHANGED
@@ -1,21 +1,10 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./types"), exports);
18
- __exportStar(require("./utils"), exports);
19
- __exportStar(require("./const"), exports);
20
- __exportStar(require("./nord"), exports);
21
- __exportStar(require("./websocket/index"), exports);
1
+ export * from "./types";
2
+ export * from "./utils";
3
+ export * from "./const";
4
+ export * from "./error";
5
+ export * from "./websocket/index";
6
+ export * from "./client/Nord";
7
+ export * from "./client/NordUser";
8
+ export * from "./client/NordAdmin";
9
+ export * as proto from "./gen/nord_pb";
10
+ export * as openapi from "./gen/openapi";
package/dist/types.d.ts CHANGED
@@ -1,22 +1,7 @@
1
1
  import * as proto from "./gen/nord_pb";
2
2
  import type { components } from "./gen/openapi.ts";
3
3
  import Decimal from "decimal.js";
4
- /**
5
- * The peak TPS rate is queried over the specified period.
6
- * The period is specified in units of: {hour, day, week, month, year}.
7
- * Example inputs:
8
- * 1. AggregateMetrics.txPeakTpsPeriod = 3,
9
- * AggregateMetrics.txPeakTpsPeriodUnit = "d" => Peak TPS over last 3 days.
10
- * 1. AggregateMetrics.txPeakTpsPeriod = 1,
11
- * AggregateMetrics.txPeakTpsPeriodUnit = "w" => Peak TPS over last week.
12
- */
13
- export declare enum PeakTpsPeriodUnit {
14
- Hour = "h",
15
- Day = "d",
16
- Week = "w",
17
- Month = "m",
18
- Year = "y"
19
- }
4
+ import { Connection } from "@solana/web3.js";
20
5
  /**
21
6
  * Nord subscription type for trades or deltas
22
7
  */
@@ -35,8 +20,8 @@ export interface NordConfig {
35
20
  webServerUrl: string;
36
21
  /** App address */
37
22
  app: string;
38
- /** Solana cluster URL */
39
- solanaUrl: string;
23
+ /** Solana connection */
24
+ solanaConnection: Connection;
40
25
  /** Proton URL, defaults to webServerUrl */
41
26
  protonUrl?: string;
42
27
  /**
@@ -85,6 +70,7 @@ export type FeeTierId = components["schemas"]["FeeTierId"];
85
70
  export type TokenStats = components["schemas"]["TokenStats"];
86
71
  export type AccountFeeTier = components["schemas"]["AccountFeeTier"];
87
72
  export type AccountFeeTierPage = components["schemas"]["PageResult_for_uint32_and_AccountFeeTier"];
73
+ export type AdminInfo = components["schemas"]["AdminInfo"];
88
74
  /**
89
75
  * Configuration options for the Nord client
90
76
  */
@@ -101,11 +87,6 @@ export interface Order {
101
87
  price: number;
102
88
  marketId: number;
103
89
  }
104
- export declare enum KeyType {
105
- Ed25519 = 0,
106
- Secp256k1 = 1,
107
- Bls12_381 = 2
108
- }
109
90
  export declare enum Side {
110
91
  Ask = "ask",
111
92
  Bid = "bid"
@@ -165,32 +146,6 @@ export interface ActionResponse {
165
146
  action: proto.Action;
166
147
  physicalExecTime: Date;
167
148
  }
168
- /**
169
- * Block summary.
170
- * block_number Block number.
171
- * from_action_id First action_id in the block.
172
- * to_action_id Last action_id in the block.
173
- */
174
- export interface BlockSummary {
175
- block_number: number;
176
- from_action_id: number;
177
- to_action_id: number;
178
- }
179
- /**
180
- * Aggregate metrics
181
- * blocks_total: Total number of L2 blocks.
182
- * tx_total: Total number of transactions.
183
- * tx_tps: Transaction throughput.
184
- * tx_tps_peak: Peak transaction throughput.
185
- * request_latency_average: Average request latency.
186
- */
187
- export interface AggregateMetrics {
188
- blocks_total: number;
189
- tx_total: number;
190
- tx_tps: number;
191
- tx_tps_peak: number;
192
- request_latency_average: number;
193
- }
194
149
  /**
195
150
  * Converts a `FillMode` enum to its corresponding protobuf representation.
196
151
  *
@@ -214,7 +169,7 @@ export interface OrderbookEntry {
214
169
  */
215
170
  export interface OrderbookQuery {
216
171
  symbol?: string;
217
- market_id?: number;
172
+ marketId?: number;
218
173
  }
219
174
  /**
220
175
  * Response for timestamp query
package/dist/types.js CHANGED
@@ -1,93 +1,30 @@
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
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.QuoteSize = exports.WebSocketMessageType = exports.TriggerStatus = exports.TriggerKind = exports.FillMode = exports.Side = exports.KeyType = exports.PeakTpsPeriodUnit = void 0;
40
- exports.fillModeToProtoFillMode = fillModeToProtoFillMode;
41
- const proto = __importStar(require("./gen/nord_pb"));
42
- const decimal_js_1 = __importDefault(require("decimal.js"));
43
- const utils_1 = require("./utils");
44
- /**
45
- * The peak TPS rate is queried over the specified period.
46
- * The period is specified in units of: {hour, day, week, month, year}.
47
- * Example inputs:
48
- * 1. AggregateMetrics.txPeakTpsPeriod = 3,
49
- * AggregateMetrics.txPeakTpsPeriodUnit = "d" => Peak TPS over last 3 days.
50
- * 1. AggregateMetrics.txPeakTpsPeriod = 1,
51
- * AggregateMetrics.txPeakTpsPeriodUnit = "w" => Peak TPS over last week.
52
- */
53
- var PeakTpsPeriodUnit;
54
- (function (PeakTpsPeriodUnit) {
55
- PeakTpsPeriodUnit["Hour"] = "h";
56
- PeakTpsPeriodUnit["Day"] = "d";
57
- PeakTpsPeriodUnit["Week"] = "w";
58
- PeakTpsPeriodUnit["Month"] = "m";
59
- PeakTpsPeriodUnit["Year"] = "y";
60
- })(PeakTpsPeriodUnit || (exports.PeakTpsPeriodUnit = PeakTpsPeriodUnit = {}));
61
- var KeyType;
62
- (function (KeyType) {
63
- KeyType[KeyType["Ed25519"] = 0] = "Ed25519";
64
- KeyType[KeyType["Secp256k1"] = 1] = "Secp256k1";
65
- KeyType[KeyType["Bls12_381"] = 2] = "Bls12_381";
66
- })(KeyType || (exports.KeyType = KeyType = {}));
67
- var Side;
1
+ import * as proto from "./gen/nord_pb";
2
+ import Decimal from "decimal.js";
3
+ import { toScaledU64 } from "./utils";
4
+ export var Side;
68
5
  (function (Side) {
69
6
  Side["Ask"] = "ask";
70
7
  Side["Bid"] = "bid";
71
- })(Side || (exports.Side = Side = {}));
72
- var FillMode;
8
+ })(Side || (Side = {}));
9
+ export var FillMode;
73
10
  (function (FillMode) {
74
11
  FillMode[FillMode["Limit"] = 0] = "Limit";
75
12
  FillMode[FillMode["PostOnly"] = 1] = "PostOnly";
76
13
  FillMode[FillMode["ImmediateOrCancel"] = 2] = "ImmediateOrCancel";
77
14
  FillMode[FillMode["FillOrKill"] = 3] = "FillOrKill";
78
- })(FillMode || (exports.FillMode = FillMode = {}));
79
- var TriggerKind;
15
+ })(FillMode || (FillMode = {}));
16
+ export var TriggerKind;
80
17
  (function (TriggerKind) {
81
18
  TriggerKind[TriggerKind["StopLoss"] = 0] = "StopLoss";
82
19
  TriggerKind[TriggerKind["TakeProfit"] = 1] = "TakeProfit";
83
- })(TriggerKind || (exports.TriggerKind = TriggerKind = {}));
84
- var TriggerStatus;
20
+ })(TriggerKind || (TriggerKind = {}));
21
+ export var TriggerStatus;
85
22
  (function (TriggerStatus) {
86
23
  TriggerStatus[TriggerStatus["Active"] = 0] = "Active";
87
24
  TriggerStatus[TriggerStatus["Success"] = 1] = "Success";
88
25
  TriggerStatus[TriggerStatus["Cancel"] = 2] = "Cancel";
89
26
  TriggerStatus[TriggerStatus["Remove"] = 4] = "Remove";
90
- })(TriggerStatus || (exports.TriggerStatus = TriggerStatus = {}));
27
+ })(TriggerStatus || (TriggerStatus = {}));
91
28
  /**
92
29
  * Converts a `FillMode` enum to its corresponding protobuf representation.
93
30
  *
@@ -95,7 +32,7 @@ var TriggerStatus;
95
32
  * @returns The corresponding protobuf fill mode.
96
33
  * @throws Will throw an error if provided with an invalid fill mode.
97
34
  */
98
- function fillModeToProtoFillMode(x) {
35
+ export function fillModeToProtoFillMode(x) {
99
36
  if (x === FillMode.Limit)
100
37
  return proto.FillMode.LIMIT;
101
38
  if (x === FillMode.PostOnly)
@@ -110,12 +47,12 @@ function fillModeToProtoFillMode(x) {
110
47
  /**
111
48
  * WebSocket message types
112
49
  */
113
- var WebSocketMessageType;
50
+ export var WebSocketMessageType;
114
51
  (function (WebSocketMessageType) {
115
52
  WebSocketMessageType["TradeUpdate"] = "trades";
116
53
  WebSocketMessageType["DeltaUpdate"] = "delta";
117
54
  WebSocketMessageType["AccountUpdate"] = "account";
118
- })(WebSocketMessageType || (exports.WebSocketMessageType = WebSocketMessageType = {}));
55
+ })(WebSocketMessageType || (WebSocketMessageType = {}));
119
56
  // Positive decimal price and size.
120
57
  // Example:
121
58
  // ```
@@ -128,11 +65,13 @@ var WebSocketMessageType;
128
65
  // If you want to get smaller tick on client (on server it will not change),
129
66
  // do `new QuoteSize(new Decimal(114000/2), new Decimal(0.00070))`.
130
67
  // It will be 40$ limit, but may help if BTC suddently moves fast.
131
- class QuoteSize {
68
+ export class QuoteSize {
69
+ price;
70
+ size;
132
71
  /// Input can be only positive values.
133
72
  constructor(quotePrice, quoteSize) {
134
- const p = new decimal_js_1.default(quotePrice);
135
- const s = new decimal_js_1.default(quoteSize);
73
+ const p = new Decimal(quotePrice);
74
+ const s = new Decimal(quoteSize);
136
75
  if (!p.isPositive() || !s.isPositive()) {
137
76
  throw new Error("quotePrice and quoteSize must be positive");
138
77
  }
@@ -146,9 +85,8 @@ class QuoteSize {
146
85
  // Converts to wire format to be send to server, scaling price and size according to market decimals.
147
86
  toWire(marketPriceDecimals, marketSizeDecimals) {
148
87
  return {
149
- price: (0, utils_1.toScaledU64)(this.price, marketPriceDecimals),
150
- size: (0, utils_1.toScaledU64)(this.size, marketSizeDecimals),
88
+ price: toScaledU64(this.price, marketPriceDecimals),
89
+ size: toScaledU64(this.size, marketSizeDecimals),
151
90
  };
152
91
  }
153
92
  }
154
- exports.QuoteSize = QuoteSize;
package/dist/utils.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { Decimal } from "decimal.js";
2
- import { KeyType, type Market, type Token } from "./types";
2
+ import { type Market, type Token } from "./types";
3
3
  import { type Message } from "@bufbuild/protobuf";
4
4
  import type { GenMessage } from "@bufbuild/protobuf/codegenv2";
5
5
  import { ethers } from "ethers";
6
6
  import { RequestInfo, RequestInit, Response } from "node-fetch";
7
7
  import { Keypair } from "@solana/web3.js";
8
+ import * as solana from "@solana/web3.js";
8
9
  export declare const SESSION_TTL: bigint;
9
10
  export declare const ZERO_DECIMAL: Decimal;
10
11
  export declare const MAX_BUFFER_LEN = 10000;
@@ -12,7 +13,7 @@ export declare const MAX_BUFFER_LEN = 10000;
12
13
  export type BigIntValue = bigint | number | string;
13
14
  export declare function panic(message: string): never;
14
15
  export declare function isRfc3339(s: string): boolean;
15
- export declare function assert(predicate: boolean, message?: string): void;
16
+ export declare function assert(predicate: boolean, message?: string): asserts predicate;
16
17
  /**
17
18
  * Extracts value out of optional if it's defined, or throws error if it's not
18
19
  * @param value Optional value to unwrap
@@ -28,14 +29,6 @@ export declare function optExpect<T>(value: T | undefined, message: string): T;
28
29
  * @throws If response wasn't Ok
29
30
  */
30
31
  export declare function checkedFetch(url: RequestInfo, init?: RequestInit): Promise<Response>;
31
- /**
32
- * Signs an action using the specified secret key and key type.
33
- * @param action - The action data to be signed.
34
- * @param sk - Secret key used for signing the action.
35
- * @param keyType - Type of the key used for signing.
36
- * @returns A new Uint8Array containing the action followed by its signature.
37
- */
38
- export declare function signAction(action: Uint8Array, sk: Uint8Array, keyType: KeyType): Uint8Array;
39
32
  /**
40
33
  * Constructs wallet signing function, usable with `NordUser` type
41
34
  *
@@ -78,8 +71,12 @@ export declare const toScaledU128: (x: Decimal.Value, decimals: number) => bigin
78
71
  * @returns Decoded message
79
72
  */
80
73
  export declare function decodeLengthDelimited<T extends Message>(bytes: Uint8Array, schema: GenMessage<T>): T;
81
- export declare function checkPubKeyLength(keyType: KeyType, len: number): void;
82
74
  export declare function decodeHex(value: string): Uint8Array;
83
75
  export declare function findMarket(markets: Market[], marketId: number): Market;
84
76
  export declare function findToken(tokens: Token[], tokenId: number): Token;
85
77
  export declare function keypairFromPrivateKey(privateKey: string | Uint8Array): Keypair;
78
+ export declare function signUserPayload({ payload, user, signTransaction, }: Readonly<{
79
+ payload: Uint8Array;
80
+ user: solana.PublicKey;
81
+ signTransaction: (tx: solana.Transaction) => Promise<solana.Transaction>;
82
+ }>): Promise<Uint8Array>;
package/dist/utils.js CHANGED
@@ -1,47 +1,25 @@
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.toScaledU128 = exports.toScaledU64 = exports.MAX_BUFFER_LEN = exports.ZERO_DECIMAL = exports.SESSION_TTL = void 0;
7
- exports.panic = panic;
8
- exports.isRfc3339 = isRfc3339;
9
- exports.assert = assert;
10
- exports.optExpect = optExpect;
11
- exports.checkedFetch = checkedFetch;
12
- exports.signAction = signAction;
13
- exports.makeWalletSignFn = makeWalletSignFn;
14
- exports.decodeLengthDelimited = decodeLengthDelimited;
15
- exports.checkPubKeyLength = checkPubKeyLength;
16
- exports.decodeHex = decodeHex;
17
- exports.findMarket = findMarket;
18
- exports.findToken = findToken;
19
- exports.keypairFromPrivateKey = keypairFromPrivateKey;
20
- const decimal_js_1 = require("decimal.js");
21
- const ed25519_1 = require("@noble/curves/ed25519");
22
- const bls12_381_1 = require("@noble/curves/bls12-381");
23
- const secp256k1_1 = require("@noble/curves/secp256k1");
24
- const sha256_1 = require("@noble/hashes/sha256");
25
- const types_1 = require("./types");
26
- const wire_1 = require("@bufbuild/protobuf/wire");
27
- const protobuf_1 = require("@bufbuild/protobuf");
28
- const ethers_1 = require("ethers");
29
- const node_fetch_1 = __importDefault(require("node-fetch"));
30
- const web3_js_1 = require("@solana/web3.js");
31
- const bs58_1 = __importDefault(require("bs58"));
32
- exports.SESSION_TTL = 60n * 60n * 24n * 30n;
33
- exports.ZERO_DECIMAL = new decimal_js_1.Decimal(0);
34
- exports.MAX_BUFFER_LEN = 10000;
1
+ import { Decimal } from "decimal.js";
2
+ import { sizeDelimitedPeek } from "@bufbuild/protobuf/wire";
3
+ import { fromBinary } from "@bufbuild/protobuf";
4
+ import { ethers } from "ethers";
5
+ import fetch from "node-fetch";
6
+ import { Keypair } from "@solana/web3.js";
7
+ import bs58 from "bs58";
8
+ import * as solana from "@solana/web3.js";
9
+ import { Buffer } from "buffer";
10
+ export const SESSION_TTL = 60n * 60n * 24n * 30n;
11
+ export const ZERO_DECIMAL = new Decimal(0);
12
+ export const MAX_BUFFER_LEN = 10_000;
35
13
  // Max size of data returned from Nord endpoints
36
14
  const MAX_PAYLOAD_SIZE = 100 * 1024; // 100 kB
37
- function panic(message) {
15
+ export function panic(message) {
38
16
  throw new Error(message);
39
17
  }
40
- function isRfc3339(s) {
18
+ export function isRfc3339(s) {
41
19
  const REGEX = /^((?:(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2}(?:\.\d+)?))(Z|[\+-]\d{2}:\d{2})?)$/;
42
20
  return REGEX.test(s);
43
21
  }
44
- function assert(predicate, message) {
22
+ export function assert(predicate, message) {
45
23
  if (!predicate)
46
24
  panic(message ?? "Assertion violated");
47
25
  }
@@ -51,7 +29,7 @@ function assert(predicate, message) {
51
29
  * @param message Error message
52
30
  * @returns Unwrapped value
53
31
  */
54
- function optExpect(value, message) {
32
+ export function optExpect(value, message) {
55
33
  if (value === undefined)
56
34
  throw new Error(message);
57
35
  return value;
@@ -63,34 +41,11 @@ function optExpect(value, message) {
63
41
  * @returns Raw response if fetch succeeded
64
42
  * @throws If response wasn't Ok
65
43
  */
66
- async function checkedFetch(url, init) {
67
- const resp = await (0, node_fetch_1.default)(url, init);
44
+ export async function checkedFetch(url, init) {
45
+ const resp = await fetch(url, init);
68
46
  assert(resp.ok, `Request failed with ${resp.status}: ${resp.statusText}`);
69
47
  return resp;
70
48
  }
71
- /**
72
- * Signs an action using the specified secret key and key type.
73
- * @param action - The action data to be signed.
74
- * @param sk - Secret key used for signing the action.
75
- * @param keyType - Type of the key used for signing.
76
- * @returns A new Uint8Array containing the action followed by its signature.
77
- */
78
- function signAction(action, sk, keyType) {
79
- let sig;
80
- if (keyType === types_1.KeyType.Ed25519) {
81
- sig = ed25519_1.ed25519.sign(action, sk);
82
- }
83
- else if (keyType === types_1.KeyType.Bls12_381) {
84
- sig = bls12_381_1.bls12_381.sign(action, sk);
85
- }
86
- else if (keyType === types_1.KeyType.Secp256k1) {
87
- sig = secp256k1_1.secp256k1.sign((0, sha256_1.sha256)(action), sk).toCompactRawBytes();
88
- }
89
- else {
90
- throw new Error("Invalid key type");
91
- }
92
- return new Uint8Array([...action, ...sig]);
93
- }
94
49
  /**
95
50
  * Constructs wallet signing function, usable with `NordUser` type
96
51
  *
@@ -99,13 +54,13 @@ function signAction(action, sk, keyType) {
99
54
  * then signs it with provided user wallet key and returns signature
100
55
  * as hex string prefixed with `"0x"`
101
56
  */
102
- function makeWalletSignFn(walletKey) {
103
- const signingKey = new ethers_1.ethers.SigningKey(walletKey);
104
- return async (message) => signingKey.sign(ethers_1.ethers.hashMessage(message)).serialized;
57
+ export function makeWalletSignFn(walletKey) {
58
+ const signingKey = new ethers.SigningKey(walletKey);
59
+ return async (message) => signingKey.sign(ethers.hashMessage(message)).serialized;
105
60
  }
106
61
  // Returned numbers do fit into specified bits range, or error is thrown.
107
62
  function makeToScaledBigUint(params) {
108
- const Dec = decimal_js_1.Decimal.clone({
63
+ const Dec = Decimal.clone({
109
64
  precision: params.precision,
110
65
  toExpPos: params.exponent,
111
66
  toExpNeg: -params.exponent,
@@ -141,7 +96,7 @@ function makeToScaledBigUint(params) {
141
96
  * @param decimals Number of decimal digits
142
97
  * @returns Rescaled unsigned integer
143
98
  */
144
- exports.toScaledU64 = makeToScaledBigUint({
99
+ export const toScaledU64 = makeToScaledBigUint({
145
100
  bits: 64,
146
101
  precision: 20,
147
102
  exponent: 28,
@@ -157,7 +112,7 @@ exports.toScaledU64 = makeToScaledBigUint({
157
112
  * @param decimals Number of decimal digits
158
113
  * @returns Rescaled unsigned integer
159
114
  */
160
- exports.toScaledU128 = makeToScaledBigUint({
115
+ export const toScaledU128 = makeToScaledBigUint({
161
116
  bits: 128,
162
117
  precision: 40,
163
118
  exponent: 56,
@@ -170,9 +125,9 @@ exports.toScaledU128 = makeToScaledBigUint({
170
125
  * @param schema Message schema for decoding
171
126
  * @returns Decoded message
172
127
  */
173
- function decodeLengthDelimited(bytes, schema) {
128
+ export function decodeLengthDelimited(bytes, schema) {
174
129
  // use sizeDelimitedPeek to extract the message length and offset
175
- const peekResult = (0, wire_1.sizeDelimitedPeek)(bytes);
130
+ const peekResult = sizeDelimitedPeek(bytes);
176
131
  if (peekResult.size === null || peekResult.offset === null) {
177
132
  throw new Error("Failed to parse size-delimited message");
178
133
  }
@@ -183,43 +138,53 @@ function decodeLengthDelimited(bytes, schema) {
183
138
  throw new Error(`Encoded message size (${peekResult.size} bytes) is greater than remaining buffer size (${bytes.length - peekResult.offset} bytes).`);
184
139
  }
185
140
  // decode the message using the offset and size from peek
186
- return (0, protobuf_1.fromBinary)(schema, bytes.slice(peekResult.offset, peekResult.offset + peekResult.size));
141
+ return fromBinary(schema, bytes.slice(peekResult.offset, peekResult.offset + peekResult.size));
187
142
  }
188
- function checkPubKeyLength(keyType, len) {
189
- if (keyType === types_1.KeyType.Bls12_381) {
190
- throw new Error("Cannot create a user using Bls12_381, use Ed25119 or Secp256k1 instead.");
191
- }
192
- if (len !== 32 && keyType === types_1.KeyType.Ed25519) {
193
- throw new Error("Ed25519 pubkeys must be 32 length.");
194
- }
195
- if (len !== 33 && keyType === types_1.KeyType.Secp256k1) {
196
- throw new Error("Secp256k1 pubkeys must be 33 length.");
197
- }
198
- }
199
- function decodeHex(value) {
143
+ export function decodeHex(value) {
200
144
  const hex = value.startsWith("0x") ? value.slice(2) : value;
201
145
  return Uint8Array.from(Buffer.from(hex, "hex"));
202
146
  }
203
- function findMarket(markets, marketId) {
147
+ export function findMarket(markets, marketId) {
204
148
  if (marketId < 0 || markets.length - 1 < marketId) {
205
149
  throw new Error(`The market with marketId=${marketId} not found`);
206
150
  }
207
151
  return markets[marketId];
208
152
  }
209
- function findToken(tokens, tokenId) {
153
+ export function findToken(tokens, tokenId) {
210
154
  if (tokenId < 0 || tokens.length - 1 < tokenId) {
211
155
  throw new Error(`The token with tokenId=${tokenId} not found`);
212
156
  }
213
157
  return tokens[tokenId];
214
158
  }
215
- function keypairFromPrivateKey(privateKey) {
159
+ export function keypairFromPrivateKey(privateKey) {
216
160
  if (typeof privateKey === "string") {
217
161
  if (!privateKey.startsWith("0x")) {
218
- return web3_js_1.Keypair.fromSecretKey(bs58_1.default.decode(privateKey));
162
+ return Keypair.fromSecretKey(bs58.decode(privateKey));
219
163
  }
220
164
  const hex = privateKey.startsWith("0x") ? privateKey.slice(2) : privateKey;
221
165
  const bytes = new Uint8Array(hex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
222
- return web3_js_1.Keypair.fromSecretKey(bytes);
166
+ return Keypair.fromSecretKey(bytes);
223
167
  }
224
- return web3_js_1.Keypair.fromSecretKey(privateKey);
168
+ return Keypair.fromSecretKey(privateKey);
169
+ }
170
+ export async function signUserPayload({ payload, user, signTransaction, }) {
171
+ const tx = new solana.Transaction({
172
+ blockhash: bs58.encode(new Uint8Array(32)),
173
+ lastValidBlockHeight: 0,
174
+ feePayer: user,
175
+ });
176
+ tx.add(new solana.TransactionInstruction({
177
+ keys: [],
178
+ programId: user,
179
+ data: Buffer.from(payload),
180
+ }));
181
+ const signedTx = await signTransaction(tx);
182
+ const sig = signedTx.signatures[0];
183
+ assert(sig !== undefined, //.
184
+ "signed transaction must have a signature");
185
+ assert(sig.signature !== null, "signature must be non-null; check your signTransaction function");
186
+ assert(sig.signature.length === 64, //.
187
+ "signature must be 64 bytes");
188
+ assert(sig.publicKey.equals(user), `signature is for ${sig.publicKey}, expected ${user}`);
189
+ return sig.signature;
225
190
  }