@dynamic-labs-wallet/tron 0.0.0 → 0.1.0-request-signing

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 (41) hide show
  1. package/index.cjs +1656 -0
  2. package/index.d.ts +1 -0
  3. package/index.esm.d.ts +1 -0
  4. package/index.esm.js +1623 -0
  5. package/package.json +35 -1
  6. package/src/client/client.d.ts +143 -0
  7. package/src/client/client.d.ts.map +1 -0
  8. package/src/client/constants.d.ts +40 -0
  9. package/src/client/constants.d.ts.map +1 -0
  10. package/src/client/index.d.ts +2 -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/signingIntent.d.ts +22 -0
  15. package/src/signingIntent.d.ts.map +1 -0
  16. package/src/tronRawData.d.ts +34 -0
  17. package/src/tronRawData.d.ts.map +1 -0
  18. package/src/types.d.ts +21 -0
  19. package/src/types.d.ts.map +1 -0
  20. package/src/utils/deriveTronAddress/deriveTronAddress.d.ts +30 -0
  21. package/src/utils/deriveTronAddress/deriveTronAddress.d.ts.map +1 -0
  22. package/src/utils/deriveTronAddress/index.d.ts +2 -0
  23. package/src/utils/deriveTronAddress/index.d.ts.map +1 -0
  24. package/src/utils/formatTronMessage/formatTronMessage.d.ts +37 -0
  25. package/src/utils/formatTronMessage/formatTronMessage.d.ts.map +1 -0
  26. package/src/utils/formatTronMessage/index.d.ts +2 -0
  27. package/src/utils/formatTronMessage/index.d.ts.map +1 -0
  28. package/src/utils/getTronTxId/getTronTxId.d.ts +17 -0
  29. package/src/utils/getTronTxId/getTronTxId.d.ts.map +1 -0
  30. package/src/utils/getTronTxId/index.d.ts +2 -0
  31. package/src/utils/getTronTxId/index.d.ts.map +1 -0
  32. package/src/utils/index.d.ts +6 -0
  33. package/src/utils/index.d.ts.map +1 -0
  34. package/src/utils/resolveTronSigningContext/index.d.ts +2 -0
  35. package/src/utils/resolveTronSigningContext/index.d.ts.map +1 -0
  36. package/src/utils/resolveTronSigningContext/resolveTronSigningContext.d.ts +9 -0
  37. package/src/utils/resolveTronSigningContext/resolveTronSigningContext.d.ts.map +1 -0
  38. package/src/utils/serializeECDSASignature/index.d.ts +2 -0
  39. package/src/utils/serializeECDSASignature/index.d.ts.map +1 -0
  40. package/src/utils/serializeECDSASignature/serializeECDSASignature.d.ts +13 -0
  41. package/src/utils/serializeECDSASignature/serializeECDSASignature.d.ts.map +1 -0
