mmn-client-js 1.0.13-node14 → 1.0.14-node14

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.
package/dist/index.js CHANGED
@@ -1,137 +1,169 @@
1
1
  'use strict';
2
2
 
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
3
5
  var bs58 = require('bs58');
4
6
  var nacl = require('tweetnacl');
5
7
 
6
- const API_FILTER_PARAMS = {
7
- ALL: 0,
8
- SENT: 2,
9
- RECEIVED: 1,
10
- };
11
- class IndexerClient {
12
- constructor(config) {
13
- this.endpoint = config.endpoint;
14
- this.chainId = config.chainId;
15
- this.timeout = config.timeout || 30000;
16
- // Minimal headers to avoid CORS preflight issues
17
- this.headers = {
18
- Accept: 'application/json',
19
- ...(config.headers || {}),
20
- };
21
- }
22
- /**
23
- * Make HTTP request with automatic CORS handling
24
- * Works out-of-the-box without CORS configuration
25
- * @param method - HTTP method (GET or POST)
26
- * @param path - API endpoint path
27
- * @param params - URL query parameters
28
- * @param body - Request body for POST requests
29
- * @returns Promise resolving to response data
30
- */
31
- async makeRequest(method, path, params, body) {
32
- // Build full URL
33
- let url = `${this.endpoint}/${path}`;
34
- // Add query parameters
35
- if (params && Object.keys(params).length > 0) {
36
- const searchParams = new URLSearchParams();
37
- Object.entries(params).forEach(([key, value]) => {
38
- searchParams.append(key, String(value));
39
- });
40
- url += `?${searchParams.toString()}`;
41
- }
42
- // Create AbortController for timeout
43
- const controller = new AbortController();
44
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
45
- try {
46
- // Simple fetch with automatic CORS handling
47
- const requestOptions = {
48
- method,
49
- mode: 'cors',
50
- credentials: 'omit',
51
- signal: controller.signal,
52
- headers: {
53
- Accept: 'application/json',
54
- ...this.headers,
55
- },
56
- };
57
- // Add body and Content-Type for POST requests
58
- if (method === 'POST' && body) {
59
- requestOptions.body = JSON.stringify(body);
60
- requestOptions.headers['Content-Type'] =
61
- 'application/json';
62
- }
63
- const response = await fetch(url, requestOptions);
64
- clearTimeout(timeoutId);
65
- // Handle response errors
66
- if (!response.ok) {
67
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
68
- }
69
- // Parse JSON response
70
- const data = await response.json();
71
- return data;
72
- }
73
- catch (error) {
74
- clearTimeout(timeoutId);
75
- if (error instanceof Error) {
76
- if (error.name === 'AbortError') {
77
- throw new Error(`Request timeout after ${this.timeout}ms`);
78
- }
79
- throw error;
80
- }
81
- throw new Error('Request failed');
82
- }
83
- }
84
- async getTransactionByHash(hash) {
85
- const path = `${this.chainId}/tx/${hash}/detail`;
86
- const res = await this.makeRequest('GET', path);
87
- return res.data.transaction;
88
- }
89
- async getTransactionByWallet(wallet, page = 1, limit = 50, filter, sortBy = 'transaction_timestamp', sortOrder = 'desc') {
90
- if (!wallet) {
91
- throw new Error('wallet address cannot be empty');
92
- }
93
- if (page < 1)
94
- page = 1;
95
- if (limit <= 0)
96
- limit = 50;
97
- if (limit > 1000)
98
- limit = 1000;
99
- const params = {
100
- page: page - 1,
101
- limit,
102
- sort_by: sortBy,
103
- sort_order: sortOrder,
104
- };
105
- switch (filter) {
106
- case API_FILTER_PARAMS.ALL:
107
- params['wallet_address'] = wallet;
108
- break;
109
- case API_FILTER_PARAMS.SENT:
110
- params['filter_from_address'] = wallet;
111
- break;
112
- case API_FILTER_PARAMS.RECEIVED:
113
- params['filter_to_address'] = wallet;
114
- break;
115
- }
116
- const path = `${this.chainId}/transactions`;
117
- return this.makeRequest('GET', path, params);
118
- }
119
- async getWalletDetail(wallet) {
120
- if (!wallet) {
121
- throw new Error('wallet address cannot be empty');
122
- }
123
- const path = `${this.chainId}/wallets/${wallet}/detail`;
124
- const res = await this.makeRequest('GET', path);
125
- return res.data;
126
- }
8
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
+
10
+ var bs58__default = /*#__PURE__*/_interopDefaultLegacy(bs58);
11
+ var nacl__default = /*#__PURE__*/_interopDefaultLegacy(nacl);
12
+
13
+ // Fetch and AbortController polyfills for Node 14 compatibility
14
+ /* eslint-disable @typescript-eslint/no-require-imports */
15
+ let fetchPolyfill;
16
+ let AbortControllerPolyfill;
17
+ if (typeof fetch === 'undefined') {
18
+ try {
19
+ // Use node-fetch in Node.js environments that don't have global fetch
20
+ fetchPolyfill = require('node-fetch');
21
+ }
22
+ catch {
23
+ throw new Error('node-fetch is required for Node 14 compatibility. Please install it: npm install node-fetch@2');
24
+ }
25
+ }
26
+ else {
27
+ fetchPolyfill = fetch;
28
+ }
29
+ if (typeof AbortController === 'undefined') {
30
+ try {
31
+ // Use abort-controller in environments that don't have AbortController
32
+ AbortControllerPolyfill = require('abort-controller');
33
+ }
34
+ catch {
35
+ throw new Error('abort-controller is required for Node 14 compatibility. Please install it: npm install abort-controller');
36
+ }
37
+ }
38
+ else {
39
+ AbortControllerPolyfill = AbortController;
127
40
  }
128
41
 
129
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
130
-
131
- function getDefaultExportFromCjs (x) {
132
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
42
+ const API_FILTER_PARAMS = {
43
+ ALL: 0,
44
+ SENT: 2,
45
+ RECEIVED: 1,
46
+ };
47
+ class IndexerClient {
48
+ constructor(config) {
49
+ this.endpoint = config.endpoint;
50
+ this.chainId = config.chainId;
51
+ this.timeout = config.timeout || 30000;
52
+ // Minimal headers to avoid CORS preflight issues
53
+ this.headers = {
54
+ Accept: 'application/json',
55
+ ...(config.headers || {}),
56
+ };
57
+ }
58
+ /**
59
+ * Make HTTP request with automatic CORS handling
60
+ * Works out-of-the-box without CORS configuration
61
+ * @param method - HTTP method (GET or POST)
62
+ * @param path - API endpoint path
63
+ * @param params - URL query parameters
64
+ * @param body - Request body for POST requests
65
+ * @returns Promise resolving to response data
66
+ */
67
+ async makeRequest(method, path, params, body) {
68
+ // Build full URL
69
+ let url = `${this.endpoint}/${path}`;
70
+ // Add query parameters
71
+ if (params && Object.keys(params).length > 0) {
72
+ const searchParams = new URLSearchParams();
73
+ Object.entries(params).forEach(([key, value]) => {
74
+ searchParams.append(key, String(value));
75
+ });
76
+ url += `?${searchParams.toString()}`;
77
+ }
78
+ // Create AbortController for timeout
79
+ const controller = new AbortControllerPolyfill();
80
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
81
+ try {
82
+ // Simple fetch with automatic CORS handling
83
+ const requestOptions = {
84
+ method,
85
+ mode: 'cors',
86
+ credentials: 'omit',
87
+ signal: controller.signal,
88
+ headers: {
89
+ Accept: 'application/json',
90
+ ...this.headers,
91
+ },
92
+ };
93
+ // Add body and Content-Type for POST requests
94
+ if (method === 'POST' && body) {
95
+ requestOptions.body = JSON.stringify(body);
96
+ requestOptions.headers['Content-Type'] =
97
+ 'application/json';
98
+ }
99
+ const response = await fetchPolyfill(url, requestOptions);
100
+ clearTimeout(timeoutId);
101
+ // Handle response errors
102
+ if (!response.ok) {
103
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
104
+ }
105
+ // Parse JSON response
106
+ const data = await response.json();
107
+ return data;
108
+ }
109
+ catch (error) {
110
+ clearTimeout(timeoutId);
111
+ if (error instanceof Error) {
112
+ if (error.name === 'AbortError') {
113
+ throw new Error(`Request timeout after ${this.timeout}ms`);
114
+ }
115
+ throw error;
116
+ }
117
+ throw new Error('Request failed');
118
+ }
119
+ }
120
+ async getTransactionByHash(hash) {
121
+ const path = `${this.chainId}/tx/${hash}/detail`;
122
+ const res = await this.makeRequest('GET', path);
123
+ return res.data.transaction;
124
+ }
125
+ async getTransactionByWallet(wallet, page = 1, limit = 50, filter, sortBy = 'transaction_timestamp', sortOrder = 'desc') {
126
+ if (!wallet) {
127
+ throw new Error('wallet address cannot be empty');
128
+ }
129
+ if (page < 1)
130
+ page = 1;
131
+ if (limit <= 0)
132
+ limit = 50;
133
+ if (limit > 1000)
134
+ limit = 1000;
135
+ const params = {
136
+ page: page - 1,
137
+ limit,
138
+ sort_by: sortBy,
139
+ sort_order: sortOrder,
140
+ };
141
+ switch (filter) {
142
+ case API_FILTER_PARAMS.ALL:
143
+ params['wallet_address'] = wallet;
144
+ break;
145
+ case API_FILTER_PARAMS.SENT:
146
+ params['filter_from_address'] = wallet;
147
+ break;
148
+ case API_FILTER_PARAMS.RECEIVED:
149
+ params['filter_to_address'] = wallet;
150
+ break;
151
+ }
152
+ const path = `${this.chainId}/transactions`;
153
+ return this.makeRequest('GET', path, params);
154
+ }
155
+ async getWalletDetail(wallet) {
156
+ if (!wallet) {
157
+ throw new Error('wallet address cannot be empty');
158
+ }
159
+ const path = `${this.chainId}/wallets/${wallet}/detail`;
160
+ const res = await this.makeRequest('GET', path);
161
+ return res.data;
162
+ }
133
163
  }
134
164
 
165
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
166
+
135
167
  var cryptoJs = {exports: {}};
136
168
 
137
169
  function commonjsRequire(path) {
@@ -944,8 +976,8 @@ function requireCore () {
944
976
 
945
977
  return CryptoJS;
946
978
 
947
- }));
948
- } (core));
979
+ }));
980
+ } (core));
949
981
  return core.exports;
