@dynamic-labs-wallet/node-tron 0.0.0 → 1.1.42

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 (33) hide show
  1. package/index.cjs +1182 -0
  2. package/index.d.ts +1 -0
  3. package/index.esm.d.ts +1 -0
  4. package/index.esm.js +1159 -0
  5. package/package.json +36 -1
  6. package/src/client/client.d.ts +178 -0
  7. package/src/client/client.d.ts.map +1 -0
  8. package/src/client/constants.d.ts +37 -0
  9. package/src/client/constants.d.ts.map +1 -0
  10. package/src/client/index.d.ts +3 -0
  11. package/src/client/index.d.ts.map +1 -0
  12. package/src/index.d.ts +6 -0
  13. package/src/index.d.ts.map +1 -0
  14. package/src/types.d.ts +21 -0
  15. package/src/types.d.ts.map +1 -0
  16. package/src/utils/deriveTronAddress/deriveTronAddress.d.ts +39 -0
  17. package/src/utils/deriveTronAddress/deriveTronAddress.d.ts.map +1 -0
  18. package/src/utils/deriveTronAddress/index.d.ts +2 -0
  19. package/src/utils/deriveTronAddress/index.d.ts.map +1 -0
  20. package/src/utils/formatTronMessage/formatTronMessage.d.ts +35 -0
  21. package/src/utils/formatTronMessage/formatTronMessage.d.ts.map +1 -0
  22. package/src/utils/formatTronMessage/index.d.ts +2 -0
  23. package/src/utils/formatTronMessage/index.d.ts.map +1 -0
  24. package/src/utils/getTronTxId/getTronTxId.d.ts +17 -0
  25. package/src/utils/getTronTxId/getTronTxId.d.ts.map +1 -0
  26. package/src/utils/getTronTxId/index.d.ts +2 -0
  27. package/src/utils/getTronTxId/index.d.ts.map +1 -0
  28. package/src/utils/index.d.ts +5 -0
  29. package/src/utils/index.d.ts.map +1 -0
  30. package/src/utils/serializeECDSASignature/index.d.ts +2 -0
  31. package/src/utils/serializeECDSASignature/index.d.ts.map +1 -0
  32. package/src/utils/serializeECDSASignature/serializeECDSASignature.d.ts +13 -0
  33. package/src/utils/serializeECDSASignature/serializeECDSASignature.d.ts.map +1 -0