package/index.esm.js ADDED
@@ -0,0 +1,1623 @@
1
+ import { DynamicWalletClient, ERROR_PASSWORD_MISMATCH, ERROR_MULTIPLE_WALLETS_PER_CHAIN, getMPCChainConfig, SigningConsentRequiredError } from '@dynamic-labs-wallet/browser';
2
+ import { keccak_256 } from '@noble/hashes/sha3';
3
+ import { sha256 } from '@noble/hashes/sha256';
4
+ import bs58 from 'bs58';
5
+ import { SignMessageRawSignHashFunctionEnum } from '@dynamic-labs/sdk-api-core';
6
+ import * as sdkApiCore from '@dynamic-labs/sdk-api-core';
7
+ export { sdkApiCore };
8
+
9
+ /**
10
+ * Mainnet address prefix byte for TRON addresses. Shasta and Nile testnets
11
+ * use the same prefix; the network is disambiguated at the node/relay layer
12
+ * (TRON does not embed a network byte into the address).
13
+ *
14
+ * @see https://github.com/tronprotocol/tips/blob/master/tip-21.md
15
+ */ var TRON_ADDRESS_PREFIX = 0x41;
16
+ /**
17
+ * Length of the Base58Check checksum appended to a TRON address payload.
18
+ */ var TRON_CHECKSUM_LENGTH = 4;
19
+ /**
20
+ * Length of the encoded (un-prefixed) Base58Check TRON address.
21
+ * `T...` addresses are always 34 characters.
22
+ */ var TRON_ADDRESS_LENGTH$1 = 34;
23
+ /**
24
+ * Derive a TRON Base58Check ("T...") address from a secp256k1 public key.
25
+ *
26
+ * TRON addresses are the keccak256 hash of the uncompressed public key
27
+ * (with the leading 0x04 byte stripped), taking the last 20 bytes, prefixed
28
+ * with 0x41, then encoded as Base58Check (SHA256d checksum).
29
+ *
30
+ * Mainnet, Shasta, and Nile share the same address format — the network is
31
+ * resolved by the RPC endpoint, not the address itself.
32
+ *
33
+ * @see https://github.com/tronprotocol/tips/blob/master/tip-21.md
34
+ */ var hexToBytes$1 = function(hex) {
35
+ var buf = Buffer.from(hex, 'hex');
36
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
37
+ };
38
+ var deriveTronAddress = function(param) {
39
+ var publicKeyHex = param.publicKeyHex;
40
+ var cleanHex = publicKeyHex.startsWith('0x') ? publicKeyHex.slice(2) : publicKeyHex;
41
+ var publicKeyBytes = hexToBytes$1(cleanHex);
42
+ // Allow either 65-byte uncompressed (0x04 || X || Y) or 64-byte X||Y form.
43
+ var xy;
44
+ if (publicKeyBytes.length === 65) {
45
+ if (publicKeyBytes[0] !== 0x04) {
46
+ throw new Error("Invalid uncompressed public key prefix: expected 0x04, got 0x".concat(publicKeyBytes[0].toString(16)));
47
+ }
48
+ xy = publicKeyBytes.subarray(1);
49
+ } else if (publicKeyBytes.length === 64) {
50
+ xy = publicKeyBytes;
51
+ } else {
52
+ throw new Error("Invalid public key length: ".concat(publicKeyBytes.length, ", expected 64 (X||Y) or 65 (uncompressed)"));
53
+ }
54
+ var hashed = keccak_256(xy);
55
+ var lastTwentyBytes = hashed.slice(-20);
56
+ var payload = new Uint8Array(21);
57
+ payload[0] = TRON_ADDRESS_PREFIX;
58
+ payload.set(lastTwentyBytes, 1);
59
+ var checksum = sha256(sha256(payload)).slice(0, TRON_CHECKSUM_LENGTH);
60
+ var addressBytes = new Uint8Array(payload.length + TRON_CHECKSUM_LENGTH);
61
+ addressBytes.set(payload, 0);
62
+ addressBytes.set(checksum, payload.length);
63
+ return bs58.encode(addressBytes);
64
+ };
65
+ /**
66
+ * Validate a TRON Base58Check address.
67
+ *
68
+ * Performs the full decode + checksum + prefix check, so it rejects EVM
69
+ * `0x...` addresses, malformed Base58, and addresses whose checksum was
70
+ * tampered with.
71
+ */ var isValidTronAddress = function(address) {
72
+ if (typeof address !== 'string' || address.length !== TRON_ADDRESS_LENGTH$1) {
73
+ return false;
74
+ }
75
+ var decoded;
76
+ try {
77
+ decoded = bs58.decode(address);
78
+ } catch (e) {
79
+ return false;
80
+ }
81
+ if (decoded.length !== 25 || decoded[0] !== TRON_ADDRESS_PREFIX) {
82
+ return false;
83
+ }
84
+ var payload = decoded.subarray(0, 21);
85
+ var expectedChecksum = decoded.subarray(21);
86
+ var actualChecksum = sha256(sha256(payload)).slice(0, TRON_CHECKSUM_LENGTH);
87
+ for(var i = 0; i < TRON_CHECKSUM_LENGTH; i++){
88
+ if (expectedChecksum[i] !== actualChecksum[i]) {
89
+ return false;
90
+ }
91
+ }
92
+ return true;
93
+ };
94
+ /**
95
+ * Decode a TRON Base58Check address to its 21-byte payload (prefix + 20-byte
96
+ * hash). Throws if the checksum doesn't validate.
97
+ */ var decodeTronAddress = function(address) {
98
+ if (!isValidTronAddress(address)) {
99
+ throw new Error('Invalid TRON address');
100
+ }
101
+ return bs58.decode(address).subarray(0, 21);
102
+ };
103
+ /**
104
+ * Convert a TRON Base58Check address to its 0x41-prefixed hex form (used in
105
+ * raw transactions).
106
+ */ var tronAddressToHex = function(address) {
107
+ var payload = decodeTronAddress(address);
108
+ return "0x".concat(Buffer.from(payload).toString('hex'));
109
+ };
110
+
111
+ function _instanceof$2(left, right) {
112
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
113
+ return !!right[Symbol.hasInstance](left);
114
+ } else {
115
+ return left instanceof right;
116
+ }
117
+ }
118
+ /**
119
+ * TIP-191 personal-sign prefix used by TRON for signed messages.
120
+ *
121
+ * The hash that gets signed is:
122
+ * keccak256("\x19TRON Signed Message:\n" || len(message) || message)
123
+ *
124
+ * where `message` is the raw bytes the user agreed to sign.
125
+ *
126
+ * @see https://github.com/tronprotocol/tips/blob/master/tip-191.md
127
+ */ var TRON_SIGN_MESSAGE_PREFIX = '\x19TRON Signed Message:\n';
128
+ var bufferToUint8Array = function(buf) {
129
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
130
+ };
131
+ var stringToBytes = function(s) {
132
+ return bufferToUint8Array(Buffer.from(s, 'utf8'));
133
+ };
134
+ var hexToBytes = function(hex) {
135
+ var clean = hex.startsWith('0x') ? hex.slice(2) : hex;
136
+ return bufferToUint8Array(Buffer.from(clean, 'hex'));
137
+ };
138
+ /**
139
+ * Convert a user-supplied message into the bytes that TIP-191 expects to be
140
+ * hashed. Mirrors the shape of `formatTempoMessage` so the wallet client can
141
+ * treat both chains uniformly.
142
+ *
143
+ * - `string` starting with `0x` → treated as hex bytes
144
+ * - `string` otherwise → treated as utf-8 bytes
145
+ * - `Uint8Array` → passed through
146
+ * - `{ raw: ... }` → mirrors viem's `{ raw }` escape hatch for already-hashed payloads
147
+ */ var toTronMessageBytes = function(message) {
148
+ if (_instanceof$2(message, Uint8Array)) return message;
149
+ if (typeof message === 'string') {
150
+ return message.startsWith('0x') ? hexToBytes(message) : stringToBytes(message);
151
+ }
152
+ if (typeof message.raw === 'string') return hexToBytes(message.raw);
153
+ return message.raw;
154
+ };
155
+ /**
156
+ * Apply the TIP-191 prefix and return the keccak256 hash that should be
157
+ * signed by the MPC ECDSA flow.
158
+ *
159
+ * Returns a `Uint8Array` (32 bytes). The wallet client converts this into a
160
+ * `MessageHash` (`isFormatted: true`) before handing it to `sign(...)` so
161
+ * the forward-MPC path sees a pre-hashed payload.
162
+ */ var formatTronMessage = function(message, logger) {
163
+ try {
164
+ var bytes = toTronMessageBytes(message);
165
+ var prefixBytes = stringToBytes("".concat(TRON_SIGN_MESSAGE_PREFIX).concat(bytes.length));
166
+ var combined = new Uint8Array(prefixBytes.length + bytes.length);
167
+ combined.set(prefixBytes, 0);
168
+ combined.set(bytes, prefixBytes.length);
169
+ return keccak_256(combined);
170
+ } catch (error) {
171
+ logger.error('[DynamicTronWalletClient]: Error formatting TRON message:', error);
172
+ throw error;
173
+ }
174
+ };
175
+
176
+ /**
177
+ * TRON transactions are signed over `sha256(raw_data_hex_bytes)`, where
178
+ * `raw_data_hex` is the protobuf-encoded `Transaction.raw` produced by the
179
+ * TRON full node when the unsigned transaction is created.
180
+ *
181
+ * The MPC client never reconstructs the protobuf itself — the caller passes
182
+ * the already-serialized `raw_data_hex` and we hash it deterministically here.
183
+ *
184
+ * @see https://developers.tron.network/docs/transactions
185
+ */ var getTronTxId = function(rawDataHex) {
186
+ var clean = rawDataHex.startsWith('0x') ? rawDataHex.slice(2) : rawDataHex;
187
+ if (clean.length === 0 || clean.length % 2 !== 0 || /[^0-9a-fA-F]/.test(clean)) {
188
+ throw new Error('Invalid raw_data_hex: must be a non-empty hex string');
189
+ }
190
+ var buf = Buffer.from(clean, 'hex');
191
+ return sha256(new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength));
192
+ };
193
+ /**
194
+ * Convenience wrapper that returns the txID as a 0x-prefixed hex string
195
+ * (matching the form returned by the TRON full node `/wallet/gettransactioninfobyid`).
196
+ */ var getTronTxIdHex = function(rawDataHex) {
197
+ var hash = getTronTxId(rawDataHex);
198
+ return "0x".concat(Buffer.from(hash).toString('hex'));
199
+ };
200
+
201
+ function _instanceof$1(left, right) {
202
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
203
+ return !!right[Symbol.hasInstance](left);
204
+ } else {
205
+ return left instanceof right;
206
+ }
207
+ }
208
+ /**
209
+ * Serialize an MPC-produced ECDSA signature into the 65-byte
210
+ * `r || s || v` hex form that TRON full nodes expect on
211
+ * `Transaction.signature[0]` and TIP-191 signed messages.
212
+ *
213
+ * TRON canonicalises v to 0 / 1 on the wire (recovery id), while the MPC
214
+ * relay returns v as 27 / 28 (Ethereum legacy convention). We strip the +27
215
+ * offset here so the output is directly usable by TRON tooling without
216
+ * the consumer having to remember the convention.
217
+ */ var serializeECDSASignature = function(signature, logger) {
218
+ try {
219
+ var r = Buffer.from(signature.r).toString('hex');
220
+ var s = Buffer.from(signature.s).toString('hex');
221
+ if (r.length !== 64 || s.length !== 64) {
222
+ throw new Error("Invalid ECDSA r/s length: r=".concat(r.length, ", s=").concat(s.length, " (expected 64 hex chars each)"));
223
+ }
224
+ var vNum = Number(signature.v);
225
+ if (!Number.isFinite(vNum)) {
226
+ throw new TypeError("Invalid ECDSA v: ".concat(signature.v));
227
+ }
228
+ var recoveryId = vNum >= 27 ? vNum - 27 : vNum;
229
+ if (recoveryId !== 0 && recoveryId !== 1) {
230
+ throw new Error("Invalid ECDSA recovery id derived from v=".concat(vNum, ": ").concat(recoveryId));
231
+ }
232
+ var vHex = recoveryId.toString(16).padStart(2, '0');
233
+ return "0x".concat(r).concat(s).concat(vHex);
234
+ } catch (error) {
235
+ logger.error('[DynamicTronWalletClient]: Error serializing ECDSA signature:', _instanceof$1(error, Error) ? error.message : String(error));
236
+ throw error;
237
+ }
238
+ };
239
+
240
+ function _define_property$2(obj, key, value) {
241
+ if (key in obj) {
242
+ Object.defineProperty(obj, key, {
243
+ value: value,
244
+ enumerable: true,
245
+ configurable: true,
246
+ writable: true
247
+ });
248
+ } else {
249
+ obj[key] = value;
250
+ }
251
+ return obj;
252
+ }
253
+ function _object_spread$2(target) {
254
+ for(var i = 1; i < arguments.length; i++){
255
+ var source = arguments[i] != null ? arguments[i] : {};
256
+ var ownKeys = Object.keys(source);
257
+ if (typeof Object.getOwnPropertySymbols === "function") {
258
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
259
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
260
+ }));
261
+ }
262
+ ownKeys.forEach(function(key) {
263
+ _define_property$2(target, key, source[key]);
264
+ });
265
+ }
266
+ return target;
267
+ }
268
+ function ownKeys$1(object, enumerableOnly) {
269
+ var keys = Object.keys(object);
270
+ if (Object.getOwnPropertySymbols) {
271
+ var symbols = Object.getOwnPropertySymbols(object);
272
+ keys.push.apply(keys, symbols);
273
+ }
274
+ return keys;
275
+ }
276
+ function _object_spread_props$1(target, source) {
277
+ source = source != null ? source : {};
278
+ if (Object.getOwnPropertyDescriptors) {
279
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
280
+ } else {
281
+ ownKeys$1(Object(source)).forEach(function(key) {
282
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
283
+ });
284
+ }
285
+ return target;
286
+ }
287
+ var HEX_CHAIN_ID = /^0x[0-9a-f]+$/i;
288
+ var normalizeTronChainId = function(chainId) {
289
+ return HEX_CHAIN_ID.test(chainId) ? BigInt(chainId).toString() : chainId;
290
+ };
291
+ var resolveTronTransactionContext = function(param) {
292
+ var context = param.context, chainId = param.chainId, rawDataHex = param.rawDataHex;
293
+ if ((context === null || context === void 0 ? void 0 : context.tronTransaction) !== undefined) {
294
+ return context;
295
+ }
296
+ var base = _object_spread$2({}, context);
297
+ delete base.rawSign;
298
+ if (chainId !== undefined) {
299
+ return _object_spread_props$1(_object_spread$2({}, base), {
300
+ tronTransaction: {
301
+ chainId: normalizeTronChainId(chainId),
302
+ rawDataHex: rawDataHex
303
+ }
304
+ });
305
+ }
306
+ return _object_spread_props$1(_object_spread$2({}, base), {
307
+ rawSign: {
308
+ hashFunction: SignMessageRawSignHashFunctionEnum.Sha256,
309
+ payload: rawDataHex
310
+ }
311
+ });
312
+ };
313
+ var resolveTronMessageContext = function(context, message) {
314
+ if ((context === null || context === void 0 ? void 0 : context.tronMessage) !== undefined || (context === null || context === void 0 ? void 0 : context.rawSign) !== undefined) {
315
+ return context;
316
+ }
317
+ return _object_spread_props$1(_object_spread$2({}, context), {
318
+ tronMessage: message
319
+ });
320
+ };
321
+
322
+ var ERROR_KEYGEN_FAILED = 'Error with keygen';
323
+ var ERROR_CREATE_WALLET_ACCOUNT = 'Error creating TRON wallet account';
324
+ var ERROR_IMPORT_PRIVATE_KEY = 'Error importing private key';
325
+ var ERROR_EXPORT_PRIVATE_KEY = 'Error exporting private key';
326
+ var ERROR_SIGN_MESSAGE = 'Error signing message';
327
+ var ERROR_SIGN_TRANSACTION = 'Error signing transaction';
328
+ var ERROR_ACCOUNT_ADDRESS_REQUIRED = 'Account address is required';
329
+ var ERROR_RAW_DATA_HEX_REQUIRED = 'Transaction raw_data_hex is required';
330
+ var ERROR_INVALID_RAW_PUBLIC_KEY = 'Invalid raw public key instance';
331
+
332
+ function _array_like_to_array(arr, len) {
333
+ if (len == null || len > arr.length) len = arr.length;
334
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
335
+ return arr2;
336
+ }
337
+ function _array_without_holes(arr) {
338
+ if (Array.isArray(arr)) return _array_like_to_array(arr);
339
+ }
340
+ function _assert_this_initialized(self) {
341
+ if (self === void 0) {
342
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
343
+ }
344
+ return self;
345
+ }
346
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
347
+ try {
348
+ var info = gen[key](arg);
349
+ var value = info.value;
350
+ } catch (error) {
351
+ reject(error);
352
+ return;
353
+ }
354
+ if (info.done) {
355
+ resolve(value);
356
+ } else {
357
+ Promise.resolve(value).then(_next, _throw);
358
+ }
359
+ }
360
+ function _async_to_generator(fn) {
361
+ return function() {
362
+ var self = this, args = arguments;
363
+ return new Promise(function(resolve, reject) {
364
+ var gen = fn.apply(self, args);
365
+ function _next(value) {
366
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
367
+ }
368
+ function _throw(err) {
369
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
370
+ }
371
+ _next(undefined);
372
+ });
373
+ };
374
+ }
375
+ function _call_super(_this, derived, args) {
376
+ derived = _get_prototype_of(derived);
377
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
378
+ }
379
+ function _class_call_check(instance, Constructor) {
380
+ if (!(instance instanceof Constructor)) {
381
+ throw new TypeError("Cannot call a class as a function");
382
+ }
383
+ }
384
+ function _defineProperties(target, props) {
385
+ for(var i = 0; i < props.length; i++){
386
+ var descriptor = props[i];
387
+ descriptor.enumerable = descriptor.enumerable || false;
388
+ descriptor.configurable = true;
389
+ if ("value" in descriptor) descriptor.writable = true;
390
+ Object.defineProperty(target, descriptor.key, descriptor);
391
+ }
392
+ }
393
+ function _create_class(Constructor, protoProps, staticProps) {
394
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
395
+ return Constructor;
396
+ }
397
+ function _define_property$1(obj, key, value) {
398
+ if (key in obj) {
399
+ Object.defineProperty(obj, key, {
400
+ value: value,
401
+ enumerable: true,
402
+ configurable: true,
403
+ writable: true
404
+ });
405
+ } else {
406
+ obj[key] = value;
407
+ }
408
+ return obj;
409
+ }
410
+ function _get_prototype_of(o) {
411
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
412
+ return o.__proto__ || Object.getPrototypeOf(o);
413
+ };
414
+ return _get_prototype_of(o);
415
+ }
416
+ function _inherits(subClass, superClass) {
417
+ if (typeof superClass !== "function" && superClass !== null) {
418
+ throw new TypeError("Super expression must either be null or a function");
419
+ }
420
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
421
+ constructor: {
422
+ value: subClass,
423
+ writable: true,
424
+ configurable: true
425
+ }
426
+ });
427
+ if (superClass) _set_prototype_of(subClass, superClass);
428
+ }
429
+ function _instanceof(left, right) {
430
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
431
+ return !!right[Symbol.hasInstance](left);
432
+ } else {
433
+ return left instanceof right;
434
+ }
435
+ }
436
+ function _iterable_to_array(iter) {
437
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
438
+ }
439
+ function _non_iterable_spread() {
440
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
441
+ }
442
+ function _object_spread$1(target) {
443
+ for(var i = 1; i < arguments.length; i++){
444
+ var source = arguments[i] != null ? arguments[i] : {};
445
+ var ownKeys = Object.keys(source);
446
+ if (typeof Object.getOwnPropertySymbols === "function") {
447
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
448
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
449
+ }));
450
+ }
451
+ ownKeys.forEach(function(key) {
452
+ _define_property$1(target, key, source[key]);
453
+ });
454
+ }
455
+ return target;
456
+ }
457
+ function ownKeys(object, enumerableOnly) {
458
+ var keys = Object.keys(object);
459
+ if (Object.getOwnPropertySymbols) {
460
+ var symbols = Object.getOwnPropertySymbols(object);
461
+ keys.push.apply(keys, symbols);
462
+ }
463
+ return keys;
464
+ }
465
+ function _object_spread_props(target, source) {
466
+ source = source != null ? source : {};
467
+ if (Object.getOwnPropertyDescriptors) {
468
+ Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
469
+ } else {
470
+ ownKeys(Object(source)).forEach(function(key) {
471
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
472
+ });
473
+ }
474
+ return target;
475
+ }
476
+ function _possible_constructor_return(self, call) {
477
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
478
+ return call;
479
+ }
480
+ return _assert_this_initialized(self);
481
+ }
482
+ function _set_prototype_of(o, p) {
483
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
484
+ o.__proto__ = p;
485
+ return o;
486
+ };
487
+ return _set_prototype_of(o, p);
488
+ }
489
+ function _to_consumable_array(arr) {
490
+ return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
491
+ }
492
+ function _type_of(obj) {
493
+ "@swc/helpers - typeof";
494
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
495
+ }
496
+ function _unsupported_iterable_to_array(o, minLen) {
497
+ if (!o) return;
498
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
499
+ var n = Object.prototype.toString.call(o).slice(8, -1);
500
+ if (n === "Object" && o.constructor) n = o.constructor.name;
501
+ if (n === "Map" || n === "Set") return Array.from(n);
502
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
503
+ }
504
+ function _is_native_reflect_construct() {
505
+ try {
506
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
507
+ } catch (_) {}
508
+ return (_is_native_reflect_construct = function() {
509
+ return !!result;
510
+ })();
511
+ }
512
+ function _ts_generator(thisArg, body) {
513
+ var f, y, t, g, _ = {
514
+ label: 0,
515
+ sent: function() {
516
+ if (t[0] & 1) throw t[1];
517
+ return t[1];
518
+ },
519
+ trys: [],
520
+ ops: []
521
+ };
522
+ return g = {
523
+ next: verb(0),
524
+ "throw": verb(1),
525
+ "return": verb(2)
526
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
527
+ return this;
528
+ }), g;
529
+ function verb(n) {
530
+ return function(v) {
531
+ return step([
532
+ n,
533
+ v
534
+ ]);
535
+ };
536
+ }
537
+ function step(op) {
538
+ if (f) throw new TypeError("Generator is already executing.");
539
+ while(_)try {
540
+ 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;
541
+ if (y = 0, t) op = [
542
+ op[0] & 2,
543
+ t.value
544
+ ];
545
+ switch(op[0]){
546
+ case 0:
547
+ case 1:
548
+ t = op;
549
+ break;
550
+ case 4:
551
+ _.label++;
552
+ return {
553
+ value: op[1],
554
+ done: false
555
+ };
556
+ case 5:
557
+ _.label++;
558
+ y = op[1];
559
+ op = [
560
+ 0
561
+ ];
562
+ continue;
563
+ case 7:
564
+ op = _.ops.pop();
565
+ _.trys.pop();
566
+ continue;
567
+ default:
568
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
569
+ _ = 0;
570
+ continue;
571
+ }
572
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
573
+ _.label = op[1];
574
+ break;
575
+ }
576
+ if (op[0] === 6 && _.label < t[1]) {
577
+ _.label = t[1];
578
+ t = op;
579
+ break;
580
+ }
581
+ if (t && _.label < t[2]) {
582
+ _.label = t[2];
583
+ _.ops.push(op);
584
+ break;
585
+ }
586
+ if (t[2]) _.ops.pop();
587
+ _.trys.pop();
588
+ continue;
589
+ }
590
+ op = body.call(thisArg, _);
591
+ } catch (e) {
592
+ op = [
593
+ 6,
594
+ e
595
+ ];
596
+ y = 0;
597
+ } finally{
598
+ f = t = 0;
599
+ }
600
+ if (op[0] & 5) throw op[1];
601
+ return {
602
+ value: op[0] ? op[1] : void 0,
603
+ done: true
604
+ };
605
+ }
606
+ }
607
+ /**
608
+ * Wallet client for TRON (SLIP-44 coin type 195, secp256k1 / ECDSA).
609
+ *
610
+ * V1 surface (matches the locked Wave C-1 handoff):
611
+ * - create / signMessageV2 / signTransaction / importPrivateKey / exportPrivateKey
612
+ * - No legacy V1 message signing (`signMessage` returns a TIP-191 result;
613
+ * consumers should call `signMessageV2`).
614
+ * - Networks (Mainnet / Shasta / Nile) share the same address format and
615
+ * keyshare namespace; the network is selected at the broadcast layer
616
+ * via the raw_data the caller assembles against the full node of their
617
+ * choice. See `TRON_NETWORKS` in `./constants`.
618
+ *
619
+ * Address derivation: keccak256 of the uncompressed secp256k1 public key
620
+ * (minus the 0x04 prefix), last 20 bytes, prefixed with 0x41, encoded as
621
+ * Base58Check (`T...`).
622
+ *
623
+ * Transaction signing: SHA-256 of `raw_data_hex` is the digest, sent through
624
+ * the forward-MPC path as a pre-hashed (`isFormatted: true`) payload.
625
+ *
626
+ * Message signing (TIP-191): keccak256 of `\x19TRON Signed Message:\n<len><msg>`.
627
+ */ var DynamicTronWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
628
+ _inherits(DynamicTronWalletClient, DynamicWalletClient);
629
+ function DynamicTronWalletClient() {
630
+ _class_call_check(this, DynamicTronWalletClient);
631
+ var _this;
632
+ _this = _call_super(this, DynamicTronWalletClient, arguments), _define_property$1(_this, "chainName", 'TRON');
633
+ return _this;
634
+ }
635
+ _create_class(DynamicTronWalletClient, [
636
+ {
637
+ key: "createWalletAccount",
638
+ value: /**
639
+ * Create a new TRON wallet account using MPC key generation.
640
+ */ function createWalletAccount(param) {
641
+ var thresholdSignatureScheme = param.thresholdSignatureScheme, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, onError = param.onError, signedSessionId = param.signedSessionId; param.traceContext; var businessAccountId = param.businessAccountId;
642
+ var _this = this;
643
+ return _async_to_generator(function() {
644
+ var ceremonyCompleteResolver, ceremonyCompletePromise, _ref, rawPublicKey, clientKeyShares, _this_deriveAccountAddress, accountAddress, publicKeyHex, error;
645
+ return _ts_generator(this, function(_state) {
646
+ switch(_state.label){
647
+ case 0:
648
+ _state.trys.push([
649
+ 0,
650
+ 5,
651
+ ,
652
+ 6
653
+ ]);
654
+ ceremonyCompletePromise = new Promise(function(resolve) {
655
+ ceremonyCompleteResolver = resolve;
656
+ });
657
+ return [
658
+ 4,
659
+ _this.keyGen({
660
+ chainName: _this.chainName,
661
+ businessAccountId: businessAccountId,
662
+ thresholdSignatureScheme: thresholdSignatureScheme,
663
+ onError: function(error) {
664
+ _this.logger.error(ERROR_CREATE_WALLET_ACCOUNT, error);
665
+ onError === null || onError === void 0 ? void 0 : onError(error);
666
+ },
667
+ onCeremonyComplete: function(param) {
668
+ var accountAddress = param.accountAddress, walletId = param.walletId, shareSetId = param.shareSetId;
669
+ var chainConfig = getMPCChainConfig(_this.chainName);
670
+ _this.initializeWalletMapEntry({
671
+ accountAddress: accountAddress,
672
+ walletId: walletId,
673
+ chainName: _this.chainName,
674
+ thresholdSignatureScheme: thresholdSignatureScheme,
675
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map(function(value, index) {
676
+ return [
677
+ index,
678
+ value
679
+ ];
680
+ }))),
681
+ shareSetId: shareSetId
682
+ });
683
+ ceremonyCompleteResolver(undefined);
684
+ },
685
+ password: password,
686
+ signedSessionId: signedSessionId
687
+ })
688
+ ];
689
+ case 1:
690
+ _ref = _state.sent(), rawPublicKey = _ref.rawPublicKey, clientKeyShares = _ref.clientKeyShares;
691
+ return [
692
+ 4,
693
+ ceremonyCompletePromise
694
+ ];
695
+ case 2:
696
+ _state.sent();
697
+ if (!rawPublicKey || !clientKeyShares) {
698
+ throw new Error(ERROR_KEYGEN_FAILED);
699
+ }
700
+ _this.checkRawPublicKeyInstance(rawPublicKey);
701
+ _this_deriveAccountAddress = _this.deriveAccountAddress({
702
+ rawPublicKey: rawPublicKey
703
+ }), accountAddress = _this_deriveAccountAddress.accountAddress, publicKeyHex = _this_deriveAccountAddress.publicKeyHex;
704
+ return [
705
+ 4,
706
+ _this.setClientKeySharesToStorage({
707
+ accountAddress: accountAddress,
708
+ clientKeyShares: clientKeyShares
709
+ })
710
+ ];
711
+ case 3:
712
+ _state.sent();
713
+ return [
714
+ 4,
715
+ _this.storeEncryptedBackupByWallet({
716
+ accountAddress: accountAddress,
717
+ clientKeyShares: clientKeyShares,
718
+ password: password,
719
+ signedSessionId: signedSessionId,
720
+ businessAccountId: businessAccountId
721
+ })
722
+ ];
723
+ case 4:
724
+ _state.sent();
725
+ return [
726
+ 2,
727
+ {
728
+ accountAddress: accountAddress,
729
+ rawPublicKey: rawPublicKey,
730
+ publicKeyHex: publicKeyHex
731
+ }
732
+ ];
733
+ case 5:
734
+ error = _state.sent();
735
+ if (_instanceof(error, Error) && (error.message === ERROR_PASSWORD_MISMATCH || error.message === ERROR_MULTIPLE_WALLETS_PER_CHAIN)) {
736
+ throw error;
737
+ }
738
+ _this.logger.error(ERROR_CREATE_WALLET_ACCOUNT, error);
739
+ throw new Error(ERROR_CREATE_WALLET_ACCOUNT, {
740
+ cause: error
741
+ });
742
+ case 6:
743
+ return [
744
+ 2
745
+ ];
746
+ }
747
+ });
748
+ })();
749
+ }
750
+ },
751
+ {
752
+ key: "signMessage",
753
+ value: /**
754
+ * TIP-191 personal-sign for TRON. This is the `signMessageV2` surface
755
+ * referenced in the rollout — there is no V1 legacy message-sign path.
756
+ *
757
+ * The TIP-191 prefix + keccak256 hashing happens client-side; the resulting
758
+ * 32-byte digest is sent to the forward-MPC relay as `isFormatted: true`
759
+ * (matches the EVM/TEMPO forward-MPC contract).
760
+ */ function signMessage(param) {
761
+ var message = param.message, accountAddress = param.accountAddress, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, context = param.context, approvalQuorum = param.approvalQuorum, onError = param.onError, traceContext = param.traceContext;
762
+ var _this = this;
763
+ return _async_to_generator(function() {
764
+ var digest, signatureEcdsa, error;
765
+ return _ts_generator(this, function(_state) {
766
+ switch(_state.label){
767
+ case 0:
768
+ if (!accountAddress) {
769
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
770
+ }
771
+ return [
772
+ 4,
773
+ _this.verifyPassword({
774
+ accountAddress: accountAddress,
775
+ password: password,
776
+ signedSessionId: signedSessionId
777
+ })
778
+ ];
779
+ case 1:
780
+ _state.sent();
781
+ _state.label = 2;
782
+ case 2:
783
+ _state.trys.push([
784
+ 2,
785
+ 4,
786
+ ,
787
+ 5
788
+ ]);
789
+ digest = formatTronMessage(message, _this.logger);
790
+ return [
791
+ 4,
792
+ _this.sign({
793
+ message: digest,
794
+ accountAddress: accountAddress,
795
+ chainName: _this.chainName,
796
+ password: password,
797
+ signedSessionId: signedSessionId,
798
+ isFormatted: true,
799
+ mfaToken: mfaToken,
800
+ elevatedAccessToken: elevatedAccessToken,
801
+ context: resolveTronMessageContext(context, message),
802
+ approvalQuorum: approvalQuorum,
803
+ onError: onError,
804
+ traceContext: traceContext
805
+ })
806
+ ];
807
+ case 3:
808
+ signatureEcdsa = _state.sent();
809
+ return [
810
+ 2,
811
+ serializeECDSASignature(signatureEcdsa, _this.logger)
812
+ ];
813
+ case 4:
814
+ error = _state.sent();
815
+ _this.logOperationFailure(ERROR_SIGN_MESSAGE, error);
816
+ throw new Error(ERROR_SIGN_MESSAGE, {
817
+ cause: error
818
+ });
819
+ case 5:
820
+ return [
821
+ 2
822
+ ];
823
+ }
824
+ });
825
+ })();
826
+ }
827
+ },
828
+ {
829
+ key: "prepareSignMessage",
830
+ value: function prepareSignMessage(param) {
831
+ var message = param.message;
832
+ return "0x".concat(Buffer.from(formatTronMessage(message, this.logger)).toString('hex'));
833
+ }
834
+ },
835
+ {
836
+ key: "signTransaction",
837
+ value: /**
838
+ * Sign a TRON transaction.
839
+ *
840
+ * The caller supplies the unsigned `raw_data_hex` produced by a TRON full
841
+ * node (e.g. `/wallet/createtransaction` or `/wallet/triggersmartcontract`),
842
+ * either as a parsed `TronTransaction` object or as the JSON string that
843
+ * came back from the full node. The MPC signer hashes those bytes with
844
+ * SHA-256 (the TRON `txID`) and signs the digest.
845
+ *
846
+ * Returns the entire signed transaction (with the new signature appended to
847
+ * `transaction.signature[]`) as a JSON string, ready to be passed to the
848
+ * full-node `/wallet/broadcasttransaction` endpoint. Returning a string
849
+ * (rather than the object) matches the SDK's iframe `signTransaction`
850
+ * contract, which only carries strings over message transport.
851
+ */ function signTransaction(param) {
852
+ var senderAddress = param.senderAddress, transaction = param.transaction, chainId = param.chainId, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, context = param.context, approvalQuorum = param.approvalQuorum, onError = param.onError, traceContext = param.traceContext;
853
+ var _this = this;
854
+ return _async_to_generator(function() {
855
+ var rawParsed, parsedTransaction, digestBytes, txid, resolvedContext, signatureEcdsa, serializedSig, hexSig, _parsedTransaction_signature, existingSignatures, _parsedTransaction_txID, signed, error;
856
+ return _ts_generator(this, function(_state) {
857
+ switch(_state.label){
858
+ case 0:
859
+ if (!senderAddress) {
860
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
861
+ }
862
+ rawParsed = transaction;
863
+ if (typeof transaction === 'string') {
864
+ try {
865
+ rawParsed = JSON.parse(transaction);
866
+ } catch (e) {
867
+ throw new Error(ERROR_RAW_DATA_HEX_REQUIRED);
868
+ }
869
+ }
870
+ if (!rawParsed || (typeof rawParsed === "undefined" ? "undefined" : _type_of(rawParsed)) !== 'object' || typeof rawParsed.raw_data_hex !== 'string' || rawParsed.raw_data_hex.length === 0) {
871
+ throw new Error(ERROR_RAW_DATA_HEX_REQUIRED);
872
+ }
873
+ parsedTransaction = rawParsed;
874
+ return [
875
+ 4,
876
+ _this.verifyPassword({
877
+ accountAddress: senderAddress,
878
+ password: password,
879
+ signedSessionId: signedSessionId
880
+ })
881
+ ];
882
+ case 1:
883
+ _state.sent();
884
+ _state.label = 2;
885
+ case 2:
886
+ _state.trys.push([
887
+ 2,
888
+ 4,
889
+ ,
890
+ 5
891
+ ]);
892
+ digestBytes = getTronTxId(parsedTransaction.raw_data_hex);
893
+ txid = getTronTxIdHex(parsedTransaction.raw_data_hex);
894
+ resolvedContext = resolveTronTransactionContext({
895
+ context: context,
896
+ chainId: chainId,
897
+ rawDataHex: parsedTransaction.raw_data_hex
898
+ });
899
+ return [
900
+ 4,
901
+ _this.sign({
902
+ message: digestBytes,
903
+ accountAddress: senderAddress,
904
+ chainName: _this.chainName,
905
+ password: password,
906
+ signedSessionId: signedSessionId,
907
+ isFormatted: true,
908
+ mfaToken: mfaToken,
909
+ elevatedAccessToken: elevatedAccessToken,
910
+ context: resolvedContext,
911
+ approvalQuorum: approvalQuorum,
912
+ onError: onError,
913
+ traceContext: traceContext
914
+ })
915
+ ];
916
+ case 3:
917
+ signatureEcdsa = _state.sent();
918
+ serializedSig = serializeECDSASignature(signatureEcdsa, _this.logger);
919
+ hexSig = serializedSig.slice(2);
920
+ existingSignatures = (_parsedTransaction_signature = parsedTransaction.signature) !== null && _parsedTransaction_signature !== void 0 ? _parsedTransaction_signature : [];
921
+ signed = _object_spread_props(_object_spread$1({}, parsedTransaction), {
922
+ txID: (_parsedTransaction_txID = parsedTransaction.txID) !== null && _parsedTransaction_txID !== void 0 ? _parsedTransaction_txID : txid.slice(2),
923
+ signature: _to_consumable_array(existingSignatures).concat([
924
+ hexSig
925
+ ])
926
+ });
927
+ return [
928
+ 2,
929
+ JSON.stringify(signed)
930
+ ];
931
+ case 4:
932
+ error = _state.sent();
933
+ _this.logOperationFailure(ERROR_SIGN_TRANSACTION, error);
934
+ throw new Error(ERROR_SIGN_TRANSACTION, {
935
+ cause: error
936
+ });
937
+ case 5:
938
+ return [
939
+ 2
940
+ ];
941
+ }
942
+ });
943
+ })();
944
+ }
945
+ },
946
+ {
947
+ /**
948
+ * Derive account address from ECDSA public key.
949
+ *
950
+ * TRON addresses are the keccak256 hash of the uncompressed pubkey (minus
951
+ * the 0x04 prefix), last 20 bytes, prefixed with 0x41, then Base58Check
952
+ * encoded.
953
+ */ key: "deriveAccountAddress",
954
+ value: function deriveAccountAddress(param) {
955
+ var rawPublicKey = param.rawPublicKey;
956
+ var publicKeyHex = rawPublicKey.pubKeyAsHex();
957
+ var serializedUncompressed = rawPublicKey.serializeUncompressed();
958
+ var uncompressedHex = Buffer.from(serializedUncompressed).toString('hex');
959
+ var accountAddress = deriveTronAddress({
960
+ publicKeyHex: uncompressedHex
961
+ });
962
+ return {
963
+ accountAddress: accountAddress,
964
+ publicKeyHex: publicKeyHex
965
+ };
966
+ }
967
+ },
968
+ {
969
+ key: "exportPrivateKey",
970
+ value: /**
971
+ * Export private key from MPC key shares.
972
+ *
973
+ * TRON uses the raw hex (no encoded prefix) for its private key format,
974
+ * matching what tronweb / TronLink expose. We return it as 0x-prefixed
975
+ * so it round-trips cleanly through `importPrivateKey`.
976
+ */ function exportPrivateKey(param) {
977
+ var accountAddress = param.accountAddress, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, signedSessionId = param.signedSessionId, mfaToken = param.mfaToken, elevatedAccessToken = param.elevatedAccessToken, approvalQuorum = param.approvalQuorum, proposalId = param.proposalId, traceContext = param.traceContext;
978
+ var _this = this;
979
+ return _async_to_generator(function() {
980
+ var derivedPrivateKey, hex, error;
981
+ return _ts_generator(this, function(_state) {
982
+ switch(_state.label){
983
+ case 0:
984
+ _state.trys.push([
985
+ 0,
986
+ 2,
987
+ ,
988
+ 3
989
+ ]);
990
+ return [
991
+ 4,
992
+ _this.exportKey({
993
+ accountAddress: accountAddress,
994
+ chainName: _this.chainName,
995
+ password: password,
996
+ signedSessionId: signedSessionId,
997
+ mfaToken: mfaToken,
998
+ elevatedAccessToken: elevatedAccessToken,
999
+ approvalQuorum: approvalQuorum,
1000
+ proposalId: proposalId,
1001
+ traceContext: traceContext
1002
+ })
1003
+ ];
1004
+ case 1:
1005
+ derivedPrivateKey = _state.sent().derivedPrivateKey;
1006
+ if (!derivedPrivateKey) {
1007
+ throw new Error('Derived private key is undefined');
1008
+ }
1009
+ hex = derivedPrivateKey.startsWith('0x') ? derivedPrivateKey.slice(2) : derivedPrivateKey;
1010
+ return [
1011
+ 2,
1012
+ "0x".concat(hex)
1013
+ ];
1014
+ case 2:
1015
+ error = _state.sent();
1016
+ // Not a failure: the export needs approvals, and the caller needs the
1017
+ // reason and proposalId to continue.
1018
+ if (_instanceof(error, SigningConsentRequiredError)) throw error;
1019
+ _this.logger.error(ERROR_EXPORT_PRIVATE_KEY, error);
1020
+ throw new Error(ERROR_EXPORT_PRIVATE_KEY);
1021
+ case 3:
1022
+ return [
1023
+ 2
1024
+ ];
1025
+ }
1026
+ });
1027
+ })();
1028
+ }
1029
+ },
1030
+ {
1031
+ key: "offlineExportPrivateKey",
1032
+ value: /**
1033
+ * Offline export of private key from key shares.
1034
+ */ function offlineExportPrivateKey(param) {
1035
+ var keyShares = param.keyShares, derivationPath = param.derivationPath;
1036
+ var _this = this;
1037
+ return _async_to_generator(function() {
1038
+ var derivedPrivateKey;
1039
+ return _ts_generator(this, function(_state) {
1040
+ switch(_state.label){
1041
+ case 0:
1042
+ return [
1043
+ 4,
1044
+ _this.offlineExportKey({
1045
+ chainName: _this.chainName,
1046
+ keyShares: keyShares,
1047
+ derivationPath: derivationPath
1048
+ })
1049
+ ];
1050
+ case 1:
1051
+ derivedPrivateKey = _state.sent().derivedPrivateKey;
1052
+ return [
1053
+ 2,
1054
+ {
1055
+ derivedPrivateKey: derivedPrivateKey
1056
+ }
1057
+ ];
1058
+ }
1059
+ });
1060
+ })();
1061
+ }
1062
+ },
1063
+ {
1064
+ key: "importPrivateKey",
1065
+ value: /**
1066
+ * Import an existing TRON private key into MPC.
1067
+ */ function importPrivateKey(param) {
1068
+ var privateKey = param.privateKey, chainName = param.chainName, thresholdSignatureScheme = param.thresholdSignatureScheme, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, onError = param.onError, signedSessionId = param.signedSessionId, publicAddressCheck = param.publicAddressCheck, legacyWalletId = param.legacyWalletId;
1069
+ var _this = this;
1070
+ return _async_to_generator(function() {
1071
+ var ceremonyCompleteResolver, ceremonyCompletePromise, formattedPrivateKey, _ref, rawPublicKey, clientKeyShares, _this_deriveAccountAddress, accountAddress, publicKeyHex, error;
1072
+ return _ts_generator(this, function(_state) {
1073
+ switch(_state.label){
1074
+ case 0:
1075
+ _state.trys.push([
1076
+ 0,
1077
+ 5,
1078
+ ,
1079
+ 6
1080
+ ]);
1081
+ if (publicAddressCheck && !isValidTronAddress(publicAddressCheck)) {
1082
+ throw new Error('Invalid TRON address provided for publicAddressCheck');
1083
+ }
1084
+ ceremonyCompletePromise = new Promise(function(resolve) {
1085
+ ceremonyCompleteResolver = resolve;
1086
+ });
1087
+ formattedPrivateKey = privateKey.startsWith('0x') ? privateKey.slice(2) : privateKey;
1088
+ return [
1089
+ 4,
1090
+ _this.importRawPrivateKey({
1091
+ chainName: chainName,
1092
+ privateKey: formattedPrivateKey,
1093
+ thresholdSignatureScheme: thresholdSignatureScheme,
1094
+ onCeremonyComplete: function(param) {
1095
+ var accountAddress = param.accountAddress, walletId = param.walletId, shareSetId = param.shareSetId;
1096
+ _this.initializeWalletMapEntry({
1097
+ accountAddress: accountAddress,
1098
+ walletId: walletId,
1099
+ chainName: _this.chainName,
1100
+ thresholdSignatureScheme: thresholdSignatureScheme,
1101
+ shareSetId: shareSetId
1102
+ });
1103
+ ceremonyCompleteResolver(undefined);
1104
+ },
1105
+ onError: onError,
1106
+ legacyWalletId: legacyWalletId,
1107
+ password: password,
1108
+ signedSessionId: signedSessionId
1109
+ })
1110
+ ];
1111
+ case 1:
1112
+ _ref = _state.sent(), rawPublicKey = _ref.rawPublicKey, clientKeyShares = _ref.clientKeyShares;
1113
+ return [
1114
+ 4,
1115
+ ceremonyCompletePromise
1116
+ ];
1117
+ case 2:
1118
+ _state.sent();
1119
+ if (!rawPublicKey || !clientKeyShares) {
1120
+ throw new Error(ERROR_IMPORT_PRIVATE_KEY);
1121
+ }
1122
+ _this.checkRawPublicKeyInstance(rawPublicKey);
1123
+ _this_deriveAccountAddress = _this.deriveAccountAddress({
1124
+ rawPublicKey: rawPublicKey
1125
+ }), accountAddress = _this_deriveAccountAddress.accountAddress, publicKeyHex = _this_deriveAccountAddress.publicKeyHex;
1126
+ if (publicAddressCheck && accountAddress !== publicAddressCheck) {
1127
+ throw new Error('Public address mismatch between derived and provided publicAddressCheck');
1128
+ }
1129
+ return [
1130
+ 4,
1131
+ _this.setClientKeySharesToStorage({
1132
+ accountAddress: accountAddress,
1133
+ clientKeyShares: clientKeyShares
1134
+ })
1135
+ ];
1136
+ case 3:
1137
+ _state.sent();
1138
+ return [
1139
+ 4,
1140
+ _this.storeEncryptedBackupByWallet({
1141
+ accountAddress: accountAddress,
1142
+ clientKeyShares: clientKeyShares,
1143
+ password: password,
1144
+ signedSessionId: signedSessionId
1145
+ })
1146
+ ];
1147
+ case 4:
1148
+ _state.sent();
1149
+ return [
1150
+ 2,
1151
+ {
1152
+ accountAddress: accountAddress,
1153
+ rawPublicKey: rawPublicKey,
1154
+ publicKeyHex: publicKeyHex
1155
+ }
1156
+ ];
1157
+ case 5:
1158
+ error = _state.sent();
1159
+ _this.logger.error(ERROR_IMPORT_PRIVATE_KEY, error);
1160
+ onError === null || onError === void 0 ? void 0 : onError(error);
1161
+ throw error;
1162
+ case 6:
1163
+ return [
1164
+ 2
1165
+ ];
1166
+ }
1167
+ });
1168
+ })();
1169
+ }
1170
+ },
1171
+ {
1172
+ key: "getTronWallets",
1173
+ value: /**
1174
+ * Get all TRON wallets known to this client.
1175
+ */ function getTronWallets() {
1176
+ var _this = this;
1177
+ return _async_to_generator(function() {
1178
+ var wallets;
1179
+ return _ts_generator(this, function(_state) {
1180
+ switch(_state.label){
1181
+ case 0:
1182
+ return [
1183
+ 4,
1184
+ _this.getWallets()
1185
+ ];
1186
+ case 1:
1187
+ wallets = _state.sent();
1188
+ return [
1189
+ 2,
1190
+ wallets.filter(function(wallet) {
1191
+ return wallet.chainName === 'TRON';
1192
+ })
1193
+ ];
1194
+ }
1195
+ });
1196
+ })();
1197
+ }
1198
+ },
1199
+ {
1200
+ key: "checkRawPublicKeyInstance",
1201
+ value: /**
1202
+ * Check if the raw public key is a valid ECDSA public key instance.
1203
+ */ function checkRawPublicKeyInstance(rawPublicKey) {
1204
+ if (!rawPublicKey || (typeof rawPublicKey === "undefined" ? "undefined" : _type_of(rawPublicKey)) !== 'object' || !('serializeUncompressed' in rawPublicKey) || !('pubKeyAsHex' in rawPublicKey)) {
1205
+ throw new Error(ERROR_INVALID_RAW_PUBLIC_KEY);
1206
+ }
1207
+ }
1208
+ }
1209
+ ]);
1210
+ return DynamicTronWalletClient;
1211
+ }(DynamicWalletClient);
1212
+
1213
+ var TRON_ADDRESS_LENGTH = 21;
1214
+ var CHECKSUM_LENGTH = 4;
1215
+ var MAX_RAW_DATA_BYTES = 102400;
1216
+ var MAX_VARINT_BYTES = 10;
1217
+ var TRANSFER_CONTRACT = 1n;
1218
+ var TRIGGER_SMART_CONTRACT = 31n;
1219
+ var TYPE_URLS = {
1220
+ TransferContract: 'type.googleapis.com/protocol.TransferContract',
1221
+ TriggerSmartContract: 'type.googleapis.com/protocol.TriggerSmartContract'
1222
+ };
1223
+ var CONTRACT_TYPES = {
1224
+ TransferContract: TRANSFER_CONTRACT,
1225
+ TriggerSmartContract: TRIGGER_SMART_CONTRACT
1226
+ };
1227
+ var readVarint = function(bytes, start) {
1228
+ var value = 0n;
1229
+ for(var index = 0; index < MAX_VARINT_BYTES; index += 1){
1230
+ var byte = bytes[start + index];
1231
+ if (byte === undefined) return undefined;
1232
+ value |= BigInt(byte & 0x7f) << BigInt(7 * index);
1233
+ if ((byte & 0x80) === 0) return {
1234
+ next: start + index + 1,
1235
+ value: value
1236
+ };
1237
+ }
1238
+ return undefined;
1239
+ };
1240
+ // Only varint and length-delimited fields: every field this parser accepts is
1241
+ // one of the two, so any other wire type is rejected rather than skipped.
1242
+ var readField = function(bytes, position) {
1243
+ var key = readVarint(bytes, position);
1244
+ if (!key) return undefined;
1245
+ var number = Number(key.value >> 3n);
1246
+ var wireType = Number(key.value & 7n);
1247
+ if (number === 0) return undefined;
1248
+ if (wireType === 0) {
1249
+ var varint = readVarint(bytes, key.next);
1250
+ return varint && {
1251
+ field: {
1252
+ number: number,
1253
+ varint: varint.value
1254
+ },
1255
+ next: varint.next
1256
+ };
1257
+ }
1258
+ if (wireType === 2) {
1259
+ var length = readVarint(bytes, key.next);
1260
+ if (!length || length.value > BigInt(bytes.length - length.next)) return undefined;
1261
+ var end = length.next + Number(length.value);
1262
+ return {
1263
+ field: {
1264
+ bytes: bytes.subarray(length.next, end),
1265
+ number: number
1266
+ },
1267
+ next: end
1268
+ };
1269
+ }
1270
+ return undefined;
1271
+ };
1272
+ var readFields = function(bytes) {
1273
+ var fields = [];
1274
+ var position = 0;
1275
+ while(position < bytes.length){
1276
+ var read = readField(bytes, position);
1277
+ if (!read) return undefined;
1278
+ fields.push(read.field);
1279
+ position = read.next;
1280
+ }
1281
+ return fields;
1282
+ };
1283
+ // A field outside `allowed`, of the wrong kind or repeated would be signed but
1284
+ // not described by the intent, so the whole message is rejected.
1285
+ var readStrict = function(bytes, allowed) {
1286
+ var fields = readFields(bytes);
1287
+ if (!fields) return undefined;
1288
+ var byNumber = new Map();
1289
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1290
+ try {
1291
+ for(var _iterator = fields[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1292
+ var field = _step.value;
1293
+ var kind = allowed[field.number];
1294
+ if (kind === undefined || byNumber.has(field.number)) return undefined;
1295
+ if (kind === 'bytes' ? !field.bytes : field.varint === undefined) return undefined;
1296
+ byNumber.set(field.number, field);
1297
+ }
1298
+ } catch (err) {
1299
+ _didIteratorError = true;
1300
+ _iteratorError = err;
1301
+ } finally{
1302
+ try {
1303
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1304
+ _iterator.return();
1305
+ }
1306
+ } finally{
1307
+ if (_didIteratorError) {
1308
+ throw _iteratorError;
1309
+ }
1310
+ }
1311
+ }
1312
+ return byNumber;
1313
+ };
1314
+ var concat = function(parts) {
1315
+ var result = new Uint8Array(parts.reduce(function(total, part) {
1316
+ return total + part.length;
1317
+ }, 0));
1318
+ var offset = 0;
1319
+ var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
1320
+ try {
1321
+ for(var _iterator = parts[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
1322
+ var part = _step.value;
1323
+ result.set(part, offset);
1324
+ offset += part.length;
1325
+ }
1326
+ } catch (err) {
1327
+ _didIteratorError = true;
1328
+ _iteratorError = err;
1329
+ } finally{
1330
+ try {
1331
+ if (!_iteratorNormalCompletion && _iterator.return != null) {
1332
+ _iterator.return();
1333
+ }
1334
+ } finally{
1335
+ if (_didIteratorError) {
1336
+ throw _iteratorError;
1337
+ }
1338
+ }
1339
+ }
1340
+ return result;
1341
+ };
1342
+ var EMPTY = new Uint8Array(0);
1343
+ var checksumOf = function(payload) {
1344
+ return sha256(sha256(payload)).subarray(0, CHECKSUM_LENGTH);
1345
+ };
1346
+ var encodeAddress = function(bytes) {
1347
+ if ((bytes === null || bytes === void 0 ? void 0 : bytes.length) !== TRON_ADDRESS_LENGTH || bytes[0] !== TRON_ADDRESS_PREFIX) return undefined;
1348
+ return bs58.encode(concat([
1349
+ bytes,
1350
+ checksumOf(bytes)
1351
+ ]));
1352
+ };
1353
+ var decodeAddressBytes = function(address) {
1354
+ var decoded = bs58.decode(address);
1355
+ var payload = decoded.subarray(0, TRON_ADDRESS_LENGTH);
1356
+ var checksum = decoded.subarray(TRON_ADDRESS_LENGTH);
1357
+ if (decoded.length !== TRON_ADDRESS_LENGTH + CHECKSUM_LENGTH || payload[0] !== TRON_ADDRESS_PREFIX || Buffer.compare(checksum, checksumOf(payload)) !== 0) {
1358
+ throw new Error('Invalid TRON address');
1359
+ }
1360
+ return payload;
1361
+ };
1362
+ var toHex = function(bytes) {
1363
+ return "0x".concat(Buffer.from(bytes !== null && bytes !== void 0 ? bytes : []).toString('hex'));
1364
+ };
1365
+ var hexBytes = function(hex) {
1366
+ return Uint8Array.from(Buffer.from(hex.replace(/^0x/, ''), 'hex'));
1367
+ };
1368
+ /**
1369
+ * Reads a TRON transaction's `raw_data` into the fields a signing intent
1370
+ * describes. Returns `undefined` for anything it cannot describe completely:
1371
+ * unknown, repeated or mistyped fields at any level, anything but one
1372
+ * TransferContract or TriggerSmartContract, a malformed address.
1373
+ */ var parseTronRawData = function(rawData) {
1374
+ var _raw_get, _contract_get, _contract_get1, _parameter_get, _parameter_get1, _value_get, _value_get1, _value_get2, _raw_get1, _value_get3;
1375
+ if (rawData.length === 0 || rawData.length > MAX_RAW_DATA_BYTES) return undefined;
1376
+ var raw = readStrict(rawData, {
1377
+ 1: 'bytes',
1378
+ 3: 'varint',
1379
+ 4: 'bytes',
1380
+ 8: 'varint',
1381
+ 11: 'bytes',
1382
+ 14: 'varint',
1383
+ 18: 'varint'
1384
+ });
1385
+ var contractBytes = raw === null || raw === void 0 ? void 0 : (_raw_get = raw.get(11)) === null || _raw_get === void 0 ? void 0 : _raw_get.bytes;
1386
+ if (!raw || !contractBytes) return undefined;
1387
+ var contract = readStrict(contractBytes, {
1388
+ 1: 'varint',
1389
+ 2: 'bytes'
1390
+ });
1391
+ var type = contract === null || contract === void 0 ? void 0 : (_contract_get = contract.get(1)) === null || _contract_get === void 0 ? void 0 : _contract_get.varint;
1392
+ var parameterBytes = contract === null || contract === void 0 ? void 0 : (_contract_get1 = contract.get(2)) === null || _contract_get1 === void 0 ? void 0 : _contract_get1.bytes;
1393
+ if (type === undefined || !parameterBytes) return undefined;
1394
+ var parameter = readStrict(parameterBytes, {
1395
+ 1: 'bytes',
1396
+ 2: 'bytes'
1397
+ });
1398
+ var typeUrl = parameter === null || parameter === void 0 ? void 0 : (_parameter_get = parameter.get(1)) === null || _parameter_get === void 0 ? void 0 : _parameter_get.bytes;
1399
+ var valueBytes = parameter === null || parameter === void 0 ? void 0 : (_parameter_get1 = parameter.get(2)) === null || _parameter_get1 === void 0 ? void 0 : _parameter_get1.bytes;
1400
+ if (!typeUrl || !valueBytes) return undefined;
1401
+ var contractType = Object.keys(TYPE_URLS).find(function(name) {
1402
+ return CONTRACT_TYPES[name] === type && TYPE_URLS[name] === Buffer.from(typeUrl).toString('utf8');
1403
+ });
1404
+ if (!contractType) return undefined;
1405
+ var isTransfer = contractType === 'TransferContract';
1406
+ var value = readStrict(valueBytes, isTransfer ? {
1407
+ 1: 'bytes',
1408
+ 2: 'bytes',
1409
+ 3: 'varint'
1410
+ } : {
1411
+ 1: 'bytes',
1412
+ 2: 'bytes',
1413
+ 3: 'varint',
1414
+ 4: 'bytes'
1415
+ });
1416
+ var from = encodeAddress(value === null || value === void 0 ? void 0 : (_value_get = value.get(1)) === null || _value_get === void 0 ? void 0 : _value_get.bytes);
1417
+ var to = encodeAddress(value === null || value === void 0 ? void 0 : (_value_get1 = value.get(2)) === null || _value_get1 === void 0 ? void 0 : _value_get1.bytes);
1418
+ if (!value || !from || !to) return undefined;
1419
+ var _raw_get_varint, _value_get_varint;
1420
+ return {
1421
+ contractType: contractType,
1422
+ data: isTransfer ? '0x' : toHex((_value_get2 = value.get(4)) === null || _value_get2 === void 0 ? void 0 : _value_get2.bytes),
1423
+ feeLimit: ((_raw_get_varint = (_raw_get1 = raw.get(18)) === null || _raw_get1 === void 0 ? void 0 : _raw_get1.varint) !== null && _raw_get_varint !== void 0 ? _raw_get_varint : 0n).toString(),
1424
+ from: from,
1425
+ to: to,
1426
+ value: ((_value_get_varint = (_value_get3 = value.get(3)) === null || _value_get3 === void 0 ? void 0 : _value_get3.varint) !== null && _value_get_varint !== void 0 ? _value_get_varint : 0n).toString()
1427
+ };
1428
+ };
1429
+ var varint = function(value) {
1430
+ var bytes = [];
1431
+ var rest = value;
1432
+ while(rest >= 0x80n){
1433
+ bytes.push(Number(rest & 0x7fn) | 0x80);
1434
+ rest >>= 7n;
1435
+ }
1436
+ bytes.push(Number(rest));
1437
+ return Uint8Array.from(bytes);
1438
+ };
1439
+ var bytesField = function(number, value) {
1440
+ return concat([
1441
+ varint(BigInt(number << 3 | 2)),
1442
+ varint(BigInt(value.length)),
1443
+ value
1444
+ ]);
1445
+ };
1446
+ // proto3 leaves a zero or empty field out.
1447
+ var optionalVarintField = function(number, value) {
1448
+ return value === 0n ? EMPTY : concat([
1449
+ varint(BigInt(number << 3)),
1450
+ varint(value)
1451
+ ]);
1452
+ };
1453
+ var optionalBytesField = function(number, value) {
1454
+ return value.length === 0 ? EMPTY : bytesField(number, value);
1455
+ };
1456
+ var encodeContract = function(body) {
1457
+ var owner = bytesField(1, decodeAddressBytes(body.from));
1458
+ var target = bytesField(2, decodeAddressBytes(body.to));
1459
+ var value = optionalVarintField(3, BigInt(body.value));
1460
+ var contractValue = body.contractType === 'TransferContract' ? concat([
1461
+ owner,
1462
+ target,
1463
+ value
1464
+ ]) : concat([
1465
+ owner,
1466
+ target,
1467
+ value,
1468
+ optionalBytesField(4, hexBytes(body.data))
1469
+ ]);
1470
+ var typeUrl = Uint8Array.from(Buffer.from(TYPE_URLS[body.contractType]));
1471
+ return concat([
1472
+ optionalVarintField(1, CONTRACT_TYPES[body.contractType]),
1473
+ bytesField(2, concat([
1474
+ bytesField(1, typeUrl),
1475
+ bytesField(2, contractValue)
1476
+ ]))
1477
+ ]);
1478
+ };
1479
+ /**
1480
+ * Serializes a transaction's `raw_data` from the described body and a block
1481
+ * reference, with the fields in field-number order as a TRON node does.
1482
+ */ var encodeTronRawData = function(body, reference) {
1483
+ return concat([
1484
+ bytesField(1, hexBytes(reference.refBlockBytes)),
1485
+ bytesField(4, hexBytes(reference.refBlockHash)),
1486
+ optionalVarintField(8, BigInt(reference.expiration)),
1487
+ bytesField(11, encodeContract(body)),
1488
+ optionalVarintField(14, BigInt(reference.timestamp)),
1489
+ optionalVarintField(18, BigInt(body.feeLimit))
1490
+ ]);
1491
+ };
1492
+
1493
+ function _define_property(obj, key, value) {
1494
+ if (key in obj) {
1495
+ Object.defineProperty(obj, key, {
1496
+ value: value,
1497
+ enumerable: true,
1498
+ configurable: true,
1499
+ writable: true
1500
+ });
1501
+ } else {
1502
+ obj[key] = value;
1503
+ }
1504
+ return obj;
1505
+ }
1506
+ function _object_spread(target) {
1507
+ for(var i = 1; i < arguments.length; i++){
1508
+ var source = arguments[i] != null ? arguments[i] : {};
1509
+ var ownKeys = Object.keys(source);
1510
+ if (typeof Object.getOwnPropertySymbols === "function") {
1511
+ ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
1512
+ return Object.getOwnPropertyDescriptor(source, sym).enumerable;
1513
+ }));
1514
+ }
1515
+ ownKeys.forEach(function(key) {
1516
+ _define_property(target, key, source[key]);
1517
+ });
1518
+ }
1519
+ return target;
1520
+ }
1521
+ var isHexBytes = function(value) {
1522
+ return /^(?:[0-9a-fA-F]{2})+$/.test(value);
1523
+ };
1524
+ var DECIMAL_CHAIN_ID = /^(0|[1-9]\d*)$/;
1525
+ // A hexadecimal id is accepted as the TRON client does, and described in decimal.
1526
+ var assertNetworkChainId = function(chainId) {
1527
+ var networkChainId = chainId && normalizeTronChainId(chainId);
1528
+ if (!networkChainId || !DECIMAL_CHAIN_ID.test(networkChainId)) {
1529
+ throw new Error('TRON signing intent requires a network chainId');
1530
+ }
1531
+ return networkChainId;
1532
+ };
1533
+ // The TRON client takes the transaction as JSON holding `raw_data_hex`; the bare hex is accepted too.
1534
+ var rawDataHexOf = function(transaction) {
1535
+ var trimmed = transaction.trim();
1536
+ if (!trimmed.startsWith('{')) return trimmed.replace(/^0x/, '');
1537
+ try {
1538
+ var _JSON_parse = JSON.parse(trimmed), rawDataHex = _JSON_parse.raw_data_hex;
1539
+ if (typeof rawDataHex === 'string') return rawDataHex.replace(/^0x/, '');
1540
+ } catch (e) {
1541
+ // Not JSON: rejected below as not hex.
1542
+ }
1543
+ return trimmed;
1544
+ };
1545
+ /**
1546
+ * Describes a TRON transaction for a signing-quorum intent from its `raw_data`
1547
+ * hex, bare or inside the transaction JSON the TRON client signs. The reference block, expiration and timestamp are not part of the
1548
+ * description: they may be refreshed when the approved intent is resumed.
1549
+ */ var prepareTronTransactionSigningOperation = function(param) {
1550
+ var transaction = param.transaction, accountAddress = param.accountAddress, chainId = param.chainId;
1551
+ var networkChainId = assertNetworkChainId(chainId);
1552
+ var rawDataHex = rawDataHexOf(transaction);
1553
+ if (!isHexBytes(rawDataHex)) throw new Error('TRON signing intent requires a hex raw_data');
1554
+ var body = parseTronRawData(Uint8Array.from(Buffer.from(rawDataHex, 'hex')));
1555
+ if (!body) throw new Error('TRON signing intent supports one TRX transfer or smart-contract call');
1556
+ if (body.from !== accountAddress) throw new Error('TRON transaction owner must be the signing account');
1557
+ return {
1558
+ operation: _object_spread({
1559
+ kind: 'transaction',
1560
+ chainName: 'TRON',
1561
+ chainId: networkChainId
1562
+ }, body),
1563
+ lifetime: {
1564
+ refreshable: 'expiration'
1565
+ }
1566
+ };
1567
+ };
1568
+ var signedTronOperation = function(intent) {
1569
+ var _intent_lifetime;
1570
+ var operation = intent.operation;
1571
+ if (operation.kind !== 'transaction' || operation.chainName !== 'TRON' || ((_intent_lifetime = intent.lifetime) === null || _intent_lifetime === void 0 ? void 0 : _intent_lifetime.refreshable) !== 'expiration') {
1572
+ throw new Error('Stored signing intent is not a TRON transaction');
1573
+ }
1574
+ return operation;
1575
+ };
1576
+ var isPositiveSafeInteger = function(value) {
1577
+ return typeof value === 'number' && Number.isSafeInteger(value) && value > 0;
1578
+ };
1579
+ var parseBlockReference = function(lifetimeValue) {
1580
+ var parsed;
1581
+ try {
1582
+ parsed = lifetimeValue ? JSON.parse(lifetimeValue) : undefined;
1583
+ } catch (e) {
1584
+ parsed = undefined;
1585
+ }
1586
+ var _ref = parsed !== null && parsed !== void 0 ? parsed : {}, expiration = _ref.expiration, refBlockBytes = _ref.refBlockBytes, refBlockHash = _ref.refBlockHash, timestamp = _ref.timestamp;
1587
+ if (typeof refBlockBytes !== 'string' || !/^(?:[0-9a-fA-F]{2}){2}$/.test(refBlockBytes) || typeof refBlockHash !== 'string' || !/^(?:[0-9a-fA-F]{2}){8}$/.test(refBlockHash) || !isPositiveSafeInteger(expiration) || !isPositiveSafeInteger(timestamp)) {
1588
+ throw new Error('TRON transaction intent requires a block reference');
1589
+ }
1590
+ return {
1591
+ expiration: expiration,
1592
+ refBlockBytes: refBlockBytes,
1593
+ refBlockHash: refBlockHash,
1594
+ timestamp: timestamp
1595
+ };
1596
+ };
1597
+ var operationBody = function(operation) {
1598
+ return {
1599
+ contractType: operation.contractType,
1600
+ data: operation.data,
1601
+ feeLimit: operation.feeLimit,
1602
+ from: operation.from,
1603
+ to: operation.to,
1604
+ value: operation.value
1605
+ };
1606
+ };
1607
+ /**
1608
+ * Rebuilds the `raw_data` hex of an approved TRON transaction intent. The
1609
+ * signed intent carries no block reference, so the caller supplies a fresh one
1610
+ * as `lifetimeValue`, a JSON object with `refBlockBytes` and `refBlockHash` as
1611
+ * hex and `expiration` and `timestamp` in milliseconds.
1612
+ */ var resumeTronTransactionSigningIntent = function(param) {
1613
+ var intent = param.intent, lifetimeValue = param.lifetimeValue;
1614
+ var operation = signedTronOperation(intent);
1615
+ var rawData = encodeTronRawData(operationBody(operation), parseBlockReference(lifetimeValue));
1616
+ var rebuilt = parseTronRawData(rawData);
1617
+ if (JSON.stringify(rebuilt) !== JSON.stringify(operationBody(operation))) {
1618
+ throw new Error('Stored TRON transaction intent is malformed');
1619
+ }
1620
+ return Buffer.from(rawData).toString('hex');
1621
+ };
1622
+
1623
+ export { DynamicTronWalletClient, TRON_ADDRESS_PREFIX, TRON_SIGN_MESSAGE_PREFIX, decodeTronAddress, deriveTronAddress, formatTronMessage, getTronTxId, getTronTxIdHex, isValidTronAddress, prepareTronTransactionSigningOperation, resumeTronTransactionSigningIntent, serializeECDSASignature, toTronMessageBytes, tronAddressToHex };