950
982
  }
951
983
 
@@ -1252,8 +1284,8 @@ function requireX64Core () {
1252
1284
 
1253
1285
  return CryptoJS;
1254
1286
 
1255
- }));
1256
- } (x64Core));
1287
+ }));
1288
+ } (x64Core));
1257
1289
  return x64Core.exports;
1258
1290
  }
1259
1291
 
@@ -1332,8 +1364,8 @@ function requireLibTypedarrays () {
1332
1364
 
1333
1365
  return CryptoJS.lib.WordArray;
1334
1366
 
1335
- }));
1336
- } (libTypedarrays));
1367
+ }));
1368
+ } (libTypedarrays));
1337
1369
  return libTypedarrays.exports;
1338
1370
  }
1339
1371
 
@@ -1485,8 +1517,8 @@ function requireEncUtf16 () {
1485
1517
 
1486
1518
  return CryptoJS.enc.Utf16;
1487
1519
 
1488
- }));
1489
- } (encUtf16));
1520
+ }));
1521
+ } (encUtf16));
1490
1522
  return encUtf16.exports;
1491
1523
  }
1492
1524
 
@@ -1625,8 +1657,8 @@ function requireEncBase64 () {
1625
1657
 
1626
1658
  return CryptoJS.enc.Base64;
1627
1659
 
1628
- }));
1629
- } (encBase64));
1660
+ }));
1661
+ } (encBase64));
1630
1662
  return encBase64.exports;
1631
1663
  }
1632
1664
 
@@ -1777,8 +1809,8 @@ function requireEncBase64url () {
1777
1809
 
1778
1810
  return CryptoJS.enc.Base64url;
1779
1811
 
1780
- }));
1781
- } (encBase64url));
1812
+ }));
1813
+ } (encBase64url));
1782
1814
  return encBase64url.exports;
1783
1815
  }
1784
1816
 
@@ -2049,8 +2081,8 @@ function requireMd5 () {
2049
2081
 
2050
2082
  return CryptoJS.MD5;
2051
2083
 
2052
- }));
2053
- } (md5));
2084
+ }));
2085
+ } (md5));
2054
2086
  return md5.exports;
2055
2087
  }
2056
2088
 
@@ -2203,8 +2235,8 @@ function requireSha1 () {
2203
2235
 
2204
2236
  return CryptoJS.SHA1;
2205
2237
 
2206
- }));
2207
- } (sha1));
2238
+ }));
2239
+ } (sha1));
2208
2240
  return sha1.exports;
2209
2241
  }
2210
2242
 
@@ -2406,8 +2438,8 @@ function requireSha256 () {
2406
2438
 
2407
2439
  return CryptoJS.SHA256;
2408
2440
 
2409
- }));
2410
- } (sha256));
2441
+ }));
2442
+ } (sha256));
2411
2443
  return sha256.exports;
2412
2444
  }
2413
2445
 
@@ -2490,8 +2522,8 @@ function requireSha224 () {
2490
2522
 
2491
2523
  return CryptoJS.SHA224;
2492
2524
 
2493
- }));
2494
- } (sha224));
2525
+ }));
2526
+ } (sha224));
2495
2527
  return sha224.exports;
2496
2528
  }
2497
2529
 
@@ -2820,8 +2852,8 @@ function requireSha512 () {
2820
2852
 
2821
2853
  return CryptoJS.SHA512;
2822
2854
 
2823
- }));
2824
- } (sha512));
2855
+ }));
2856
+ } (sha512));
2825
2857
  return sha512.exports;
2826
2858
  }
2827
2859
 
@@ -2907,8 +2939,8 @@ function requireSha384 () {
2907
2939
 
2908
2940
  return CryptoJS.SHA384;
2909
2941
 
2910
- }));
2911
- } (sha384));
2942
+ }));
2943
+ } (sha384));
2912
2944
  return sha384.exports;
2913
2945
  }
2914
2946
 
@@ -3237,8 +3269,8 @@ function requireSha3 () {
3237
3269
 
3238
3270
  return CryptoJS.SHA3;
3239
3271
 
3240
- }));
3241
- } (sha3));
3272
+ }));
3273
+ } (sha3));
3242
3274
  return sha3.exports;
3243
3275
  }
3244
3276
 
@@ -3508,8 +3540,8 @@ function requireRipemd160 () {
3508
3540
 
3509
3541
  return CryptoJS.RIPEMD160;
3510
3542
 
3511
- }));
3512
- } (ripemd160));
3543
+ }));
3544
+ } (ripemd160));
3513
3545
  return ripemd160.exports;
3514
3546
  }
3515
3547
 
@@ -3655,8 +3687,8 @@ function requireHmac () {
3655
3687
  }());
3656
3688
 
3657
3689
 
3658
- }));
3659
- } (hmac));
3690
+ }));
3691
+ } (hmac));
3660
3692
  return hmac.exports;
3661
3693
  }
3662
3694
 
@@ -3804,8 +3836,8 @@ function requirePbkdf2 () {
3804
3836
 
3805
3837
  return CryptoJS.PBKDF2;
3806
3838
 
3807
- }));
3808
- } (pbkdf2));
3839
+ }));
3840
+ } (pbkdf2));
3809
3841
  return pbkdf2.exports;
3810
3842
  }
3811
3843
 
@@ -3942,8 +3974,8 @@ function requireEvpkdf () {
3942
3974
 
3943
3975
  return CryptoJS.EvpKDF;
3944
3976
 
3945
- }));
3946
- } (evpkdf));
3977
+ }));
3978
+ } (evpkdf));
3947
3979
  return evpkdf.exports;
3948
3980
  }
3949
3981
 
@@ -4166,7 +4198,7 @@ function requireCipherCore () {
4166
4198
  C_lib.StreamCipher = Cipher.extend({
4167
4199
  _doFinalize: function () {
4168
4200
  // Process partial blocks
4169
- var finalProcessedBlocks = this._process(true);
4201
+ var finalProcessedBlocks = this._process(!!'flush');
4170
4202
 
4171
4203
  return finalProcessedBlocks;
4172
4204
  },
@@ -4447,10 +4479,10 @@ function requireCipherCore () {
4447
4479
  padding.pad(this._data, this.blockSize);
4448
4480
 
4449
4481
  // Process final blocks
4450
- finalProcessedBlocks = this._process(true);
4482
+ finalProcessedBlocks = this._process(!!'flush');
4451
4483
  } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
4452
4484
  // Process final blocks
4453
- finalProcessedBlocks = this._process(true);
4485
+ finalProcessedBlocks = this._process(!!'flush');
4454
4486
 
4455
4487
  // Unpad data
4456
4488
  padding.unpad(finalProcessedBlocks);
@@ -4841,8 +4873,8 @@ function requireCipherCore () {
4841
4873
  }());
4842
4874
 
4843
4875
 
4844
- }));
4845
- } (cipherCore));
4876
+ }));
4877
+ } (cipherCore));
4846
4878
  return cipherCore.exports;
4847
4879
  }
4848
4880
 
@@ -4925,8 +4957,8 @@ function requireModeCfb () {
4925
4957
 
4926
4958
  return CryptoJS.mode.CFB;
4927
4959
 
4928
- }));
4929
- } (modeCfb));
4960
+ }));
4961
+ } (modeCfb));
4930
4962
  return modeCfb.exports;
4931
4963
  }
4932
4964
 
@@ -4987,8 +5019,8 @@ function requireModeCtr () {
4987
5019
 
4988
5020
  return CryptoJS.mode.CTR;
4989
5021
 
4990
- }));
4991
- } (modeCtr));
5022
+ }));
5023
+ } (modeCtr));
4992
5024
  return modeCtr.exports;
4993
5025
  }
4994
5026
 
@@ -5107,8 +5139,8 @@ function requireModeCtrGladman () {
5107
5139
 
5108
5140
  return CryptoJS.mode.CTRGladman;
5109
5141
 
5110
- }));
5111
- } (modeCtrGladman));
5142
+ }));
5143
+ } (modeCtrGladman));
5112
5144
  return modeCtrGladman.exports;
5113
5145
  }
5114
5146
 
@@ -5165,8 +5197,8 @@ function requireModeOfb () {
5165
5197
 
5166
5198
  return CryptoJS.mode.OFB;
5167
5199
 
5168
- }));
5169
- } (modeOfb));
5200
+ }));
5201
+ } (modeOfb));
5170
5202
  return modeOfb.exports;
5171
5203
  }
5172
5204
 
@@ -5209,8 +5241,8 @@ function requireModeEcb () {
5209
5241
 
5210
5242
  return CryptoJS.mode.ECB;
5211
5243
 
5212
- }));
5213
- } (modeEcb));
5244
+ }));
5245
+ } (modeEcb));
5214
5246
  return modeEcb.exports;
5215
5247
  }
5216
5248
 
@@ -5262,8 +5294,8 @@ function requirePadAnsix923 () {
5262
5294
 
5263
5295
  return CryptoJS.pad.Ansix923;
5264
5296
 
5265
- }));
5266
- } (padAnsix923));
5297
+ }));
5298
+ } (padAnsix923));
5267
5299
  return padAnsix923.exports;