package/index.cjs ADDED
@@ -0,0 +1,1182 @@
1
+ 'use strict';
2
+
3
+ var node = require('@dynamic-labs-wallet/node');
4
+ var sha3 = require('@noble/hashes/sha3');
5
+ var sha256 = require('@noble/hashes/sha256');
6
+ var bs58 = require('bs58');
7
+
8
+ /**
9
+ * Mainnet address prefix byte for TRON addresses. Shasta and Nile testnets
10
+ * use the same prefix; the network is disambiguated at the node/relay layer
11
+ * (TRON does not embed a network byte into the address).
12
+ *
13
+ * @see https://github.com/tronprotocol/tips/blob/master/tip-21.md
14
+ */ var TRON_ADDRESS_PREFIX = 0x41;
15
+ /**
16
+ * Length of the Base58Check checksum appended to a TRON address payload.
17
+ */ var TRON_CHECKSUM_LENGTH = 4;
18
+ /**
19
+ * Length of the encoded (un-prefixed) Base58Check TRON address.
20
+ * `T...` addresses are always 34 characters.
21
+ */ var TRON_ADDRESS_LENGTH = 34;
22
+ var hexToBytes$1 = function(hex) {
23
+ var buf = Buffer.from(hex, 'hex');
24
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
25
+ };
26
+ /**
27
+ * Derive a TRON Base58Check ("T...") address from a secp256k1 public key.
28
+ *
29
+ * TRON addresses are the keccak256 hash of the uncompressed public key
30
+ * (with the leading 0x04 byte stripped), taking the last 20 bytes, prefixed
31
+ * with 0x41, then encoded as Base58Check (SHA256d checksum).
32
+ *
33
+ * @see https://github.com/tronprotocol/tips/blob/master/tip-21.md
34
+ */ var deriveTronAddress = function(param) {
35
+ var publicKeyHex = param.publicKeyHex;
36
+ var cleanHex = publicKeyHex.startsWith('0x') ? publicKeyHex.slice(2) : publicKeyHex;
37
+ var publicKeyBytes = hexToBytes$1(cleanHex);
38
+ // Allow either 65-byte uncompressed (0x04 || X || Y) or 64-byte X||Y form.
39
+ var xy;
40
+ if (publicKeyBytes.length === 65) {
41
+ if (publicKeyBytes[0] !== 0x04) {
42
+ throw new Error("Invalid uncompressed public key prefix: expected 0x04, got 0x".concat(publicKeyBytes[0].toString(16)));
43
+ }
44
+ xy = publicKeyBytes.subarray(1);
45
+ } else if (publicKeyBytes.length === 64) {
46
+ xy = publicKeyBytes;
47
+ } else {
48
+ throw new Error("Invalid public key length: ".concat(publicKeyBytes.length, ", expected 64 (X||Y) or 65 (uncompressed)"));
49
+ }
50
+ var hashed = sha3.keccak_256(xy);
51
+ var lastTwentyBytes = hashed.slice(-20);
52
+ var payload = new Uint8Array(21);
53
+ payload[0] = TRON_ADDRESS_PREFIX;
54
+ payload.set(lastTwentyBytes, 1);
55
+ var checksum = sha256.sha256(sha256.sha256(payload)).slice(0, TRON_CHECKSUM_LENGTH);
56
+ var addressBytes = new Uint8Array(payload.length + TRON_CHECKSUM_LENGTH);
57
+ addressBytes.set(payload, 0);
58
+ addressBytes.set(checksum, payload.length);
59
+ return bs58.encode(addressBytes);
60
+ };
61
+ /**
62
+ * Validate a TRON Base58Check address.
63
+ *
64
+ * Performs the full decode + checksum + prefix check, so it rejects EVM
65
+ * `0x...` addresses, malformed Base58, and addresses whose checksum was
66
+ * tampered with.
67
+ */ var isValidTronAddress = function(address) {
68
+ if (typeof address !== 'string' || address.length !== TRON_ADDRESS_LENGTH) {
69
+ return false;
70
+ }
71
+ var decoded;
72
+ try {
73
+ decoded = bs58.decode(address);
74
+ } catch (e) {
75
+ return false;
76
+ }
77
+ if (decoded.length !== 25 || decoded[0] !== TRON_ADDRESS_PREFIX) {
78
+ return false;
79
+ }
80
+ var payload = decoded.subarray(0, 21);
81
+ var expectedChecksum = decoded.subarray(21);
82
+ var actualChecksum = sha256.sha256(sha256.sha256(payload)).slice(0, TRON_CHECKSUM_LENGTH);
83
+ for(var i = 0; i < TRON_CHECKSUM_LENGTH; i++){
84
+ if (expectedChecksum[i] !== actualChecksum[i]) {
85
+ return false;
86
+ }
87
+ }
88
+ return true;
89
+ };
90
+ /**
91
+ * Decode a TRON Base58Check address to its 21-byte payload (prefix + 20-byte
92
+ * hash). Throws if the checksum doesn't validate.
93
+ */ var decodeTronAddress = function(address) {
94
+ if (!isValidTronAddress(address)) {
95
+ throw new Error('Invalid TRON address');
96
+ }
97
+ return bs58.decode(address).subarray(0, 21);
98
+ };
99
+ /**
100
+ * Convert a TRON Base58Check address to its 0x41-prefixed hex form (used in
101
+ * raw transactions).
102
+ */ var tronAddressToHex = function(address) {
103
+ var payload = decodeTronAddress(address);
104
+ return "0x".concat(Buffer.from(payload).toString('hex'));
105
+ };
106
+
107
+ function _instanceof(left, right) {
108
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
109
+ return !!right[Symbol.hasInstance](left);
110
+ } else {
111
+ return left instanceof right;
112
+ }
113
+ }
114
+ /**
115
+ * TIP-191 personal-sign prefix used by TRON for signed messages.
116
+ *
117
+ * The hash that gets signed is:
118
+ * keccak256("\x19TRON Signed Message:\n" || len(message) || message)
119
+ *
120
+ * where `message` is the raw bytes the user agreed to sign.
121
+ *
122
+ * @see https://github.com/tronprotocol/tips/blob/master/tip-191.md
123
+ */ var TRON_SIGN_MESSAGE_PREFIX = '\x19TRON Signed Message:\n';
124
+ var bufferToUint8Array = function(buf) {
125
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
126
+ };
127
+ var stringToBytes = function(s) {
128
+ return bufferToUint8Array(Buffer.from(s, 'utf8'));
129
+ };
130
+ var hexToBytes = function(hex) {
131
+ var clean = hex.startsWith('0x') ? hex.slice(2) : hex;
132
+ return bufferToUint8Array(Buffer.from(clean, 'hex'));
133
+ };
134
+ /**
135
+ * Convert a user-supplied message into the bytes that TIP-191 expects to be
136
+ * hashed.
137
+ *
138
+ * - `string` starting with `0x` → treated as hex bytes
139
+ * - `string` otherwise → treated as utf-8 bytes
140
+ * - `Uint8Array` → passed through
141
+ * - `{ raw: ... }` → mirrors viem's `{ raw }` escape hatch for already-hashed payloads
142
+ */ var toTronMessageBytes = function(message) {
143
+ if (_instanceof(message, Uint8Array)) return message;
144
+ if (typeof message === 'string') {
145
+ return message.startsWith('0x') ? hexToBytes(message) : stringToBytes(message);
146
+ }
147
+ if (typeof message.raw === 'string') return hexToBytes(message.raw);
148
+ return message.raw;
149
+ };
150
+ /**
151
+ * Apply the TIP-191 prefix and return the keccak256 hash that should be
152
+ * signed by the MPC ECDSA flow.
153
+ *
154
+ * Returns a `Uint8Array` (32 bytes). The wallet client hands this to
155
+ * `sign(...)` with `isFormatted: true` so the forward-MPC path sees a
156
+ * pre-hashed payload.
157
+ */ var formatTronMessage = function(message) {
158
+ var bytes = toTronMessageBytes(message);
159
+ var prefixBytes = stringToBytes("".concat(TRON_SIGN_MESSAGE_PREFIX).concat(bytes.length));
160
+ var combined = new Uint8Array(prefixBytes.length + bytes.length);
161
+ combined.set(prefixBytes, 0);
162
+ combined.set(bytes, prefixBytes.length);
163
+ return sha3.keccak_256(combined);
164
+ };
165
+
166
+ /**
167
+ * TRON transactions are signed over `sha256(raw_data_hex_bytes)`, where
168
+ * `raw_data_hex` is the protobuf-encoded `Transaction.raw` produced by the
169
+ * TRON full node when the unsigned transaction is created.
170
+ *
171
+ * The MPC client never reconstructs the protobuf itself — the caller passes
172
+ * the already-serialized `raw_data_hex` and we hash it deterministically here.
173
+ *
174
+ * @see https://developers.tron.network/docs/transactions
175
+ */ var getTronTxId = function(rawDataHex) {
176
+ var clean = rawDataHex.startsWith('0x') ? rawDataHex.slice(2) : rawDataHex;
177
+ if (clean.length === 0 || clean.length % 2 !== 0 || /[^0-9a-fA-F]/.test(clean)) {
178
+ throw new Error('Invalid raw_data_hex: must be a non-empty hex string');
179
+ }
180
+ var buf = Buffer.from(clean, 'hex');
181
+ return sha256.sha256(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
182
+ };
183
+ /**
184
+ * Convenience wrapper that returns the txID as a 0x-prefixed hex string
185
+ * (matching the form returned by the TRON full node `/wallet/gettransactioninfobyid`).
186
+ */ var getTronTxIdHex = function(rawDataHex) {
187
+ var hash = getTronTxId(rawDataHex);
188
+ return "0x".concat(Buffer.from(hash).toString('hex'));
189
+ };
190
+
191
+ /**
192
+ * Serialize an MPC-produced ECDSA signature into the 65-byte
193
+ * `r || s || v` hex form that TRON full nodes expect on
194
+ * `Transaction.signature[0]` and TIP-191 signed messages.
195
+ *
196
+ * TRON canonicalises v to 0 / 1 on the wire (recovery id), while the MPC
197
+ * relay returns v as 27 / 28 (Ethereum legacy convention). We strip the +27
198
+ * offset here so the output is directly usable by TRON tooling without
199
+ * the consumer having to remember the convention.
200
+ */ var serializeECDSASignature = function(signature) {
201
+ var r = Buffer.from(signature.r).toString('hex');
202
+ var s = Buffer.from(signature.s).toString('hex');
203
+ if (r.length !== 64 || s.length !== 64) {
204
+ throw new Error("Invalid ECDSA r/s length: r=".concat(r.length, ", s=").concat(s.length, " (expected 64 hex chars each)"));
205
+ }
206
+ var vNum = Number(signature.v);
207
+ if (!Number.isFinite(vNum)) {
208
+ throw new TypeError("Invalid ECDSA v: ".concat(signature.v));
209
+ }
210
+ var recoveryId = vNum >= 27 ? vNum - 27 : vNum;
211
+ if (recoveryId !== 0 && recoveryId !== 1) {
212
+ throw new Error("Invalid ECDSA recovery id derived from v=".concat(vNum, ": ").concat(recoveryId));
213
+ }
214
+ var vHex = recoveryId.toString(16).padStart(2, '0');
215
+ return "0x".concat(r).concat(s).concat(vHex);
216
+ };
217
+
218
+ var ERROR_KEYGEN_FAILED = 'Error with keygen';
219
+ var ERROR_CREATE_WALLET_ACCOUNT = 'Error creating TRON wallet account';
220
+ var ERROR_IMPORT_PRIVATE_KEY = 'Error importing private key';
221
+ var ERROR_EXPORT_PRIVATE_KEY = 'Error exporting private key';
222
+ var ERROR_SIGN_MESSAGE = 'Error signing message';
223
+ var ERROR_SIGN_TRANSACTION = 'Error signing transaction';
224
+ var ERROR_ACCOUNT_ADDRESS_REQUIRED = 'Account address is required';
225
+ var ERROR_RAW_DATA_HEX_REQUIRED = 'Transaction raw_data_hex is required';
226
+ var ERROR_INVALID_RAW_PUBLIC_KEY = 'Invalid raw public key instance';
227
+ /**
228
+ * TRON network identifiers.
229
+ *
230
+ * Mainnet, Shasta, and Nile share the same address format and the same MPC
231
+ * keyshare namespace (SLIP-44 coin type 195). They only differ at the RPC /
232
+ * full-node URL level, so the wallet client itself is network-agnostic; the
233
+ * network passes through transactions via the raw_data the caller assembled
234
+ * against the appropriate full-node endpoint.
235
+ */ var TRON_NETWORKS = {
236
+ MAINNET: {
237
+ name: 'Mainnet',
238
+ rpcUrl: 'https://api.trongrid.io',
239
+ chainId: '0x2b6653dc'
240
+ },
241
+ SHASTA: {
242
+ name: 'Shasta',
243
+ rpcUrl: 'https://api.shasta.trongrid.io',
244
+ chainId: '0x94a9059e'
245
+ },
246
+ NILE: {
247
+ name: 'Nile',
248
+ rpcUrl: 'https://nile.trongrid.io',
249
+ chainId: '0xcd8690dc'
250
+ }
251
+ };
252
+
253
+ function _array_like_to_array(arr, len) {
254
+ if (len == null || len > arr.length) len = arr.length;
255
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
256
+ return arr2;
257
+ }
258
+ function _array_without_holes(arr) {
259
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
260
+ }
261
+ function _assert_this_initialized(self) {
262
+ if (self === void 0) {
263
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
264
+ }
265
+ return self;
266
+ }
267
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
268
+ try {
269
+ var info = gen[key](arg);
270
+ var value = info.value;
271
+ } catch (error) {
272
+ reject(error);
273
+ return;
274
+ }
275
+ if (info.done) {
276
+ resolve(value);
277
+ } else {
278
+ Promise.resolve(value).then(_next, _throw);
279
+ }
280
+ }
281
+ function _async_to_generator(fn) {
282
+ return function() {
283
+ var self = this, args = arguments;
284
+ return new Promise(function(resolve, reject) {
285
+ var gen = fn.apply(self, args);
286
+ function _next(value) {
287
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
288
+ }
289
+ function _throw(err) {
290
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
291
+ }
292
+ _next(undefined);
293
+ });
294
+ };
295
+ }
296
+ function _call_super(_this, derived, args) {
297
+ derived = _get_prototype_of(derived);
298
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
299
+ }
300
+ function _class_call_check(instance, Constructor) {
301
+ if (!(instance instanceof Constructor)) {
302
+ throw new TypeError("Cannot call a class as a function");
303
+ }
304
+ }
305
+ function _defineProperties(target, props) {
306
+ for(var i = 0; i < props.length; i++){
307
+ var descriptor = props[i];
308
+ descriptor.enumerable = descriptor.enumerable || false;
309
+ descriptor.configurable = true;
310
+ if ("value" in descriptor) descriptor.writable = true;
311
+ Object.defineProperty(target, descriptor.key, descriptor);
312
+ }
313
+ }
314
+ function _create_class(Constructor, protoProps, staticProps) {
315
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
316
+ return Constructor;
317
+ }
318
+ function _define_property(obj, key, value) {
319
+ if (key in obj) {
320
+ Object.defineProperty(obj, key, {
321
+ value: value,
322
+ enumerable: true,
323
+ configurable: true,
324
+ writable: true
325
+ });
326
+ } else {
327
+ obj[key] = value;
328
+ }
329
+ return obj;
330
+ }
331
+ function _get_prototype_of(o) {
332
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
333
+ return o.__proto__ || Object.getPrototypeOf(o);
334
+ };
335
+ return _get_prototype_of(o);
336
+ }
337
+ function _inherits(subClass, superClass) {
338
+ if (typeof superClass !== "function" && superClass !== null) {
339
+ throw new TypeError("Super expression must either be null or a function");
340
+ }
341
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
342
+ constructor: {
343
+ value: subClass,
344
+ writable: true,
345
+ configurable: true
346
+ }
347
+ });
348
+ if (superClass) _set_prototype_of(subClass, superClass);
349
+ }
350
+ function _iterable_to_array(iter) {
351
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
352
+ }
353
+ function _non_iterable_spread() {
354
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
355
+ }
356
+ function _object_spread(target) {
357
+ for(var i = 1; i < arguments.length; i++){
358
+ var source = arguments[i] != null ? arguments[i] : {};
359
+ var ownKeys = Object.keys(source);
360
+ if (typeof Object.getOwnPropertySymbols === "function") {
361
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
362
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
363
+ }));
364
+ }
365
+ ownKeys.forEach(function(key) {
366
+ _define_property(target, key, source[key]);
367
+ });
368
+ }
369
+ return target;
370
+ }
371
+ function ownKeys(object, enumerableOnly) {
372
+ var keys = Object.keys(object);
373
+ if (Object.getOwnPropertySymbols) {
374
+ var symbols = Object.getOwnPropertySymbols(object);
375
+ keys.push.apply(keys, symbols);
376
+ }
377
+ return keys;
378
+ }
379
+ function _object_spread_props(target, source) {
380
+ source = source != null ? source : {};
381
+ if (Object.getOwnPropertyDescriptors) {
382
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
383
+ } else {
384
+ ownKeys(Object(source)).forEach(function(key) {
385
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
386
+ });
387
+ }
388
+ return target;
389
+ }
390
+ function _possible_constructor_return(self, call) {
391
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
392
+ return call;
393
+ }
394
+ return _assert_this_initialized(self);
395
+ }
396
+ function _set_prototype_of(o, p) {
397
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
398
+ o.__proto__ = p;
399
+ return o;
400
+ };
401
+ return _set_prototype_of(o, p);
402
+ }
403
+ function _to_consumable_array(arr) {
404
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
405
+ }
406
+ function _type_of(obj) {
407
+ "@swc/helpers - typeof";
408
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
409
+ }
410
+ function _unsupported_iterable_to_array(o, minLen) {
411
+ if (!o) return;
412
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
413
+ var n = Object.prototype.toString.call(o).slice(8, -1);
414
+ if (n === "Object" && o.constructor) n = o.constructor.name;
415
+ if (n === "Map" || n === "Set") return Array.from(n);
416
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
417
+ }
418
+ function _is_native_reflect_construct() {
419
+ try {
420
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
421
+ } catch (_) {}
422
+ return (_is_native_reflect_construct = function() {
423
+ return !!result;
424
+ })();
425
+ }
426
+ function _ts_generator(thisArg, body) {
427
+ var f, y, t, g, _ = {
428
+ label: 0,
429
+ sent: function() {
430
+ if (t[0] & 1) throw t[1];
431
+ return t[1];
432
+ },
433
+ trys: [],
434
+ ops: []
435
+ };
436
+ return g = {
437
+ next: verb(0),
438
+ "throw": verb(1),
439
+ "return": verb(2)
440
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
441
+ return this;
442
+ }), g;
443
+ function verb(n) {
444
+ return function(v) {
445
+ return step([
446
+ n,
447
+ v
448
+ ]);
449
+ };
450
+ }
451
+ function step(op) {
452
+ if (f) throw new TypeError("Generator is already executing.");
453
+ while(_)try {
454
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
455
+ if (y = 0, t) op = [
456
+ op[0] & 2,
457
+ t.value
458
+ ];
459
+ switch(op[0]){
460
+ case 0:
461
+ case 1:
462
+ t = op;
463
+ break;
464
+ case 4:
465
+ _.label++;
466
+ return {
467
+ value: op[1],
468
+ done: false
469
+ };
470
+ case 5:
471
+ _.label++;
472
+ y = op[1];
473
+ op = [
474
+ 0
475
+ ];
476
+ continue;
477
+ case 7:
478
+ op = _.ops.pop();
479
+ _.trys.pop();
480
+ continue;
481
+ default:
482
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
483
+ _ = 0;
484
+ continue;
485
+ }
486
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
487
+ _.label = op[1];
488
+ break;
489
+ }
490
+ if (op[0] === 6 && _.label < t[1]) {
491
+ _.label = t[1];
492
+ t = op;
493
+ break;
494
+ }
495
+ if (t && _.label < t[2]) {
496
+ _.label = t[2];
497
+ _.ops.push(op);
498
+ break;
499
+ }
500
+ if (t[2]) _.ops.pop();
501
+ _.trys.pop();
502
+ continue;
503
+ }
504
+ op = body.call(thisArg, _);
505
+ } catch (e) {
506
+ op = [
507
+ 6,
508
+ e
509
+ ];
510
+ y = 0;
511
+ } finally{
512
+ f = t = 0;
513
+ }
514
+ if (op[0] & 5) throw op[1];
515
+ return {
516
+ value: op[0] ? op[1] : void 0,
517
+ done: true
518
+ };
519
+ }
520
+ }
521
+ var logError = node.createLogError('node-tron');
522
+ /**
523
+ * Wallet client for TRON (SLIP-44 coin type 195, secp256k1 / ECDSA).
524
+ *
525
+ * V1 surface: create / signMessage (TIP-191, aka signMessageV2) /
526
+ * signTransaction / importPrivateKey / exportPrivateKey.
527
+ *
528
+ * Networks (Mainnet / Shasta / Nile) share the same address format and
529
+ * keyshare namespace; the network is selected at the broadcast layer via the
530
+ * raw_data the caller assembles against the full node of their choice. See
531
+ * `TRON_NETWORKS` in `./constants`.
532
+ *
533
+ * Address derivation: keccak256 of the uncompressed secp256k1 public key
534
+ * (minus the 0x04 prefix), last 20 bytes, prefixed with 0x41, encoded as
535
+ * Base58Check (`T...`).
536
+ *
537
+ * Transaction signing: SHA-256 of `raw_data_hex` is the digest, sent through
538
+ * the sign path as a pre-hashed (`isFormatted: true`) payload.
539
+ *
540
+ * Message signing (TIP-191): keccak256 of `\x19TRON Signed Message:\n<len><msg>`.
541
+ */ var DynamicTronWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
542
+ _inherits(DynamicTronWalletClient, DynamicWalletClient);
543
+ function DynamicTronWalletClient(param) {
544
+ var environmentId = param.environmentId, baseApiUrl = param.baseApiUrl, baseMPCRelayApiUrl = param.baseMPCRelayApiUrl, debug = param.debug, enableMPCAccelerator = param.enableMPCAccelerator, logger = param.logger;
545
+ _class_call_check(this, DynamicTronWalletClient);
546
+ var _this;
547
+ _this = _call_super(this, DynamicTronWalletClient, [
548
+ {
549
+ environmentId: environmentId,
550
+ baseApiUrl: baseApiUrl,
551
+ baseMPCRelayApiUrl: baseMPCRelayApiUrl,
552
+ debug: debug,
553
+ enableMPCAccelerator: enableMPCAccelerator,
554
+ logger: logger
555
+ }
556
+ ]), _define_property(_this, "chainName", 'TRON');
557
+ return _this;
558
+ }
559
+ _create_class(DynamicTronWalletClient, [
560
+ {
561
+ key: "createWalletAccount",
562
+ value: /**
563
+ * Creates a new wallet account.
564
+ * @param thresholdSignatureScheme - The threshold signature scheme to use for the wallet.
565
+ * @param password - The password to use for the wallet.
566
+ * @param onError - The function to call if an error occurs.
567
+ * @param backUpToDynamic - Whether to back up the external server key shares to the client share service. By default, it is false.
568
+ * @returns The walletMetadata, public key hex, raw public key, and external server key shares.
569
+ */ function createWalletAccount(param) {
570
+ var thresholdSignatureScheme = param.thresholdSignatureScheme, password = param.password, onError = param.onError, _param_backUpToDynamic = param.backUpToDynamic, backUpToDynamic = _param_backUpToDynamic === void 0 ? false : _param_backUpToDynamic;
571
+ var _this = this;
572
+ return _async_to_generator(function() {
573
+ var ceremony, _ref, rawPublicKey, externalServerKeyShares, _ceremony_completion, resolvedWalletId, resolvedShareSetId, _this_deriveAccountAddress, accountAddress, publicKeyHex, chainConfig, walletMetadata, _ref1, keySharesWithBackupStatus, backupInfo, _ceremony_completion_encryptedWalletApiKey, error;
574
+ return _ts_generator(this, function(_state) {
575
+ switch(_state.label){
576
+ case 0:
577
+ _state.trys.push([
578
+ 0,
579
+ 4,
580
+ ,
581
+ 5
582
+ ]);
583
+ ceremony = _this.createCeremonyCompletionTracker();
584
+ return [
585
+ 4,
586
+ _this.keyGen({
587
+ chainName: _this.chainName,
588
+ thresholdSignatureScheme: thresholdSignatureScheme,
589
+ skipLock: true,
590
+ password: password,
591
+ backUpToDynamic: backUpToDynamic,
592
+ onError: onError,
593
+ onCeremonyComplete: ceremony.onCeremonyComplete
594
+ })
595
+ ];
596
+ case 1:
597
+ _ref = _state.sent(), rawPublicKey = _ref.rawPublicKey, externalServerKeyShares = _ref.externalServerKeyShares;
598
+ return [
599
+ 4,
600
+ ceremony.promise
601
+ ];
602
+ case 2:
603
+ _state.sent();
604
+ _ceremony_completion = ceremony.completion, resolvedWalletId = _ceremony_completion.walletId, resolvedShareSetId = _ceremony_completion.shareSetId;
605
+ if (!rawPublicKey || !externalServerKeyShares || !resolvedWalletId) {
606
+ throw new Error(ERROR_KEYGEN_FAILED);
607
+ }
608
+ _this.checkRawPublicKeyInstance(rawPublicKey);
609
+ _this_deriveAccountAddress = _this.deriveAccountAddress({
610
+ rawPublicKey: rawPublicKey
611
+ }), accountAddress = _this_deriveAccountAddress.accountAddress, publicKeyHex = _this_deriveAccountAddress.publicKeyHex;
612
+ chainConfig = node.getMPCChainConfig(_this.chainName);
613
+ walletMetadata = {
614
+ walletId: resolvedWalletId,
615
+ accountAddress: accountAddress,
616
+ chainName: _this.chainName,
617
+ thresholdSignatureScheme: thresholdSignatureScheme,
618
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map(function(value, index) {
619
+ return [
620
+ index,
621
+ value
622
+ ];
623
+ }))),
624
+ shareSetId: resolvedShareSetId
625
+ };
626
+ return [
627
+ 4,
628
+ _this.storeEncryptedBackupByWalletWithRetry({
629
+ accountAddress: accountAddress,
630
+ externalServerKeyShares: externalServerKeyShares,
631
+ password: password,
632
+ backUpToDynamic: backUpToDynamic,
633
+ walletMetadata: walletMetadata
634
+ })
635
+ ];
636
+ case 3:
637
+ _ref1 = _state.sent(), keySharesWithBackupStatus = _ref1.keySharesWithBackupStatus, backupInfo = _ref1.backupInfo;
638
+ walletMetadata.externalServerKeySharesBackupInfo = backupInfo;
639
+ return [
640
+ 2,
641
+ {
642
+ walletMetadata: walletMetadata,
643
+ rawPublicKey: rawPublicKey,
644
+ publicKeyHex: publicKeyHex,
645
+ externalServerKeyShares: externalServerKeyShares,
646
+ externalKeySharesWithBackupStatus: keySharesWithBackupStatus,
647
+ encryptedWalletApiKey: (_ceremony_completion_encryptedWalletApiKey = ceremony.completion.encryptedWalletApiKey) !== null && _ceremony_completion_encryptedWalletApiKey !== void 0 ? _ceremony_completion_encryptedWalletApiKey : undefined
648
+ }
649
+ ];
650
+ case 4:
651
+ error = _state.sent();
652
+ logError({
653
+ message: ERROR_CREATE_WALLET_ACCOUNT,
654
+ error: error,
655
+ context: {}
656
+ });
657
+ throw new Error(ERROR_CREATE_WALLET_ACCOUNT, {
658
+ cause: error
659
+ });
660
+ case 5:
661
+ return [
662
+ 2
663
+ ];
664
+ }
665
+ });
666
+ })();
667
+ }
668
+ },
669
+ {
670
+ key: "signMessage",
671
+ value: /**
672
+ * TIP-191 personal-sign for TRON. This is the `signMessageV2` surface — there
673
+ * is no V1 legacy message-sign path for TRON.
674
+ *
675
+ * The TIP-191 prefix + keccak256 hashing happens client-side; the resulting
676
+ * 32-byte digest goes through the sign path as `isFormatted: true` (matches
677
+ * the browser TRON client and the EVM pre-hashed contract).
678
+ *
679
+ * @returns `0x`-prefixed `r || s || v` signature with v normalized to 0/1.
680
+ */ function signMessage(param) {
681
+ var message = param.message, walletMetadata = param.walletMetadata, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, externalServerKeyShares = param.externalServerKeyShares, context = param.context, onError = param.onError;
682
+ var _this = this;
683
+ return _async_to_generator(function() {
684
+ var accountAddress, digest, messageBytes, resolvedContext, signatureEcdsa, error;
685
+ return _ts_generator(this, function(_state) {
686
+ switch(_state.label){
687
+ case 0:
688
+ accountAddress = walletMetadata.accountAddress;
689
+ _state.label = 1;
690
+ case 1:
691
+ _state.trys.push([
692
+ 1,
693
+ 3,
694
+ ,
695
+ 4
696
+ ]);
697
+ if (!accountAddress) {
698
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
699
+ }
700
+ digest = formatTronMessage(message);
701
+ // TIP-191 pre-image as rawSign context — a bare digest is rejected as
702
+ // missing_context by policy-enabled wallets.
703
+ messageBytes = toTronMessageBytes(message);
704
+ resolvedContext = node.resolveRawSignContext(context, {
705
+ hashFunction: node.SignMessageRawSignHashFunctionEnum.Keccak256,
706
+ payload: Buffer.from(messageBytes).toString('hex'),
707
+ prefix: Buffer.from("".concat(TRON_SIGN_MESSAGE_PREFIX).concat(messageBytes.length), 'utf8').toString('hex')
708
+ });
709
+ return [
710
+ 4,
711
+ _this.sign({
712
+ message: digest,
713
+ accountAddress: accountAddress,
714
+ chainName: _this.chainName,
715
+ password: password,
716
+ externalServerKeyShares: externalServerKeyShares,
717
+ isFormatted: true,
718
+ context: resolvedContext,
719
+ onError: onError,
720
+ walletMetadata: walletMetadata
721
+ })
722
+ ];
723
+ case 2:
724
+ signatureEcdsa = _state.sent();
725
+ return [
726
+ 2,
727
+ serializeECDSASignature(signatureEcdsa)
728
+ ];
729
+ case 3:
730
+ error = _state.sent();
731
+ logError({
732
+ message: ERROR_SIGN_MESSAGE,
733
+ error: error,
734
+ context: {
735
+ accountAddress: accountAddress
736
+ }
737
+ });
738
+ throw new Error(ERROR_SIGN_MESSAGE, {
739
+ cause: error
740
+ });
741
+ case 4:
742
+ return [
743
+ 2
744
+ ];
745
+ }
746
+ });
747
+ })();
748
+ }
749
+ },
750
+ {
751
+ /**
752
+ * Alias for {@link signMessage} — the TIP-191 sign surface is the only
753
+ * TRON message-sign path (there is no V1 variant for this chain).
754
+ */ key: "signMessageV2",
755
+ value: function signMessageV2(args) {
756
+ return this.signMessage(args);
757
+ }
758
+ },
759
+ {
760
+ /**
761
+ * Returns the `0x`-prefixed TIP-191 digest that `signMessage` sends to the
762
+ * signer — mirrors the browser client's `prepareSignMessage`.
763
+ */ key: "prepareSignMessage",
764
+ value: function prepareSignMessage(param) {
765
+ var message = param.message;
766
+ return "0x".concat(Buffer.from(formatTronMessage(message)).toString('hex'));
767
+ }
768
+ },
769
+ {
770
+ key: "signTransaction",
771
+ value: /**
772
+ * Sign a TRON transaction.
773
+ *
774
+ * The caller supplies the unsigned `raw_data_hex` produced by a TRON full
775
+ * node (e.g. `/wallet/createtransaction` or `/wallet/triggersmartcontract`),
776
+ * either as a parsed `TronTransaction` object or as the JSON string that
777
+ * came back from the full node. The signer hashes those bytes with SHA-256
778
+ * (the TRON `txID`) and signs the digest.
779
+ *
780
+ * Returns the entire signed transaction (with the new signature appended to
781
+ * `transaction.signature[]`) as a JSON string, ready to be passed to the
782
+ * full-node `/wallet/broadcasttransaction` endpoint.
783
+ */ function signTransaction(param) {
784
+ var walletMetadata = param.walletMetadata, transaction = param.transaction, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, externalServerKeyShares = param.externalServerKeyShares, context = param.context, onError = param.onError;
785
+ var _this = this;
786
+ return _async_to_generator(function() {
787
+ var accountAddress, rawParsed, parsedTransaction, digestBytes, txid, resolvedContext, signatureEcdsa, hexSig, _parsedTransaction_signature, signed, error;
788
+ return _ts_generator(this, function(_state) {
789
+ switch(_state.label){
790
+ case 0:
791
+ accountAddress = walletMetadata.accountAddress;
792
+ if (!accountAddress) {
793
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
794
+ }
795
+ rawParsed = transaction;
796
+ if (typeof transaction === 'string') {
797
+ try {
798
+ rawParsed = JSON.parse(transaction);
799
+ } catch (e) {
800
+ throw new Error(ERROR_RAW_DATA_HEX_REQUIRED);
801
+ }
802
+ }
803
+ if (!rawParsed || (typeof rawParsed === "undefined" ? "undefined" : _type_of(rawParsed)) !== 'object' || typeof rawParsed.raw_data_hex !== 'string' || rawParsed.raw_data_hex.length === 0) {
804
+ throw new Error(ERROR_RAW_DATA_HEX_REQUIRED);
805
+ }
806
+ parsedTransaction = rawParsed;
807
+ _state.label = 1;
808
+ case 1:
809
+ _state.trys.push([
810
+ 1,
811
+ 3,
812
+ ,
813
+ 4
814
+ ]);
815
+ digestBytes = getTronTxId(parsedTransaction.raw_data_hex);
816
+ txid = getTronTxIdHex(parsedTransaction.raw_data_hex);
817
+ resolvedContext = _object_spread_props(_object_spread({}, context), {
818
+ rawSign: {
819
+ hashFunction: node.SignMessageRawSignHashFunctionEnum.Sha256,
820
+ payload: parsedTransaction.raw_data_hex
821
+ }
822
+ });
823
+ return [
824
+ 4,
825
+ _this.sign({
826
+ message: digestBytes,
827
+ accountAddress: accountAddress,
828
+ chainName: _this.chainName,
829
+ password: password,
830
+ externalServerKeyShares: externalServerKeyShares,
831
+ isFormatted: true,
832
+ context: resolvedContext,
833
+ onError: onError,
834
+ walletMetadata: walletMetadata,
835
+ walletOperation: node.WalletOperation.SIGN_TRANSACTION
836
+ })
837
+ ];
838
+ case 2:
839
+ signatureEcdsa = _state.sent();
840
+ hexSig = serializeECDSASignature(signatureEcdsa).slice(2);
841
+ signed = _object_spread_props(_object_spread({}, parsedTransaction), {
842
+ // txID is always recomputed — a caller-supplied one could name a different payload.
843
+ txID: txid.slice(2),
844
+ signature: _to_consumable_array((_parsedTransaction_signature = parsedTransaction.signature) !== null && _parsedTransaction_signature !== void 0 ? _parsedTransaction_signature : []).concat([
845
+ hexSig
846
+ ])
847
+ });
848
+ return [
849
+ 2,
850
+ JSON.stringify(signed)
851
+ ];
852
+ case 3:
853
+ error = _state.sent();
854
+ logError({
855
+ message: ERROR_SIGN_TRANSACTION,
856
+ error: error,
857
+ context: {
858
+ accountAddress: accountAddress
859
+ }
860
+ });
861
+ throw new Error(ERROR_SIGN_TRANSACTION, {
862
+ cause: error
863
+ });
864
+ case 4:
865
+ return [
866
+ 2
867
+ ];
868
+ }
869
+ });
870
+ })();
871
+ }
872
+ },
873
+ {
874
+ key: "exportPrivateKey",
875
+ value: /**
876
+ * Exports the private key for a given wallet.
877
+ * @returns `0x`-prefixed 32-byte hex private key (tronweb / TronLink format).
878
+ */ function exportPrivateKey(param) {
879
+ var walletMetadata = param.walletMetadata, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, externalServerKeyShares = param.externalServerKeyShares;
880
+ var _this = this;
881
+ return _async_to_generator(function() {
882
+ var accountAddress, derivedPrivateKey, hex, error;
883
+ return _ts_generator(this, function(_state) {
884
+ switch(_state.label){
885
+ case 0:
886
+ accountAddress = walletMetadata.accountAddress;
887
+ _state.label = 1;
888
+ case 1:
889
+ _state.trys.push([
890
+ 1,
891
+ 3,
892
+ ,
893
+ 4
894
+ ]);
895
+ return [
896
+ 4,
897
+ _this.exportKey({
898
+ accountAddress: accountAddress,
899
+ chainName: _this.chainName,
900
+ password: password,
901
+ externalServerKeyShares: externalServerKeyShares,
902
+ walletMetadata: walletMetadata
903
+ })
904
+ ];
905
+ case 2:
906
+ derivedPrivateKey = _state.sent().derivedPrivateKey;
907
+ if (!derivedPrivateKey) {
908
+ throw new Error('Derived private key is undefined');
909
+ }
910
+ hex = derivedPrivateKey.startsWith('0x') ? derivedPrivateKey.slice(2) : derivedPrivateKey;
911
+ return [
912
+ 2,
913
+ "0x".concat(hex)
914
+ ];
915
+ case 3:
916
+ error = _state.sent();
917
+ logError({
918
+ message: ERROR_EXPORT_PRIVATE_KEY,
919
+ error: error,
920
+ context: {
921
+ accountAddress: accountAddress
922
+ }
923
+ });
924
+ throw new Error(ERROR_EXPORT_PRIVATE_KEY);
925
+ case 4:
926
+ return [
927
+ 2
928
+ ];
929
+ }
930
+ });
931
+ })();
932
+ }
933
+ },
934
+ {
935
+ key: "offlineExportPrivateKey",
936
+ value: /**
937
+ * `derivationPath` is the JSON-serialized index map that
938
+ * `walletMetadata.derivationPath` carries (e.g. `'{"0":44,"1":195,"2":0,"3":0,"4":0}'`
939
+ * or `'[44,195,0,0,0]'`). BIP-32 strings such as `"m/44'/195'/0'/0/0"` are rejected.
940
+ * Omit it to export without path derivation.
941
+ */ function offlineExportPrivateKey(param) {
942
+ var keyShares = param.keyShares, derivationPath = param.derivationPath;
943
+ var _this = this;
944
+ return _async_to_generator(function() {
945
+ var derivedPrivateKey;
946
+ return _ts_generator(this, function(_state) {
947
+ switch(_state.label){
948
+ case 0:
949
+ return [
950
+ 4,
951
+ _this.offlineExportKey({
952
+ chainName: _this.chainName,
953
+ keyShares: keyShares,
954
+ derivationPath: derivationPath
955
+ })
956
+ ];
957
+ case 1:
958
+ derivedPrivateKey = _state.sent().derivedPrivateKey;
959
+ return [
960
+ 2,
961
+ {
962
+ derivedPrivateKey: derivedPrivateKey
963
+ }
964
+ ];
965
+ }
966
+ });
967
+ })();
968
+ }
969
+ },
970
+ {
971
+ key: "importPrivateKey",
972
+ value: /**
973
+ * Imports a private key.
974
+ * @param privateKey - The private key to import (hex, with or without 0x).
975
+ * @param chainName - The chain name to use for the wallet.
976
+ * @param thresholdSignatureScheme - The threshold signature scheme to use for the wallet.
977
+ * @param password - The password to use for the wallet.
978
+ * @param onError - The function to call if an error occurs.
979
+ * @param backUpToDynamic - Whether to back up the external server key shares to the client share service. By default, it is false.
980
+ * @param publicAddressCheck - Optional TRON address to verify the imported key against.
981
+ * @returns The walletMetadata, public key hex, raw public key, and external server key shares.
982
+ */ function importPrivateKey(param) {
983
+ var privateKey = param.privateKey, thresholdSignatureScheme = param.thresholdSignatureScheme, password = param.password, _param_backUpToDynamic = param.backUpToDynamic, backUpToDynamic = _param_backUpToDynamic === void 0 ? false : _param_backUpToDynamic, onError = param.onError, publicAddressCheck = param.publicAddressCheck;
984
+ var _this = this;
985
+ return _async_to_generator(function() {
986
+ var resolvedWalletId, resolvedShareSetId, ceremonyCeremonyCompleteResolver, ceremonyCompletePromise, formattedPrivateKey, _ref, rawPublicKey, externalServerKeyShares, _this_deriveAccountAddress, accountAddress, publicKeyHex, chainConfig, walletMetadata, _ref1, keySharesWithBackupStatus, backupInfo, error;
987
+ return _ts_generator(this, function(_state) {
988
+ switch(_state.label){
989
+ case 0:
990
+ _state.trys.push([
991
+ 0,
992
+ 4,
993
+ ,
994
+ 5
995
+ ]);
996
+ if (publicAddressCheck && !isValidTronAddress(publicAddressCheck)) {
997
+ throw new Error('Invalid TRON address provided for publicAddressCheck');
998
+ }
999
+ ceremonyCompletePromise = new Promise(function(resolve) {
1000
+ ceremonyCeremonyCompleteResolver = resolve;
1001
+ });
1002
+ formattedPrivateKey = privateKey.startsWith('0x') ? privateKey.slice(2) : privateKey;
1003
+ return [
1004
+ 4,
1005
+ _this.importRawPrivateKey({
1006
+ chainName: _this.chainName,
1007
+ privateKey: formattedPrivateKey,
1008
+ thresholdSignatureScheme: thresholdSignatureScheme,
1009
+ password: password,
1010
+ backUpToDynamic: backUpToDynamic,
1011
+ onCeremonyComplete: function(_accountAddress, walletId, shareSetId) {
1012
+ resolvedWalletId = walletId;
1013
+ resolvedShareSetId = shareSetId;
1014
+ ceremonyCeremonyCompleteResolver(undefined);
1015
+ },
1016
+ onError: function(e) {
1017
+ logError({
1018
+ message: 'importPrivateKey: onError',
1019
+ error: e,
1020
+ context: {}
1021
+ });
1022
+ onError === null || onError === void 0 ? void 0 : onError(e);
1023
+ }
1024
+ })
1025
+ ];
1026
+ case 1:
1027
+ _ref = _state.sent(), rawPublicKey = _ref.rawPublicKey, externalServerKeyShares = _ref.externalServerKeyShares;
1028
+ return [
1029
+ 4,
1030
+ ceremonyCompletePromise
1031
+ ];
1032
+ case 2:
1033
+ _state.sent();
1034
+ if (!rawPublicKey || !externalServerKeyShares || !resolvedWalletId) {
1035
+ throw new Error(ERROR_IMPORT_PRIVATE_KEY);
1036
+ }
1037
+ _this.checkRawPublicKeyInstance(rawPublicKey);
1038
+ _this_deriveAccountAddress = _this.deriveAccountAddress({
1039
+ rawPublicKey: rawPublicKey
1040
+ }), accountAddress = _this_deriveAccountAddress.accountAddress, publicKeyHex = _this_deriveAccountAddress.publicKeyHex;
1041
+ if (publicAddressCheck && accountAddress !== publicAddressCheck) {
1042
+ throw new Error('Public address mismatch between derived and provided publicAddressCheck');
1043
+ }
1044
+ chainConfig = node.getMPCChainConfig(_this.chainName);
1045
+ walletMetadata = {
1046
+ walletId: resolvedWalletId,
1047
+ accountAddress: accountAddress,
1048
+ chainName: _this.chainName,
1049
+ thresholdSignatureScheme: thresholdSignatureScheme,
1050
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map(function(value, index) {
1051
+ return [
1052
+ index,
1053
+ value
1054
+ ];
1055
+ }))),
1056
+ shareSetId: resolvedShareSetId
1057
+ };
1058
+ return [
1059
+ 4,
1060
+ _this.storeEncryptedBackupByWalletWithRetry({
1061
+ accountAddress: accountAddress,
1062
+ externalServerKeyShares: externalServerKeyShares,
1063
+ password: password,
1064
+ backUpToDynamic: backUpToDynamic,
1065
+ walletMetadata: walletMetadata
1066
+ })
1067
+ ];
1068
+ case 3:
1069
+ _ref1 = _state.sent(), keySharesWithBackupStatus = _ref1.keySharesWithBackupStatus, backupInfo = _ref1.backupInfo;
1070
+ walletMetadata.externalServerKeySharesBackupInfo = backupInfo;
1071
+ return [
1072
+ 2,
1073
+ {
1074
+ walletMetadata: walletMetadata,
1075
+ rawPublicKey: rawPublicKey,
1076
+ publicKeyHex: publicKeyHex,
1077
+ externalServerKeyShares: externalServerKeyShares,
1078
+ externalKeySharesWithBackupStatus: keySharesWithBackupStatus
1079
+ }
1080
+ ];
1081
+ case 4:
1082
+ error = _state.sent();
1083
+ logError({
1084
+ message: ERROR_IMPORT_PRIVATE_KEY,
1085
+ error: error,
1086
+ context: {}
1087
+ });
1088
+ onError === null || onError === void 0 ? void 0 : onError(error);
1089
+ throw new Error(ERROR_IMPORT_PRIVATE_KEY);
1090
+ case 5:
1091
+ return [
1092
+ 2
1093
+ ];
1094
+ }
1095
+ });
1096
+ })();
1097
+ }
1098
+ },
1099
+ {
1100
+ /**
1101
+ * Derives the TRON Base58Check address from an MPC ECDSA public key.
1102
+ */ key: "deriveAccountAddress",
1103
+ value: function deriveAccountAddress(param) {
1104
+ var rawPublicKey = param.rawPublicKey;
1105
+ var publicKeyHex = rawPublicKey.pubKeyAsHex();
1106
+ var serializedUncompressed = rawPublicKey.serializeUncompressed();
1107
+ var uncompressedHex = Buffer.from(serializedUncompressed).toString('hex');
1108
+ var accountAddress = deriveTronAddress({
1109
+ publicKeyHex: uncompressedHex
1110
+ });
1111
+ return {
1112
+ accountAddress: accountAddress,
1113
+ publicKeyHex: publicKeyHex
1114
+ };
1115
+ }
1116
+ },
1117
+ {
1118
+ key: "getTronWallets",
1119
+ value: /**
1120
+ * Gets all TRON wallets.
1121
+ * @returns Array of TRON wallets
1122
+ */ function getTronWallets() {
1123
+ var _this = this;
1124
+ return _async_to_generator(function() {
1125
+ var wallets, tronWallets;
1126
+ return _ts_generator(this, function(_state) {
1127
+ switch(_state.label){
1128
+ case 0:
1129
+ return [
1130
+ 4,
1131
+ _this.getWallets()
1132
+ ];
1133
+ case 1:
1134
+ wallets = _state.sent();
1135
+ tronWallets = wallets.filter(function(wallet) {
1136
+ return wallet.chainName === 'TRON';
1137
+ });
1138
+ return [
1139
+ 2,
1140
+ tronWallets
1141
+ ];
1142
+ }
1143
+ });
1144
+ })();
1145
+ }
1146
+ },
1147
+ {
1148
+ key: "checkRawPublicKeyInstance",
1149
+ value: /**
1150
+ * Check if the raw public key is a valid ECDSA public key instance.
1151
+ */ function checkRawPublicKeyInstance(rawPublicKey) {
1152
+ if (!rawPublicKey || (typeof rawPublicKey === "undefined" ? "undefined" : _type_of(rawPublicKey)) !== 'object' || !('serializeUncompressed' in rawPublicKey) || !('pubKeyAsHex' in rawPublicKey)) {
1153
+ throw new Error(ERROR_INVALID_RAW_PUBLIC_KEY);
1154
+ }
1155
+ }
1156
+ }
1157
+ ]);
1158
+ return DynamicTronWalletClient;
1159
+ }(node.DynamicWalletClient);
1160
+
1161
+ exports.DynamicTronWalletClient = DynamicTronWalletClient;
1162
+ exports.ERROR_ACCOUNT_ADDRESS_REQUIRED = ERROR_ACCOUNT_ADDRESS_REQUIRED;
1163
+ exports.ERROR_CREATE_WALLET_ACCOUNT = ERROR_CREATE_WALLET_ACCOUNT;
1164
+ exports.ERROR_EXPORT_PRIVATE_KEY = ERROR_EXPORT_PRIVATE_KEY;
1165
+ exports.ERROR_IMPORT_PRIVATE_KEY = ERROR_IMPORT_PRIVATE_KEY;
1166
+ exports.ERROR_INVALID_RAW_PUBLIC_KEY = ERROR_INVALID_RAW_PUBLIC_KEY;
1167
+ exports.ERROR_KEYGEN_FAILED = ERROR_KEYGEN_FAILED;
1168
+ exports.ERROR_RAW_DATA_HEX_REQUIRED = ERROR_RAW_DATA_HEX_REQUIRED;
1169
+ exports.ERROR_SIGN_MESSAGE = ERROR_SIGN_MESSAGE;
1170
+ exports.ERROR_SIGN_TRANSACTION = ERROR_SIGN_TRANSACTION;
1171
+ exports.TRON_ADDRESS_PREFIX = TRON_ADDRESS_PREFIX;
1172
+ exports.TRON_NETWORKS = TRON_NETWORKS;
1173
+ exports.TRON_SIGN_MESSAGE_PREFIX = TRON_SIGN_MESSAGE_PREFIX;
1174
+ exports.decodeTronAddress = decodeTronAddress;
1175
+ exports.deriveTronAddress = deriveTronAddress;
1176
+ exports.formatTronMessage = formatTronMessage;
1177
+ exports.getTronTxId = getTronTxId;
1178
+ exports.getTronTxIdHex = getTronTxIdHex;
1179
+ exports.isValidTronAddress = isValidTronAddress;
1180
+ exports.serializeECDSASignature = serializeECDSASignature;
1181
+ exports.toTronMessageBytes = toTronMessageBytes;
1182
+ exports.tronAddressToHex = tronAddressToHex;