5268
5300
  }
5269
5301
 
@@ -5310,8 +5342,8 @@ function requirePadIso10126 () {
5310
5342
 
5311
5343
  return CryptoJS.pad.Iso10126;
5312
5344
 
5313
- }));
5314
- } (padIso10126));
5345
+ }));
5346
+ } (padIso10126));
5315
5347
  return padIso10126.exports;
5316
5348
  }
5317
5349
 
@@ -5354,8 +5386,8 @@ function requirePadIso97971 () {
5354
5386
 
5355
5387
  return CryptoJS.pad.Iso97971;
5356
5388
 
5357
- }));
5358
- } (padIso97971));
5389
+ }));
5390
+ } (padIso97971));
5359
5391
  return padIso97971.exports;
5360
5392
  }
5361
5393
 
@@ -5405,8 +5437,8 @@ function requirePadZeropadding () {
5405
5437
 
5406
5438
  return CryptoJS.pad.ZeroPadding;
5407
5439
 
5408
- }));
5409
- } (padZeropadding));
5440
+ }));
5441
+ } (padZeropadding));
5410
5442
  return padZeropadding.exports;
5411
5443
  }
5412
5444
 
@@ -5439,8 +5471,8 @@ function requirePadNopadding () {
5439
5471
 
5440
5472
  return CryptoJS.pad.NoPadding;
5441
5473
 
5442
- }));
5443
- } (padNopadding));
5474
+ }));
5475
+ } (padNopadding));
5444
5476
  return padNopadding.exports;
5445
5477
  }
5446
5478
 
@@ -5509,8 +5541,8 @@ function requireFormatHex () {
5509
5541
 
5510
5542
  return CryptoJS.format.Hex;
5511
5543
 
5512
- }));
5513
- } (formatHex));
5544
+ }));
5545
+ } (formatHex));
5514
5546
  return formatHex.exports;
5515
5547
  }
5516
5548
 
@@ -5747,8 +5779,8 @@ function requireAes () {
5747
5779
 
5748
5780
  return CryptoJS.AES;
5749
5781
 
5750
- }));
5751
- } (aes));
5782
+ }));
5783
+ } (aes));
5752
5784
  return aes.exports;
5753
5785
  }
5754
5786
 
@@ -6530,8 +6562,8 @@ function requireTripledes () {
6530
6562
 
6531
6563
  return CryptoJS.TripleDES;
6532
6564
 
6533
- }));
6534
- } (tripledes));
6565
+ }));
6566
+ } (tripledes));
6535
6567
  return tripledes.exports;
6536
6568
  }
6537
6569
 
@@ -6673,8 +6705,8 @@ function requireRc4 () {
6673
6705
 
6674
6706
  return CryptoJS.RC4;
6675
6707
 
6676
- }));
6677
- } (rc4));
6708
+ }));
6709
+ } (rc4));
6678
6710
  return rc4.exports;
6679
6711
  }
6680
6712
 
@@ -6869,8 +6901,8 @@ function requireRabbit () {
6869
6901
 
6870
6902
  return CryptoJS.Rabbit;
6871
6903
 
6872
- }));
6873
- } (rabbit));
6904
+ }));
6905
+ } (rabbit));
6874
6906
  return rabbit.exports;
6875
6907
  }
6876
6908
 
@@ -7063,8 +7095,8 @@ function requireRabbitLegacy () {
7063
7095
 
7064
7096
  return CryptoJS.RabbitLegacy;
7065
7097
 
7066
- }));
7067
- } (rabbitLegacy));
7098
+ }));
7099
+ } (rabbitLegacy));
7068
7100
  return rabbitLegacy.exports;
7069
7101
  }
7070
7102
 
@@ -7538,8 +7570,8 @@ function requireBlowfish () {
7538
7570
 
7539
7571
  return CryptoJS.Blowfish;
7540
7572
 
7541
- }));
7542
- } (blowfish));
7573
+ }));
7574
+ } (blowfish));
7543
7575
  return blowfish.exports;
7544
7576
  }
7545
7577
 
@@ -7553,623 +7585,621 @@ function requireBlowfish () {
7553
7585
 
7554
7586
  return CryptoJS;
7555
7587
 
7556
- }));
7588
+ }));
7557
7589
  } (cryptoJs));
7558
7590
 
7559
- var cryptoJsExports = cryptoJs.exports;
7560
- var CryptoJS = /*@__PURE__*/getDefaultExportFromCjs(cryptoJsExports);
7561
-
7562
- // MMN Client
7563
- // This client provides a complete interface for interacting with MMN blockchain
7564
- // Buffer polyfill for mobile environments
7565
- class BufferPolyfill {
7566
- static isBuffer(obj) {
7567
- if (typeof Buffer !== 'undefined' && Buffer.isBuffer) {
7568
- return Buffer.isBuffer(obj);
7569
- }
7570
- return obj instanceof Uint8Array;
7571
- }
7572
- static from(data, encoding) {
7573
- if (typeof Buffer !== 'undefined' && Buffer.from) {
7574
- return Buffer.from(data, encoding);
7575
- }
7576
- let result;
7577
- if (Array.isArray(data)) {
7578
- result = new Uint8Array(data);
7579
- }
7580
- else if (typeof data === 'string') {
7581
- if (encoding === 'hex') {
7582
- const bytes = [];
7583
- for (let i = 0; i < data.length; i += 2) {
7584
- bytes.push(parseInt(data.substr(i, 2), 16));
7585
- }
7586
- result = new Uint8Array(bytes);
7587
- }
7588
- else {
7589
- // UTF-8 encoding
7590
- const encoder = new TextEncoder();
7591
- result = encoder.encode(data);
7592
- }
7593
- }
7594
- else if (data instanceof Uint8Array) {
7595
- result = data;
7596
- }
7597
- else {
7598
- result = new Uint8Array(data);
7599
- }
7600
- // Add toString method
7601
- result.toString = function (encoding) {
7602
- if (encoding === 'hex') {
7603
- return Array.from(this)
7604
- .map((b) => b.toString(16).padStart(2, '0'))
7605
- .join('');
7606
- }
7607
- else if (encoding === 'base64') {
7608
- // Simple base64 encoding
7609
- const bytes = this;
7610
- let binary = '';
7611
- for (let i = 0; i < bytes.length; i++) {
7612
- binary += String.fromCharCode(bytes[i]);
7613
- }
7614
- return btoa(binary);
7615
- }
7616
- else {
7617
- // UTF-8 decoding
7618
- const decoder = new TextDecoder();
7619
- return decoder.decode(this);
7620
- }
7621
- };
7622
- return result;
7623
- }
7624
- static concat(arrays) {
7625
- if (typeof Buffer !== 'undefined' && Buffer.concat) {
7626
- return Buffer.concat(arrays);
7627
- }
7628
- const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
7629
- const result = new Uint8Array(totalLength);
7630
- let offset = 0;
7631
- for (const arr of arrays) {
7632
- result.set(arr, offset);
7633
- offset += arr.length;
7634
- }
7635
- // Add toString method
7636
- result.toString = function (encoding) {
7637
- if (encoding === 'hex') {
7638
- return Array.from(this)
7639
- .map((b) => b.toString(16).padStart(2, '0'))
7640
- .join('');
7641
- }
7642
- else {
7643
- const decoder = new TextDecoder();
7644
- return decoder.decode(this);
7645
- }
7646
- };
7647
- return result;
7648
- }
7649
- }
7650
- // Use polyfill if Buffer is not available
7651
- const BufferCompat = typeof Buffer !== 'undefined' ? Buffer : BufferPolyfill;
7652
- // Cryptographic constants
7653
- const CRYPTO_CONSTANTS = {
7654
- ED25519_PRIVATE_KEY_LENGTH: 32,
7655
- ED25519_PUBLIC_KEY_LENGTH: 32,
7656
- MNEMONIC_ENTROPY_BITS: 128,
7657
- PKCS8_VERSION: 0,
7658
- // ASN.1 DER encoding
7659
- ASN1_SEQUENCE_TAG: 0x30,
7660
- ASN1_OCTET_STRING_TAG: 0x04,
7661
- ASN1_INTEGER_TAG: 0x02,
7662
- ASN1_LENGTH: 0x80,
7663
- // Ed25519 OID bytes: 1.3.101.112 (RFC 8410)
7664
- ED25519_OID_BYTES: [0x06, 0x03, 0x2b, 0x65, 0x70],
7665
- // PKCS#8 structure length constants
7666
- PKCS8_ALGORITHM_ID_LENGTH: 0x0b, // SEQUENCE length for algorithm identifier
7667
- PKCS8_PRIVATE_KEY_OCTET_OUTER_LENGTH: 0x22, // Outer OCTET STRING length (34 bytes)
7668
- PKCS8_PRIVATE_KEY_OCTET_INNER_LENGTH: 0x20, // Inner OCTET STRING length (32 bytes)
7669
- };
7670
- // PRNG (Pseudo-Random Number Generator) constants
7671
- const PRNG_CONSTANTS = {
7672
- // Numerical Recipes LCG
7673
- LCG_MULTIPLIER: 1664525, // LCG multiplier (from Numerical Recipes)
7674
- LCG_INCREMENT: 1013904223, // LCG increment
7675
- LCG_MODULUS: 4294967296, // 2^32 modulus for LCG
7676
- TIMESTAMP_MULTIPLIER: 2654435761, // Golden Ratio constant
7677
- HASH_SUBSTRING_LENGTH: 8,
7678
- BYTE_SHIFT: 24,
7679
- BYTE_MASK: 0xff,
7680
- };
7681
- const TX_TYPE = {
7682
- TRANSFER: 0,
7683
- PRIVATE_KEY: 1,
7684
- };
7685
- const DECIMALS = 6;
7686
- class MmnClient {
7687
- constructor(config) {
7688
- this.requestId = 0;
7689
- this.config = {
7690
- timeout: 30000,
7691
- headers: {
7692
- 'Content-Type': 'application/json',
7693
- Accept: 'application/json',
7694
- },
7695
- ...config,
7696
- };
7697
- }
7698
- async makeRequest(method, params) {
7699
- const request = {
7700
- jsonrpc: '2.0',
7701
- method,
7702
- params,
7703
- id: ++this.requestId,
7704
- };
7705
- // Create AbortController for timeout
7706
- const controller = new AbortController();
7707
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout || 30000);
7708
- try {
7709
- const requestOptions = {
7710
- method: 'POST',
7711
- mode: 'cors',
7712
- credentials: 'omit',
7713
- signal: controller.signal,
7714
- headers: this.config.headers || {},
7715
- body: JSON.stringify(request),
7716
- };
7717
- const response = await fetch(this.config.baseUrl, requestOptions);
7718
- clearTimeout(timeoutId);
7719
- if (!response.ok) {
7720
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
7721
- }
7722
- const result = await response.json();
7723
- if (result.error) {
7724
- throw new Error(`JSON-RPC Error ${result.error.code}: ${result.error.message}`);
7725
- }
7726
- return result.result;
7727
- }
7728
- catch (error) {
7729
- clearTimeout(timeoutId);
7730
- if (error instanceof Error) {
7731
- if (error.name === 'AbortError') {
7732
- throw new Error(`Request timeout after ${this.config.timeout || 30000}ms`);
7733
- }
7734
- throw error;
7735
- }
7736
- throw new Error('Unknown error occurred');
7737
- }
7738
- }
7739
- /**
7740
- * Securely convert raw Ed25519 private key to PKCS#8 format
7741
- * @param raw - Raw 32-byte Ed25519 private key
7742
- * @returns PKCS#8 formatted private key in hex
7743
- * @throws Error if input validation fails
7744
- */
7745
- rawEd25519ToPkcs8Hex(raw) {
7746
- // Input validation
7747
- if (!BufferCompat.isBuffer(raw)) {
7748
- throw new Error('Private key must be a Buffer');
7749
- }
7750
- if (raw.length !== CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH) {
7751
- throw new Error(`Ed25519 private key must be exactly ${CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH} bytes`);
7752
- }
7753
- try {
7754
- // Ed25519 OID: 1.3.101.112 (RFC 8410 - Algorithm Identifiers for Ed25519)
7755
- const ED25519_OID = BufferCompat.from(CRYPTO_CONSTANTS.ED25519_OID_BYTES);
7756
- const VERSION_BYTES = BufferCompat.from([
7757
- CRYPTO_CONSTANTS.ASN1_INTEGER_TAG,
7758
- 0x01, // Length of integer (1 byte)
7759
- CRYPTO_CONSTANTS.PKCS8_VERSION,
7760
- ]);
7761
- // Create algorithm identifier sequence (AlgorithmIdentifier)
7762
- const algorithmId = BufferCompat.concat([
7763
- BufferCompat.from([
7764
- CRYPTO_CONSTANTS.ASN1_SEQUENCE_TAG,
7765
- CRYPTO_CONSTANTS.PKCS8_ALGORITHM_ID_LENGTH,
7766
- ]),
7767
- ED25519_OID,
7768
- ]);
7769
- // Create private key octet string (wrapped Ed25519 private key)
7770
- const privateKeyOctetString = BufferCompat.concat([
7771
- BufferCompat.from([
7772
- CRYPTO_CONSTANTS.ASN1_OCTET_STRING_TAG,
7773
- CRYPTO_CONSTANTS.PKCS8_PRIVATE_KEY_OCTET_OUTER_LENGTH,
7774
- ]), // OCTET STRING, length 34
7775
- BufferCompat.from([
7776
- CRYPTO_CONSTANTS.ASN1_OCTET_STRING_TAG,
7777
- CRYPTO_CONSTANTS.PKCS8_PRIVATE_KEY_OCTET_INNER_LENGTH,
7778
- ]), // inner OCTET STRING, length 32
7779
- raw,
7780
- ]);
7781
- // Create PKCS#8 body
7782
- const pkcs8Body = BufferCompat.concat([
7783
- VERSION_BYTES,
7784
- algorithmId,
7785
- privateKeyOctetString,
7786
- ]);
7787
- // Create final PKCS#8 structure
7788
- const pkcs8 = BufferCompat.concat([
7789
- BufferCompat.from([CRYPTO_CONSTANTS.ASN1_SEQUENCE_TAG]), // SEQUENCE
7790
- this.encodeLength(pkcs8Body.length),
7791
- pkcs8Body,
7792
- ]);
7793
- const result = pkcs8.toString('hex');
7794
- // Clear sensitive data from memory
7795
- raw.fill(0);
7796
- privateKeyOctetString.fill(0);
7797
- pkcs8Body.fill(0);
7798
- pkcs8.fill(0);
7799
- return result;
7800
- }
7801
- catch (error) {
7802
- // Clear sensitive data on error
7803
- raw.fill(0);
7804
- throw new Error(`Failed to convert private key to PKCS#8: ${error instanceof Error ? error.message : 'Unknown error'}`);
7805
- }
7806
- }
7807
- /**
7808
- * Encode length in ASN.1 DER format
7809
- * ASN.1 length encoding rules:
7810
- * - Short form (0-127): single byte with the length value
7811
- * - Long form (128+): first byte is 0x80 + number of length bytes, followed by length bytes
7812
- * @param length - The length value to encode
7813
- * @returns ASN.1 DER encoded length bytes
7814
- */
7815
- encodeLength(length) {
7816
- if (length < CRYPTO_CONSTANTS.ASN1_LENGTH) {
7817
- return BufferCompat.from([length]);
7818
- }
7819
- const bytes = [];
7820
- let len = length;
7821
- while (len > 0) {
7822
- bytes.unshift(len & PRNG_CONSTANTS.BYTE_MASK);
7823
- len >>= 8;
7824
- }
7825
- return BufferCompat.from([
7826
- CRYPTO_CONSTANTS.ASN1_LENGTH | bytes.length,
7827
- ...bytes,
7828
- ]);
7829
- }
7830
- /**
7831
- * Generate secure entropy using multiple sources for maximum compatibility
7832
- * @returns Array of 32 random bytes
7833
- */
7834
- generateSecureEntropy() {
7835
- const entropy = [];
7836
- const targetLength = CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH;
7837
- // Use multiple entropy sources
7838
- const now = Date.now();
7839
- const performance = typeof window !== 'undefined' && window.performance
7840
- ? window.performance.now()
7841
- : now;
7842
- const random = Math.random();
7843
- // Create initial seed from timestamp and random
7844
- let seed = now + performance + random;
7845
- // Generate bytes using Linear Congruential Generator (LCG) with multiple entropy sources
7846
- // This provides a fallback Pseudorandom Number Generator (PRNG) when crypto.getRandomValues is not available
7847
- for (let i = 0; i < targetLength; i++) {
7848
- // Xₙ₊₁ = (a * Xₙ + c) mod m
7849
- seed =
7850
- (seed * PRNG_CONSTANTS.LCG_MULTIPLIER + PRNG_CONSTANTS.LCG_INCREMENT) %
7851
- PRNG_CONSTANTS.LCG_MODULUS;
7852
- // Mix with timestamp to add time-based entropy
7853
- seed ^= (now + i) * PRNG_CONSTANTS.TIMESTAMP_MULTIPLIER;
7854
- // Mix with Math.random() for additional browser-provided randomness
7855
- seed ^= Math.floor(Math.random() * PRNG_CONSTANTS.LCG_MODULUS);
7856
- // Additional cryptographic mixing using SHA256 if CryptoJS is available
7857
- if (typeof CryptoJS !== 'undefined') {
7858
- const hashInput = seed.toString() + i.toString() + now.toString();
7859
- const hash = CryptoJS.SHA256(hashInput).toString();
7860
- // Extract first 8 hex characters (32 bits) from hash for mixing
7861
- seed ^= parseInt(hash.substring(0, PRNG_CONSTANTS.HASH_SUBSTRING_LENGTH), 16);
7862
- }
7863
- entropy.push((seed >>> PRNG_CONSTANTS.BYTE_SHIFT) & PRNG_CONSTANTS.BYTE_MASK);
7864
- }
7865
- return entropy;
7866
- }
7867
- /**
7868
- * Securely generate ephemeral key pair with proper entropy
7869
- * React Native compatible version with multiple fallbacks
7870
- * @returns Ephemeral key pair with private and public keys
7871
- * @throws Error if key generation fails
7872
- */
7873
- generateEphemeralKeyPair() {
7874
- try {
7875
- let seed;
7876
- // Try multiple approaches for mobile compatibility
7877
- try {
7878
- // Method 1: Try nacl.randomBytes first
7879
- seed = nacl.randomBytes(CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH);
7880
- }
7881
- catch (naclError) {
7882
- try {
7883
- // Method 2: Use crypto.getRandomValues if available (browsers/React Native)
7884
- if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
7885
- seed = new Uint8Array(CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH);
7886
- crypto.getRandomValues(seed);
7887
- }
7888
- else {
7889
- throw new Error('crypto.getRandomValues not available');
7890
- }
7891
- }
7892
- catch (cryptoError) {
7893
- // Method 3: Fallback to secure pseudo-random generation
7894
- const entropy = this.generateSecureEntropy();
7895
- seed = new Uint8Array(entropy);
7896
- }
7897
- }
7898
- // Validate seed length
7899
- if (seed.length !== CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH) {
7900
- throw new Error(`Invalid seed length: expected ${CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH}, got ${seed.length}`);
7901
- }
7902
- // Generate key pair from seed
7903
- const keyPair = nacl.sign.keyPair.fromSeed(seed);
7904
- const publicKeyBytes = keyPair.publicKey;
7905
- // Validate public key
7906
- if (publicKeyBytes.length !== CRYPTO_CONSTANTS.ED25519_PUBLIC_KEY_LENGTH) {
7907
- throw new Error(`Invalid public key length: expected ${CRYPTO_CONSTANTS.ED25519_PUBLIC_KEY_LENGTH}, got ${publicKeyBytes.length}`);
7908
- }
7909
- // Convert private key to PKCS#8 format
7910
- const privateKeyHex = this.rawEd25519ToPkcs8Hex(BufferCompat.from(seed));
7911
- // Clear sensitive data
7912
- seed.fill(0);
7913
- keyPair.secretKey.fill(0);
7914
- return {
7915
- privateKey: privateKeyHex,
7916
- publicKey: bs58.encode(publicKeyBytes),
7917
- };
7918
- }
7919
- catch (error) {
7920
- throw new Error(`Failed to generate ephemeral key pair: ${error instanceof Error ? error.message : 'Unknown error'}`);
7921
- }
7922
- }
7923
- getAddressFromUserId(userId) {
7924
- // Use crypto-js for SHA-256 in React Native
7925
- const hash = CryptoJS.SHA256(userId).toString(CryptoJS.enc.Hex);
7926
- const hashBuffer = BufferCompat.from(hash, 'hex');
7927
- return bs58.encode(hashBuffer);
7928
- }
7929
- /**
7930
- * Create and sign a transaction message
7931
- */
7932
- createAndSignTx(params) {
7933
- if (!this.validateAddress(params.sender)) {
7934
- throw new Error('Invalid sender address');
7935
- }
7936
- if (!this.validateAddress(params.recipient)) {
7937
- throw new Error('Invalid recipient address');
7938
- }
7939
- if (params.sender === params.recipient) {
7940
- throw new Error('Sender and recipient addresses cannot be the same');
7941
- }
7942
- const txMsg = {
7943
- type: params.type,
7944
- sender: params.sender,
7945
- recipient: params.recipient,
7946
- amount: params.amount,
7947
- timestamp: params.timestamp || Date.now(),
7948
- text_data: params.textData || '',
7949
- nonce: params.nonce,
7950
- extra_info: JSON.stringify(params.extraInfo) || '',
7951
- zk_proof: params.zkProof || '',
7952
- zk_pub: params.zkPub || '',
7953
- };
7954
- const signature = this.signTransaction(txMsg, params.privateKey);
7955
- return {
7956
- tx_msg: txMsg,
7957
- signature,
7958
- };
7959
- }
7960
- /**
7961
- * Securely sign a transaction with Ed25519
7962
- * @param tx - Transaction message to sign
7963
- * @param privateKeyHex - Private key in PKCS#8 hex format
7964
- * @returns Base58 encoded signature
7965
- * @throws Error if signing fails
7966
- */
7967
- signTransaction(tx, privateKeyHex) {
7968
- try {
7969
- // Validate inputs
7970
- if (!tx || typeof tx !== 'object') {
7971
- throw new Error('Invalid transaction object');
7972
- }
7973
- if (!privateKeyHex || typeof privateKeyHex !== 'string') {
7974
- throw new Error('Invalid private key format');
7975
- }
7976
- // Serialize transaction data
7977
- const serializedData = this.serializeTransaction(tx);
7978
- if (!serializedData || serializedData.length === 0) {
7979
- throw new Error('Failed to serialize transaction');
7980
- }
7981
- // Extract the Ed25519 seed from the private key for nacl signing
7982
- const privateKeyDer = BufferCompat.from(privateKeyHex, 'hex');
7983
- if (privateKeyDer.length < CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH) {
7984
- throw new Error(`Invalid private key length: expected at least ${CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH} bytes, got ${privateKeyDer.length}`);
7985
- }
7986
- const seed = privateKeyDer.subarray(-CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH); // Last 32 bytes
7987
- const keyPair = nacl.sign.keyPair.fromSeed(seed);
7988
- // Validate key pair
7989
- if (!keyPair.publicKey || !keyPair.secretKey) {
7990
- throw new Error('Failed to create key pair from seed');
7991
- }
7992
- // Sign using Ed25519 (nacl) - constant time operation
7993
- const signature = nacl.sign.detached(serializedData, keyPair.secretKey);
7994
- if (!signature || signature.length === 0) {
7995
- throw new Error('Failed to generate signature');
7996
- }
7997
- // Clear sensitive data
7998
- privateKeyDer.fill(0);
7999
- seed.fill(0);
8000
- keyPair.secretKey.fill(0);
8001
- // Return signature based on transaction type
8002
- if (tx.type === TX_TYPE.PRIVATE_KEY) {
8003
- return bs58.encode(BufferCompat.from(signature));
8004
- }
8005
- // For regular transactions, wrap signature with public key
8006
- const userSig = {
8007
- PubKey: BufferCompat.from(keyPair.publicKey).toString('base64'),
8008
- Sig: BufferCompat.from(signature).toString('base64'),
8009
- };
8010
- return bs58.encode(BufferCompat.from(JSON.stringify(userSig)));
8011
- }
8012
- catch (error) {
8013
- throw new Error(`Transaction signing failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
8014
- }
8015
- }
8016
- /**
8017
- * Serialize transaction for signing
8018
- */
8019
- serializeTransaction(tx) {
8020
- const data = `${tx.type}|${tx.sender}|${tx.recipient}|${tx.amount}|${tx.text_data}|${tx.nonce}|${tx.extra_info}`;
8021
- return BufferCompat.from(data, 'utf8');
8022
- }
8023
- /**
8024
- * Add a signed transaction to the blockchain
8025
- */
8026
- async addTx(signedTx) {
8027
- return this.makeRequest('tx.addtx', signedTx);
8028
- }
8029
- /**
8030
- * Send a transaction (create, sign, and submit)
8031
- */
8032
- async sendTransaction(params) {
8033
- const fromAddress = this.getAddressFromUserId(params.sender);
8034
- const toAddress = this.getAddressFromUserId(params.recipient);
8035
- const signedTx = this.createAndSignTx({
8036
- ...params,
8037
- type: TX_TYPE.TRANSFER,
8038
- sender: fromAddress,
8039
- recipient: toAddress,
8040
- });
8041
- return this.addTx(signedTx);
8042
- }
8043
- async sendTransactionByAddress(params) {
8044
- const signedTx = this.createAndSignTx({
8045
- ...params,
8046
- type: TX_TYPE.TRANSFER,
8047
- });
8048
- return this.addTx(signedTx);
8049
- }
8050
- async sendTransactionByPrivateKey(params) {
8051
- const signedTx = this.createAndSignTx({
8052
- ...params,
8053
- type: TX_TYPE.PRIVATE_KEY,
8054
- });
8055
- return this.addTx(signedTx);
8056
- }
8057
- /**
8058
- * Get current nonce for an account
8059
- */
8060
- async getCurrentNonce(userId, tag = 'latest') {
8061
- const address = this.getAddressFromUserId(userId);
8062
- return this.makeRequest('account.getcurrentnonce', { address, tag });
8063
- }
8064
- async getAccountByUserId(userId) {
8065
- const address = this.getAddressFromUserId(userId);
8066
- return this.makeRequest('account.getaccount', {
8067
- address,
8068
- });
8069
- }
8070
- scaleAmountToDecimals(originalAmount, decimals = DECIMALS) {
8071
- let scaledAmount = BigInt(originalAmount);
8072
- for (let i = 0; i < decimals; i++) {
8073
- scaledAmount = scaledAmount * BigInt(10);
8074
- }
8075
- return scaledAmount.toString();
8076
- }
8077
- validateAddress(addr) {
8078
- const decoded = bs58.decode(addr);
8079
- if (!decoded ||
8080
- decoded.length !== CRYPTO_CONSTANTS.ED25519_PUBLIC_KEY_LENGTH) {
8081
- return false;
8082
- }
8083
- return true;
8084
- }
8085
- validateAmount(balance, amount) {
8086
- const bigBalance = BigInt(balance);
8087
- const bigAmount = BigInt(typeof amount === 'number' ? this.scaleAmountToDecimals(amount) : amount);
8088
- return bigAmount <= bigBalance;
8089
- }
8090
- }
8091
- function createMmnClient(config) {
8092
- return new MmnClient(config);
7591
+ var CryptoJS = cryptoJs.exports;
7592
+
7593
+ // MMN Client
7594
+ // Buffer polyfill for mobile environments
7595
+ class BufferPolyfill {
7596
+ static isBuffer(obj) {
7597
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer) {
7598
+ return Buffer.isBuffer(obj);
7599
+ }
7600
+ return obj instanceof Uint8Array;
7601
+ }
7602
+ static from(data, encoding) {
7603
+ if (typeof Buffer !== 'undefined' && Buffer.from) {
7604
+ return Buffer.from(data, encoding);
7605
+ }
7606
+ let result;
7607
+ if (Array.isArray(data)) {
7608
+ result = new Uint8Array(data);
7609
+ }
7610
+ else if (typeof data === 'string') {
7611
+ if (encoding === 'hex') {
7612
+ const bytes = [];
7613
+ for (let i = 0; i < data.length; i += 2) {
7614
+ bytes.push(parseInt(data.substr(i, 2), 16));
7615
+ }
7616
+ result = new Uint8Array(bytes);
7617
+ }
7618
+ else {
7619
+ // UTF-8 encoding
7620
+ const encoder = new TextEncoder();
7621
+ result = encoder.encode(data);
7622
+ }
7623
+ }
7624
+ else if (data instanceof Uint8Array) {
7625
+ result = data;
7626
+ }
7627
+ else {
7628
+ result = new Uint8Array(data);
7629
+ }
7630
+ // Add toString method
7631
+ result.toString = function (encoding) {
7632
+ if (encoding === 'hex') {
7633
+ return Array.from(this)
7634
+ .map((b) => b.toString(16).padStart(2, '0'))
7635
+ .join('');
7636
+ }
7637
+ else if (encoding === 'base64') {
7638
+ // Simple base64 encoding
7639
+ const bytes = this;
7640
+ let binary = '';
7641
+ for (let i = 0; i < bytes.length; i++) {
7642
+ binary += String.fromCharCode(bytes[i]);
7643
+ }
7644
+ return btoa(binary);
7645
+ }
7646
+ else {
7647
+ // UTF-8 decoding
7648
+ const decoder = new TextDecoder();
7649
+ return decoder.decode(this);
7650
+ }
7651
+ };
7652
+ return result;
7653
+ }
7654
+ static concat(arrays) {
7655
+ if (typeof Buffer !== 'undefined' && Buffer.concat) {
7656
+ return Buffer.concat(arrays);
7657
+ }
7658
+ const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0);
7659
+ const result = new Uint8Array(totalLength);
7660
+ let offset = 0;
7661
+ for (const arr of arrays) {
7662
+ result.set(arr, offset);
7663
+ offset += arr.length;
7664
+ }
7665
+ // Add toString method
7666
+ result.toString = function (encoding) {
7667
+ if (encoding === 'hex') {
7668
+ return Array.from(this)
7669
+ .map((b) => b.toString(16).padStart(2, '0'))
7670
+ .join('');
7671
+ }
7672
+ else {
7673
+ const decoder = new TextDecoder();
7674
+ return decoder.decode(this);
7675
+ }
7676
+ };
7677
+ return result;
7678
+ }
7679
+ }
7680
+ // Use polyfill if Buffer is not available
7681
+ const BufferCompat = typeof Buffer !== 'undefined' ? Buffer : BufferPolyfill;
7682
+ // Cryptographic constants
7683
+ const CRYPTO_CONSTANTS = {
7684
+ ED25519_PRIVATE_KEY_LENGTH: 32,
7685
+ ED25519_PUBLIC_KEY_LENGTH: 32,
7686
+ MNEMONIC_ENTROPY_BITS: 128,
7687
+ PKCS8_VERSION: 0,
7688
+ // ASN.1 DER encoding
7689
+ ASN1_SEQUENCE_TAG: 0x30,
7690
+ ASN1_OCTET_STRING_TAG: 0x04,
7691
+ ASN1_INTEGER_TAG: 0x02,
7692
+ ASN1_LENGTH: 0x80,
7693
+ // Ed25519 OID bytes: 1.3.101.112 (RFC 8410)
7694
+ ED25519_OID_BYTES: [0x06, 0x03, 0x2b, 0x65, 0x70],
7695
+ // PKCS#8 structure length constants
7696
+ PKCS8_ALGORITHM_ID_LENGTH: 0x0b,
7697
+ PKCS8_PRIVATE_KEY_OCTET_OUTER_LENGTH: 0x22,
7698
+ PKCS8_PRIVATE_KEY_OCTET_INNER_LENGTH: 0x20, // Inner OCTET STRING length (32 bytes)
7699
+ };
7700
+ // PRNG (Pseudo-Random Number Generator) constants
7701
+ const PRNG_CONSTANTS = {
7702
+ // Numerical Recipes LCG
7703
+ LCG_MULTIPLIER: 1664525,
7704
+ LCG_INCREMENT: 1013904223,
7705
+ LCG_MODULUS: 4294967296,
7706
+ TIMESTAMP_MULTIPLIER: 2654435761,
7707
+ HASH_SUBSTRING_LENGTH: 8,
7708
+ BYTE_SHIFT: 24,
7709
+ BYTE_MASK: 0xff,
7710
+ };
7711
+ const TX_TYPE = {
7712
+ TRANSFER: 0,
7713
+ PRIVATE_KEY: 1,
7714
+ };
7715
+ const DECIMALS = 6;
7716
+ class MmnClient {
7717
+ constructor(config) {
7718
+ this.requestId = 0;
7719
+ this.config = {
7720
+ timeout: 30000,
7721
+ headers: {
7722
+ 'Content-Type': 'application/json',
7723
+ Accept: 'application/json',
7724
+ },
7725
+ ...config,
7726
+ };
7727
+ }
7728
+ async makeRequest(method, params) {
7729
+ const request = {
7730
+ jsonrpc: '2.0',
7731
+ method,
7732
+ params,
7733
+ id: ++this.requestId,
7734
+ };
7735
+ // Create AbortController for timeout
7736
+ const controller = new AbortControllerPolyfill();
7737
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout || 30000);
7738
+ try {
7739
+ const requestOptions = {
7740
+ method: 'POST',
7741
+ mode: 'cors',
7742
+ credentials: 'omit',
7743
+ signal: controller.signal,
7744
+ headers: this.config.headers || {},
7745
+ body: JSON.stringify(request),
7746
+ };
7747
+ const response = await fetchPolyfill(this.config.baseUrl, requestOptions);
7748
+ clearTimeout(timeoutId);
7749
+ if (!response.ok) {
7750
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
7751
+ }
7752
+ const result = await response.json();
7753
+ if (result.error) {
7754
+ throw new Error(`JSON-RPC Error ${result.error.code}: ${result.error.message}`);
7755
+ }
7756
+ return result.result;
7757
+ }
7758
+ catch (error) {
7759
+ clearTimeout(timeoutId);
7760
+ if (error instanceof Error) {
7761
+ if (error.name === 'AbortError') {
7762
+ throw new Error(`Request timeout after ${this.config.timeout || 30000}ms`);
7763
+ }
7764
+ throw error;
7765
+ }
7766
+ throw new Error('Unknown error occurred');
7767
+ }
7768
+ }
7769
+ /**
7770
+ * Securely convert raw Ed25519 private key to PKCS#8 format
7771
+ * @param raw - Raw 32-byte Ed25519 private key
7772
+ * @returns PKCS#8 formatted private key in hex
7773
+ * @throws Error if input validation fails
7774
+ */
7775
+ rawEd25519ToPkcs8Hex(raw) {
7776
+ // Input validation
7777
+ if (!BufferCompat.isBuffer(raw)) {
7778
+ throw new Error('Private key must be a Buffer');
7779
+ }
7780
+ if (raw.length !== CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH) {
7781
+ throw new Error(`Ed25519 private key must be exactly ${CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH} bytes`);
7782
+ }
7783
+ try {
7784
+ // Ed25519 OID: 1.3.101.112 (RFC 8410 - Algorithm Identifiers for Ed25519)
7785
+ const ED25519_OID = BufferCompat.from(CRYPTO_CONSTANTS.ED25519_OID_BYTES);
7786
+ const VERSION_BYTES = BufferCompat.from([
7787
+ CRYPTO_CONSTANTS.ASN1_INTEGER_TAG,
7788
+ 0x01,
7789
+ CRYPTO_CONSTANTS.PKCS8_VERSION,
7790
+ ]);
7791
+ // Create algorithm identifier sequence (AlgorithmIdentifier)
7792
+ const algorithmId = BufferCompat.concat([
7793
+ BufferCompat.from([
7794
+ CRYPTO_CONSTANTS.ASN1_SEQUENCE_TAG,
7795
+ CRYPTO_CONSTANTS.PKCS8_ALGORITHM_ID_LENGTH,
7796
+ ]),
7797
+ ED25519_OID,
7798
+ ]);
7799
+ // Create private key octet string (wrapped Ed25519 private key)
7800
+ const privateKeyOctetString = BufferCompat.concat([
7801
+ BufferCompat.from([
7802
+ CRYPTO_CONSTANTS.ASN1_OCTET_STRING_TAG,
7803
+ CRYPTO_CONSTANTS.PKCS8_PRIVATE_KEY_OCTET_OUTER_LENGTH,
7804
+ ]),
7805
+ BufferCompat.from([
7806
+ CRYPTO_CONSTANTS.ASN1_OCTET_STRING_TAG,
7807
+ CRYPTO_CONSTANTS.PKCS8_PRIVATE_KEY_OCTET_INNER_LENGTH,
7808
+ ]),
7809
+ raw,
7810
+ ]);
7811
+ // Create PKCS#8 body
7812
+ const pkcs8Body = BufferCompat.concat([
7813
+ VERSION_BYTES,
7814
+ algorithmId,
7815
+ privateKeyOctetString,
7816
+ ]);
7817
+ // Create final PKCS#8 structure
7818
+ const pkcs8 = BufferCompat.concat([
7819
+ BufferCompat.from([CRYPTO_CONSTANTS.ASN1_SEQUENCE_TAG]),
7820
+ this.encodeLength(pkcs8Body.length),
7821
+ pkcs8Body,
7822
+ ]);
7823
+ const result = pkcs8.toString('hex');
7824
+ // Clear sensitive data from memory
7825
+ raw.fill(0);
7826
+ privateKeyOctetString.fill(0);
7827
+ pkcs8Body.fill(0);
7828
+ pkcs8.fill(0);
7829
+ return result;
7830
+ }
7831
+ catch (error) {
7832
+ // Clear sensitive data on error
7833
+ raw.fill(0);
7834
+ throw new Error(`Failed to convert private key to PKCS#8: ${error instanceof Error ? error.message : 'Unknown error'}`);
7835
+ }
7836
+ }
7837
+ /**
7838
+ * Encode length in ASN.1 DER format
7839
+ * ASN.1 length encoding rules:
7840
+ * - Short form (0-127): single byte with the length value
7841
+ * - Long form (128+): first byte is 0x80 + number of length bytes, followed by length bytes
7842
+ * @param length - The length value to encode
7843
+ * @returns ASN.1 DER encoded length bytes
7844
+ */
7845
+ encodeLength(length) {
7846
+ if (length < CRYPTO_CONSTANTS.ASN1_LENGTH) {
7847
+ return BufferCompat.from([length]);
7848
+ }
7849
+ const bytes = [];
7850
+ let len = length;
7851
+ while (len > 0) {
7852
+ bytes.unshift(len & PRNG_CONSTANTS.BYTE_MASK);
7853
+ len >>= 8;
7854
+ }
7855
+ return BufferCompat.from([
7856
+ CRYPTO_CONSTANTS.ASN1_LENGTH | bytes.length,
7857
+ ...bytes,
7858
+ ]);
7859
+ }
7860
+ /**
7861
+ * Generate secure entropy using multiple sources for maximum compatibility
7862
+ * @returns Array of 32 random bytes
7863
+ */
7864
+ generateSecureEntropy() {
7865
+ const entropy = [];
7866
+ const targetLength = CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH;
7867
+ // Use multiple entropy sources
7868
+ const now = Date.now();
7869
+ const performance = typeof window !== 'undefined' && window.performance
7870
+ ? window.performance.now()
7871
+ : now;
7872
+ const random = Math.random();
7873
+ // Create initial seed from timestamp and random
7874
+ let seed = now + performance + random;
7875
+ // Generate bytes using Linear Congruential Generator (LCG) with multiple entropy sources
7876
+ // This provides a fallback Pseudorandom Number Generator (PRNG) when crypto.getRandomValues is not available
7877
+ for (let i = 0; i < targetLength; i++) {
7878
+ // Xₙ₊₁ = (a * Xₙ + c) mod m
7879
+ seed =
7880
+ (seed * PRNG_CONSTANTS.LCG_MULTIPLIER + PRNG_CONSTANTS.LCG_INCREMENT) %
7881
+ PRNG_CONSTANTS.LCG_MODULUS;
7882
+ // Mix with timestamp to add time-based entropy
7883
+ seed ^= (now + i) * PRNG_CONSTANTS.TIMESTAMP_MULTIPLIER;
7884
+ // Mix with Math.random() for additional browser-provided randomness
7885
+ seed ^= Math.floor(Math.random() * PRNG_CONSTANTS.LCG_MODULUS);
7886
+ // Additional cryptographic mixing using SHA256 if CryptoJS is available
7887
+ if (typeof CryptoJS !== 'undefined') {
7888
+ const hashInput = seed.toString() + i.toString() + now.toString();
7889
+ const hash = CryptoJS.SHA256(hashInput).toString();
7890
+ // Extract first 8 hex characters (32 bits) from hash for mixing
7891
+ seed ^= parseInt(hash.substring(0, PRNG_CONSTANTS.HASH_SUBSTRING_LENGTH), 16);
7892
+ }
7893
+ entropy.push((seed >>> PRNG_CONSTANTS.BYTE_SHIFT) & PRNG_CONSTANTS.BYTE_MASK);
7894
+ }
7895
+ return entropy;
7896
+ }
7897
+ /**
7898
+ * Securely generate ephemeral key pair with proper entropy
7899
+ * React Native compatible version with multiple fallbacks
7900
+ * @returns Ephemeral key pair with private and public keys
7901
+ * @throws Error if key generation fails
7902
+ */
7903
+ generateEphemeralKeyPair() {
7904
+ try {
7905
+ let seed;
7906
+ // Try multiple approaches for mobile compatibility
7907
+ try {
7908
+ // Method 1: Try nacl.randomBytes first
7909
+ seed = nacl__default["default"].randomBytes(CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH);
7910
+ }
7911
+ catch (naclError) {
7912
+ try {
7913
+ // Method 2: Use crypto.getRandomValues if available (browsers/React Native)
7914
+ if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
7915
+ seed = new Uint8Array(CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH);
7916
+ crypto.getRandomValues(seed);
7917
+ }
7918
+ else {
7919
+ throw new Error('crypto.getRandomValues not available');
7920
+ }
7921
+ }
7922
+ catch (cryptoError) {
7923
+ // Method 3: Fallback to secure pseudo-random generation
7924
+ const entropy = this.generateSecureEntropy();
7925
+ seed = new Uint8Array(entropy);
7926
+ }
7927
+ }
7928
+ // Validate seed length
7929
+ if (seed.length !== CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH) {
7930
+ throw new Error(`Invalid seed length: expected ${CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH}, got ${seed.length}`);
7931
+ }
7932
+ // Generate key pair from seed
7933
+ const keyPair = nacl__default["default"].sign.keyPair.fromSeed(seed);
7934
+ const publicKeyBytes = keyPair.publicKey;
7935
+ // Validate public key
7936
+ if (publicKeyBytes.length !== CRYPTO_CONSTANTS.ED25519_PUBLIC_KEY_LENGTH) {
7937
+ throw new Error(`Invalid public key length: expected ${CRYPTO_CONSTANTS.ED25519_PUBLIC_KEY_LENGTH}, got ${publicKeyBytes.length}`);
7938
+ }
7939
+ // Convert private key to PKCS#8 format
7940
+ const privateKeyHex = this.rawEd25519ToPkcs8Hex(BufferCompat.from(seed));
7941
+ // Clear sensitive data
7942
+ seed.fill(0);
7943
+ keyPair.secretKey.fill(0);
7944
+ return {
7945
+ privateKey: privateKeyHex,
7946
+ publicKey: bs58__default["default"].encode(publicKeyBytes),
7947
+ };
7948
+ }
7949
+ catch (error) {
7950
+ throw new Error(`Failed to generate ephemeral key pair: ${error instanceof Error ? error.message : 'Unknown error'}`);
7951
+ }
7952
+ }
7953
+ getAddressFromUserId(userId) {
7954
+ // Use crypto-js for SHA-256 in React Native
7955
+ const hash = CryptoJS.SHA256(userId).toString(CryptoJS.enc.Hex);
7956
+ const hashBuffer = BufferCompat.from(hash, 'hex');
7957
+ return bs58__default["default"].encode(hashBuffer);
7958
+ }
7959
+ /**
7960
+ * Create and sign a transaction message
7961
+ */
7962
+ createAndSignTx(params) {
7963
+ if (!this.validateAddress(params.sender)) {
7964
+ throw new Error('Invalid sender address');
7965
+ }
7966
+ if (!this.validateAddress(params.recipient)) {
7967
+ throw new Error('Invalid recipient address');
7968
+ }
7969
+ if (params.sender === params.recipient) {
7970
+ throw new Error('Sender and recipient addresses cannot be the same');
7971
+ }
7972
+ const txMsg = {
7973
+ type: params.type,
7974
+ sender: params.sender,
7975
+ recipient: params.recipient,
7976
+ amount: params.amount,
7977
+ timestamp: params.timestamp || Date.now(),
7978
+ text_data: params.textData || '',
7979
+ nonce: params.nonce,
7980
+ extra_info: JSON.stringify(params.extraInfo) || '',
7981
+ zk_proof: params.zkProof || '',
7982
+ zk_pub: params.zkPub || '',
7983
+ };
7984
+ const signature = this.signTransaction(txMsg, params.privateKey);
7985
+ return {
7986
+ tx_msg: txMsg,
7987
+ signature,
7988
+ };
7989
+ }
7990
+ /**
7991
+ * Securely sign a transaction with Ed25519
7992
+ * @param tx - Transaction message to sign
7993
+ * @param privateKeyHex - Private key in PKCS#8 hex format
7994
+ * @returns Base58 encoded signature
7995
+ * @throws Error if signing fails
7996
+ */
7997
+ signTransaction(tx, privateKeyHex) {
7998
+ try {
7999
+ // Validate inputs
8000
+ if (!tx || typeof tx !== 'object') {
8001
+ throw new Error('Invalid transaction object');
8002
+ }
8003
+ if (!privateKeyHex || typeof privateKeyHex !== 'string') {
8004
+ throw new Error('Invalid private key format');
8005
+ }
8006
+ // Serialize transaction data
8007
+ const serializedData = this.serializeTransaction(tx);
8008
+ if (!serializedData || serializedData.length === 0) {
8009
+ throw new Error('Failed to serialize transaction');
8010
+ }
8011
+ // Extract the Ed25519 seed from the private key for nacl signing
8012
+ const privateKeyDer = BufferCompat.from(privateKeyHex, 'hex');
8013
+ if (privateKeyDer.length < CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH) {
8014
+ throw new Error(`Invalid private key length: expected at least ${CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH} bytes, got ${privateKeyDer.length}`);
8015
+ }
8016
+ const seed = privateKeyDer.subarray(-CRYPTO_CONSTANTS.ED25519_PRIVATE_KEY_LENGTH); // Last 32 bytes
8017
+ const keyPair = nacl__default["default"].sign.keyPair.fromSeed(seed);
8018
+ // Validate key pair
8019
+ if (!keyPair.publicKey || !keyPair.secretKey) {
8020
+ throw new Error('Failed to create key pair from seed');
8021
+ }
8022
+ // Sign using Ed25519 (nacl) - constant time operation
8023
+ const signature = nacl__default["default"].sign.detached(serializedData, keyPair.secretKey);
8024
+ if (!signature || signature.length === 0) {
8025
+ throw new Error('Failed to generate signature');
8026
+ }
8027
+ // Clear sensitive data
8028
+ privateKeyDer.fill(0);
8029
+ seed.fill(0);
8030
+ keyPair.secretKey.fill(0);
8031
+ // Return signature based on transaction type
8032
+ if (tx.type === TX_TYPE.PRIVATE_KEY) {
8033
+ return bs58__default["default"].encode(BufferCompat.from(signature));
8034
+ }
8035
+ // For regular transactions, wrap signature with public key
8036
+ const userSig = {
8037
+ PubKey: BufferCompat.from(keyPair.publicKey).toString('base64'),
8038
+ Sig: BufferCompat.from(signature).toString('base64'),
8039
+ };
8040
+ return bs58__default["default"].encode(BufferCompat.from(JSON.stringify(userSig)));
8041
+ }
8042
+ catch (error) {
8043
+ throw new Error(`Transaction signing failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
8044
+ }
8045
+ }
8046
+ /**
8047
+ * Serialize transaction for signing
8048
+ */
8049
+ serializeTransaction(tx) {
8050
+ const data = `${tx.type}|${tx.sender}|${tx.recipient}|${tx.amount}|${tx.text_data}|${tx.nonce}|${tx.extra_info}`;
8051
+ return BufferCompat.from(data, 'utf8');
8052
+ }
8053
+ /**
8054
+ * Add a signed transaction to the blockchain
8055
+ */
8056
+ async addTx(signedTx) {
8057
+ return this.makeRequest('tx.addtx', signedTx);
8058
+ }
8059
+ /**
8060
+ * Send a transaction (create, sign, and submit)
8061
+ */
8062
+ async sendTransaction(params) {
8063
+ const fromAddress = this.getAddressFromUserId(params.sender);
8064
+ const toAddress = this.getAddressFromUserId(params.recipient);
8065
+ const signedTx = this.createAndSignTx({
8066
+ ...params,
8067
+ type: TX_TYPE.TRANSFER,
8068
+ sender: fromAddress,
8069
+ recipient: toAddress,
8070
+ });
8071
+ return this.addTx(signedTx);
8072
+ }
8073
+ async sendTransactionByAddress(params) {
8074
+ const signedTx = this.createAndSignTx({
8075
+ ...params,
8076
+ type: TX_TYPE.TRANSFER,
8077
+ });
8078
+ return this.addTx(signedTx);
8079
+ }
8080
+ async sendTransactionByPrivateKey(params) {
8081
+ const signedTx = this.createAndSignTx({
8082
+ ...params,
8083
+ type: TX_TYPE.PRIVATE_KEY,
8084
+ });
8085
+ return this.addTx(signedTx);
8086
+ }
8087
+ /**
8088
+ * Get current nonce for an account
8089
+ */
8090
+ async getCurrentNonce(userId, tag = 'latest') {
8091
+ const address = this.getAddressFromUserId(userId);
8092
+ return this.makeRequest('account.getcurrentnonce', { address, tag });
8093
+ }
8094
+ async getAccountByUserId(userId) {
8095
+ const address = this.getAddressFromUserId(userId);
8096
+ return this.makeRequest('account.getaccount', {
8097
+ address,
8098
+ });
8099
+ }
8100
+ scaleAmountToDecimals(originalAmount, decimals = DECIMALS) {
8101
+ let scaledAmount = BigInt(originalAmount);
8102
+ for (let i = 0; i < decimals; i++) {
8103
+ scaledAmount = scaledAmount * BigInt(10);
8104
+ }
8105
+ return scaledAmount.toString();
8106
+ }
8107
+ validateAddress(addr) {
8108
+ const decoded = bs58__default["default"].decode(addr);
8109
+ if (!decoded ||
8110
+ decoded.length !== CRYPTO_CONSTANTS.ED25519_PUBLIC_KEY_LENGTH) {
8111
+ return false;
8112
+ }
8113
+ return true;
8114
+ }
8115
+ validateAmount(balance, amount) {
8116
+ const bigBalance = BigInt(balance);
8117
+ const bigAmount = BigInt(typeof amount === 'number' ? this.scaleAmountToDecimals(amount) : amount);
8118
+ return bigAmount <= bigBalance;
8119
+ }
8120
+ }
8121
+ function createMmnClient(config) {
8122
+ return new MmnClient(config);
8093
8123
  }
8094
8124
 
8095
- // --- JSON-RPC Types ---
8096
- exports.ETransferType = void 0;
8097
- (function (ETransferType) {
8098
- ETransferType["GiveCoffee"] = "give_coffee";
8099
- ETransferType["TransferToken"] = "transfer_token";
8100
- ETransferType["UnlockItem"] = "unlock_item";
8101
- })(exports.ETransferType || (exports.ETransferType = {}));
8102
- exports.EZkClientType = void 0;
8103
- (function (EZkClientType) {
8104
- EZkClientType["MEZON"] = "mezon";
8105
- EZkClientType["OAUTH"] = "oauth";
8125
+ // --- JSON-RPC Types ---
8126
+ exports.ETransferType = void 0;
8127
+ (function (ETransferType) {
8128
+ ETransferType["GiveCoffee"] = "give_coffee";
8129
+ ETransferType["TransferToken"] = "transfer_token";
8130
+ ETransferType["UnlockItem"] = "unlock_item";
8131
+ })(exports.ETransferType || (exports.ETransferType = {}));
8132
+ exports.EZkClientType = void 0;
8133
+ (function (EZkClientType) {
8134
+ EZkClientType["MEZON"] = "mezon";
8135
+ EZkClientType["OAUTH"] = "oauth";
8106
8136
  })(exports.EZkClientType || (exports.EZkClientType = {}));
8107
8137
 
8108
- class ZkClient {
8109
- constructor(config) {
8110
- this.endpoint = config.endpoint;
8111
- this.timeout = config.timeout || 30000;
8112
- this.headers = {
8113
- Accept: 'application/json',
8114
- 'Content-Type': 'application/json',
8115
- ...(config.headers || {}),
8116
- };
8117
- }
8118
- async makeRequest(method, path, params, body) {
8119
- let url = `${this.endpoint}/${path}`;
8120
- // Add query parameters for GET requests
8121
- if (params && Object.keys(params).length > 0) {
8122
- const searchParams = new URLSearchParams();
8123
- Object.entries(params).forEach(([key, value]) => {
8124
- searchParams.append(key, String(value));
8125
- });
8126
- url += `?${searchParams.toString()}`;
8127
- }
8128
- // Create AbortController for timeout
8129
- const controller = new AbortController();
8130
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
8131
- try {
8132
- const requestOptions = {
8133
- method,
8134
- mode: 'cors',
8135
- credentials: 'omit',
8136
- signal: controller.signal,
8137
- headers: this.headers,
8138
- };
8139
- // Add body for POST requests
8140
- if (method === 'POST' && body) {
8141
- requestOptions.body = JSON.stringify(body);
8142
- }
8143
- const response = await fetch(url, requestOptions);
8144
- clearTimeout(timeoutId);
8145
- if (!response.ok) {
8146
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
8147
- }
8148
- const data = await response.json();
8149
- return data;
8150
- }
8151
- catch (error) {
8152
- clearTimeout(timeoutId);
8153
- if (error instanceof Error) {
8154
- if (error.name === 'AbortError') {
8155
- throw new Error(`Request timeout after ${this.timeout}ms`);
8156
- }
8157
- throw error;
8158
- }
8159
- throw new Error('Request failed');
8160
- }
8161
- }
8162
- async getZkProofs({ userId, ephemeralPublicKey, jwt, address, clientType = exports.EZkClientType.MEZON, }) {
8163
- const path = `prove`;
8164
- const res = await this.makeRequest('POST', path, undefined, {
8165
- user_id: userId,
8166
- ephemeral_pk: ephemeralPublicKey,
8167
- jwt,
8168
- address,
8169
- client_type: clientType,
8170
- });
8171
- return res.data;
8172
- }
8138
+ class ZkClient {
8139
+ constructor(config) {
8140
+ this.endpoint = config.endpoint;
8141
+ this.timeout = config.timeout || 30000;
8142
+ this.headers = {
8143
+ Accept: 'application/json',
8144
+ 'Content-Type': 'application/json',
8145
+ ...(config.headers || {}),
8146
+ };
8147
+ }
8148
+ async makeRequest(method, path, params, body) {
8149
+ let url = `${this.endpoint}/${path}`;
8150
+ // Add query parameters for GET requests
8151
+ if (params && Object.keys(params).length > 0) {
8152
+ const searchParams = new URLSearchParams();
8153
+ Object.entries(params).forEach(([key, value]) => {
8154
+ searchParams.append(key, String(value));
8155
+ });
8156
+ url += `?${searchParams.toString()}`;
8157
+ }
8158
+ // Create AbortController for timeout
8159
+ const controller = new AbortControllerPolyfill();
8160
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
8161
+ try {
8162
+ const requestOptions = {
8163
+ method,
8164
+ mode: 'cors',
8165
+ credentials: 'omit',
8166
+ signal: controller.signal,
8167
+ headers: this.headers,
8168
+ };
8169
+ // Add body for POST requests
8170
+ if (method === 'POST' && body) {
8171
+ requestOptions.body = JSON.stringify(body);
8172
+ }
8173
+ const response = await fetchPolyfill(url, requestOptions);
8174
+ clearTimeout(timeoutId);
8175
+ if (!response.ok) {
8176
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
8177
+ }
8178
+ const data = await response.json();
8179
+ return data;
8180
+ }
8181
+ catch (error) {
8182
+ clearTimeout(timeoutId);
8183
+ if (error instanceof Error) {
8184
+ if (error.name === 'AbortError') {
8185
+ throw new Error(`Request timeout after ${this.timeout}ms`);
8186
+ }
8187
+ throw error;
8188
+ }
8189
+ throw new Error('Request failed');
8190
+ }
8191
+ }
8192
+ async getZkProofs({ userId, ephemeralPublicKey, jwt, address, clientType = exports.EZkClientType.MEZON, }) {
8193
+ const path = `prove`;
8194
+ const res = await this.makeRequest('POST', path, undefined, {
8195
+ user_id: userId,
8196
+ ephemeral_pk: ephemeralPublicKey,
8197
+ jwt,
8198
+ address,
8199
+ client_type: clientType,
8200
+ });
8201
+ return res.data;
8202
+ }
8173
8203
  }
8174
8204
 
8175
8205
  exports.IndexerClient = IndexerClient;