@dynamic-labs-wallet/node-ton 0.0.0-pr658.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.esm.js ADDED
@@ -0,0 +1,861 @@
1
+ import { DynamicWalletClient, getMPCChainConfig, WalletOperation } from '@dynamic-labs-wallet/node';
2
+ import { keyPairFromSeed } from '@ton/crypto';
3
+ import { WalletContractV5R1 } from '@ton/ton';
4
+ import { Logger } from '@dynamic-labs/logger';
5
+ import { AxiosError } from 'axios';
6
+ import { handleAxiosError } from '@dynamic-labs-wallet/core';
7
+
8
+ function _instanceof$1(left, right) {
9
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
10
+ return !!right[Symbol.hasInstance](left);
11
+ } else {
12
+ return left instanceof right;
13
+ }
14
+ }
15
+ var logger = new Logger('DynamicWaasWalletClient');
16
+ var logError = function(param) {
17
+ var message = param.message, error = param.error, context = param.context;
18
+ if (_instanceof$1(error, AxiosError)) {
19
+ handleAxiosError(error, message, context, logger);
20
+ }
21
+ logger.error('[DynamicWaasWalletClient] Error in node-ton client', {
22
+ error: _instanceof$1(error, Error) ? error.message : String(error),
23
+ context: context
24
+ });
25
+ };
26
+
27
+ var ERROR_KEYGEN_FAILED = 'Error with keygen';
28
+ var ERROR_CREATE_WALLET_ACCOUNT = 'Error creating ton wallet account';
29
+ var ERROR_IMPORT_PRIVATE_KEY = 'Error importing private key';
30
+ var ERROR_EXPORT_PRIVATE_KEY = 'Error exporting private key';
31
+ var ERROR_SIGN_MESSAGE = 'Error signing message';
32
+ var ERROR_ACCOUNT_ADDRESS_REQUIRED = 'Account address is required';
33
+ var ERROR_SIGN_TRANSACTION = 'Error signing transaction';
34
+
35
+ function _assert_this_initialized(self) {
36
+ if (self === void 0) {
37
+ throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
38
+ }
39
+ return self;
40
+ }
41
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
42
+ try {
43
+ var info = gen[key](arg);
44
+ var value = info.value;
45
+ } catch (error) {
46
+ reject(error);
47
+ return;
48
+ }
49
+ if (info.done) {
50
+ resolve(value);
51
+ } else {
52
+ Promise.resolve(value).then(_next, _throw);
53
+ }
54
+ }
55
+ function _async_to_generator(fn) {
56
+ return function() {
57
+ var self = this, args = arguments;
58
+ return new Promise(function(resolve, reject) {
59
+ var gen = fn.apply(self, args);
60
+ function _next(value) {
61
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
62
+ }
63
+ function _throw(err) {
64
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
65
+ }
66
+ _next(undefined);
67
+ });
68
+ };
69
+ }
70
+ function _call_super(_this, derived, args) {
71
+ derived = _get_prototype_of(derived);
72
+ return _possible_constructor_return(_this, _is_native_reflect_construct() ? Reflect.construct(derived, args || [], _get_prototype_of(_this).constructor) : derived.apply(_this, args));
73
+ }
74
+ function _class_call_check(instance, Constructor) {
75
+ if (!(instance instanceof Constructor)) {
76
+ throw new TypeError("Cannot call a class as a function");
77
+ }
78
+ }
79
+ function _defineProperties(target, props) {
80
+ for(var i = 0; i < props.length; i++){
81
+ var descriptor = props[i];
82
+ descriptor.enumerable = descriptor.enumerable || false;
83
+ descriptor.configurable = true;
84
+ if ("value" in descriptor) descriptor.writable = true;
85
+ Object.defineProperty(target, descriptor.key, descriptor);
86
+ }
87
+ }
88
+ function _create_class(Constructor, protoProps, staticProps) {
89
+ if (protoProps) _defineProperties(Constructor.prototype, protoProps);
90
+ return Constructor;
91
+ }
92
+ function _define_property(obj, key, value) {
93
+ if (key in obj) {
94
+ Object.defineProperty(obj, key, {
95
+ value: value,
96
+ enumerable: true,
97
+ configurable: true,
98
+ writable: true
99
+ });
100
+ } else {
101
+ obj[key] = value;
102
+ }
103
+ return obj;
104
+ }
105
+ function _get_prototype_of(o) {
106
+ _get_prototype_of = Object.setPrototypeOf ? Object.getPrototypeOf : function getPrototypeOf(o) {
107
+ return o.__proto__ || Object.getPrototypeOf(o);
108
+ };
109
+ return _get_prototype_of(o);
110
+ }
111
+ function _inherits(subClass, superClass) {
112
+ if (typeof superClass !== "function" && superClass !== null) {
113
+ throw new TypeError("Super expression must either be null or a function");
114
+ }
115
+ subClass.prototype = Object.create(superClass && superClass.prototype, {
116
+ constructor: {
117
+ value: subClass,
118
+ writable: true,
119
+ configurable: true
120
+ }
121
+ });
122
+ if (superClass) _set_prototype_of(subClass, superClass);
123
+ }
124
+ function _instanceof(left, right) {
125
+ if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
126
+ return !!right[Symbol.hasInstance](left);
127
+ } else {
128
+ return left instanceof right;
129
+ }
130
+ }
131
+ function _possible_constructor_return(self, call) {
132
+ if (call && (_type_of(call) === "object" || typeof call === "function")) {
133
+ return call;
134
+ }
135
+ return _assert_this_initialized(self);
136
+ }
137
+ function _set_prototype_of(o, p) {
138
+ _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
139
+ o.__proto__ = p;
140
+ return o;
141
+ };
142
+ return _set_prototype_of(o, p);
143
+ }
144
+ function _type_of(obj) {
145
+ "@swc/helpers - typeof";
146
+ return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
147
+ }
148
+ function _is_native_reflect_construct() {
149
+ try {
150
+ var result = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() {}));
151
+ } catch (_) {}
152
+ return (_is_native_reflect_construct = function() {
153
+ return !!result;
154
+ })();
155
+ }
156
+ function _ts_generator(thisArg, body) {
157
+ var f, y, t, g, _ = {
158
+ label: 0,
159
+ sent: function() {
160
+ if (t[0] & 1) throw t[1];
161
+ return t[1];
162
+ },
163
+ trys: [],
164
+ ops: []
165
+ };
166
+ return g = {
167
+ next: verb(0),
168
+ "throw": verb(1),
169
+ "return": verb(2)
170
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
171
+ return this;
172
+ }), g;
173
+ function verb(n) {
174
+ return function(v) {
175
+ return step([
176
+ n,
177
+ v
178
+ ]);
179
+ };
180
+ }
181
+ function step(op) {
182
+ if (f) throw new TypeError("Generator is already executing.");
183
+ while(_)try {
184
+ 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;
185
+ if (y = 0, t) op = [
186
+ op[0] & 2,
187
+ t.value
188
+ ];
189
+ switch(op[0]){
190
+ case 0:
191
+ case 1:
192
+ t = op;
193
+ break;
194
+ case 4:
195
+ _.label++;
196
+ return {
197
+ value: op[1],
198
+ done: false
199
+ };
200
+ case 5:
201
+ _.label++;
202
+ y = op[1];
203
+ op = [
204
+ 0
205
+ ];
206
+ continue;
207
+ case 7:
208
+ op = _.ops.pop();
209
+ _.trys.pop();
210
+ continue;
211
+ default:
212
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
213
+ _ = 0;
214
+ continue;
215
+ }
216
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
217
+ _.label = op[1];
218
+ break;
219
+ }
220
+ if (op[0] === 6 && _.label < t[1]) {
221
+ _.label = t[1];
222
+ t = op;
223
+ break;
224
+ }
225
+ if (t && _.label < t[2]) {
226
+ _.label = t[2];
227
+ _.ops.push(op);
228
+ break;
229
+ }
230
+ if (t[2]) _.ops.pop();
231
+ _.trys.pop();
232
+ continue;
233
+ }
234
+ op = body.call(thisArg, _);
235
+ } catch (e) {
236
+ op = [
237
+ 6,
238
+ e
239
+ ];
240
+ y = 0;
241
+ } finally{
242
+ f = t = 0;
243
+ }
244
+ if (op[0] & 5) throw op[1];
245
+ return {
246
+ value: op[0] ? op[1] : void 0,
247
+ done: true
248
+ };
249
+ }
250
+ }
251
+ var DynamicTonWalletClient = /*#__PURE__*/ function(DynamicWalletClient) {
252
+ _inherits(DynamicTonWalletClient, DynamicWalletClient);
253
+ function DynamicTonWalletClient(param) {
254
+ var environmentId = param.environmentId, baseApiUrl = param.baseApiUrl, baseMPCRelayApiUrl = param.baseMPCRelayApiUrl, debug = param.debug, enableMPCAccelerator = param.enableMPCAccelerator;
255
+ _class_call_check(this, DynamicTonWalletClient);
256
+ var _this;
257
+ _this = _call_super(this, DynamicTonWalletClient, [
258
+ {
259
+ environmentId: environmentId,
260
+ baseApiUrl: baseApiUrl,
261
+ baseMPCRelayApiUrl: baseMPCRelayApiUrl,
262
+ debug: debug,
263
+ enableMPCAccelerator: enableMPCAccelerator
264
+ }
265
+ ]), _define_property(_this, "chainName", 'TON'), /**
266
+ * Derives a TON address from a public key
267
+ * TON addresses are derived from the wallet contract state init
268
+ */ _define_property(_this, "deriveTonAddress", function(param) {
269
+ var publicKeyHex = param.publicKeyHex, _param_workchain = param.workchain, workchain = _param_workchain === void 0 ? 0 : _param_workchain;
270
+ var pubKeyBytes = Buffer.from(publicKeyHex, 'hex');
271
+ if (pubKeyBytes.length !== 32) {
272
+ throw new Error("Invalid public key length: ".concat(pubKeyBytes.length, ", expected 32"));
273
+ }
274
+ var walletContract = WalletContractV5R1.create({
275
+ workchain: workchain,
276
+ publicKey: pubKeyBytes
277
+ });
278
+ return walletContract.address.toString({
279
+ urlSafe: true,
280
+ bounceable: false,
281
+ testOnly: false
282
+ });
283
+ });
284
+ return _this;
285
+ }
286
+ _create_class(DynamicTonWalletClient, [
287
+ {
288
+ key: "createWalletAccount",
289
+ value: /**
290
+ * Creates a new wallet account and stores the key shares in the wallet map.
291
+ * @param thresholdSignatureScheme - The threshold signature scheme to use for the wallet.
292
+ * @param password - The password to use for the wallet.
293
+ * @param onError - The function to call if an error occurs.
294
+ * @param backUpToClientShareService - Whether to back up the external server key shares to the client share service. By default, it is false.
295
+ * @returns The account address, public key hex, raw public key, external server key shares, and wallet id.
296
+ */ function createWalletAccount(param) {
297
+ var thresholdSignatureScheme = param.thresholdSignatureScheme, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, onError = param.onError, _param_backUpToClientShareService = param.backUpToClientShareService, backUpToClientShareService = _param_backUpToClientShareService === void 0 ? false : _param_backUpToClientShareService;
298
+ var _this = this;
299
+ return _async_to_generator(function() {
300
+ var _this_walletMap_accountAddress, ceremonyCeremonyCompleteResolver, ceremonyCompletePromise, _ref, rawPublicKey, externalServerKeyShares, publicKeyHex, accountAddress, _this_walletMap_accountAddress_walletId, error;
301
+ return _ts_generator(this, function(_state) {
302
+ switch(_state.label){
303
+ case 0:
304
+ _state.trys.push([
305
+ 0,
306
+ 4,
307
+ ,
308
+ 5
309
+ ]);
310
+ ceremonyCompletePromise = new Promise(function(resolve) {
311
+ ceremonyCeremonyCompleteResolver = resolve;
312
+ });
313
+ return [
314
+ 4,
315
+ _this.keyGen({
316
+ thresholdSignatureScheme: thresholdSignatureScheme,
317
+ chainName: _this.chainName,
318
+ onError: onError,
319
+ onCeremonyComplete: function(accountAddress, walletId) {
320
+ var chainConfig = getMPCChainConfig(_this.chainName);
321
+ _this.initializeWalletMapEntry({
322
+ accountAddress: accountAddress,
323
+ walletId: walletId,
324
+ chainName: _this.chainName,
325
+ thresholdSignatureScheme: thresholdSignatureScheme,
326
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map(function(value, index) {
327
+ return [
328
+ index,
329
+ value
330
+ ];
331
+ })))
332
+ });
333
+ ceremonyCeremonyCompleteResolver(undefined);
334
+ }
335
+ })
336
+ ];
337
+ case 1:
338
+ _ref = _state.sent(), rawPublicKey = _ref.rawPublicKey, externalServerKeyShares = _ref.externalServerKeyShares;
339
+ // Wait for the ceremony to complete before proceeding
340
+ return [
341
+ 4,
342
+ ceremonyCompletePromise
343
+ ];
344
+ case 2:
345
+ _state.sent();
346
+ if (!rawPublicKey || !externalServerKeyShares || !(typeof rawPublicKey === 'string' || _instanceof(rawPublicKey, Uint8Array))) {
347
+ throw new Error(ERROR_KEYGEN_FAILED);
348
+ }
349
+ publicKeyHex = typeof rawPublicKey === 'string' ? rawPublicKey : Buffer.from(rawPublicKey).toString('hex');
350
+ accountAddress = _this.deriveTonAddress({
351
+ publicKeyHex: publicKeyHex,
352
+ workchain: 0
353
+ });
354
+ return [
355
+ 4,
356
+ _this.storeEncryptedBackupByWalletWithRetry({
357
+ accountAddress: accountAddress,
358
+ externalServerKeyShares: externalServerKeyShares,
359
+ password: password,
360
+ backUpToClientShareService: backUpToClientShareService
361
+ })
362
+ ];
363
+ case 3:
364
+ _state.sent();
365
+ return [
366
+ 2,
367
+ {
368
+ walletId: (_this_walletMap_accountAddress_walletId = (_this_walletMap_accountAddress = _this.walletMap[accountAddress]) === null || _this_walletMap_accountAddress === void 0 ? void 0 : _this_walletMap_accountAddress.walletId) !== null && _this_walletMap_accountAddress_walletId !== void 0 ? _this_walletMap_accountAddress_walletId : '',
369
+ accountAddress: accountAddress,
370
+ publicKeyHex: publicKeyHex,
371
+ rawPublicKey: rawPublicKey,
372
+ externalServerKeyShares: externalServerKeyShares
373
+ }
374
+ ];
375
+ case 4:
376
+ error = _state.sent();
377
+ logError({
378
+ message: ERROR_CREATE_WALLET_ACCOUNT,
379
+ error: error,
380
+ context: {}
381
+ });
382
+ throw new Error(ERROR_CREATE_WALLET_ACCOUNT);
383
+ case 5:
384
+ return [
385
+ 2
386
+ ];
387
+ }
388
+ });
389
+ })();
390
+ }
391
+ },
392
+ {
393
+ key: "signMessage",
394
+ value: /**
395
+ * Signs a message using MPC
396
+ * @param message - The message to sign
397
+ * @param accountAddress - The account address to sign with
398
+ * @param password - The password for encrypted backup shares
399
+ * @param externalServerKeyShares - The external server key shares
400
+ * @param onError - The function to call if an error occurs
401
+ * @returns The signature as a base64 string
402
+ */ function signMessage(param) {
403
+ var message = param.message, accountAddress = param.accountAddress, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, externalServerKeyShares = param.externalServerKeyShares, onError = param.onError;
404
+ var _this = this;
405
+ return _async_to_generator(function() {
406
+ var signatureEd25519, formattedSignature, error;
407
+ return _ts_generator(this, function(_state) {
408
+ switch(_state.label){
409
+ case 0:
410
+ if (!accountAddress) {
411
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
412
+ }
413
+ _state.label = 1;
414
+ case 1:
415
+ _state.trys.push([
416
+ 1,
417
+ 4,
418
+ ,
419
+ 5
420
+ ]);
421
+ // Attempt to recover key shares from backup if not provided
422
+ return [
423
+ 4,
424
+ _this.ensureKeySharesRecovered({
425
+ accountAddress: accountAddress,
426
+ password: password,
427
+ walletOperation: WalletOperation.SIGN_MESSAGE,
428
+ externalServerKeyShares: externalServerKeyShares,
429
+ errorMessage: 'External server key shares are required to sign a message. No backup shares available for recovery.'
430
+ })
431
+ ];
432
+ case 2:
433
+ _state.sent();
434
+ return [
435
+ 4,
436
+ _this.sign({
437
+ message: message,
438
+ accountAddress: accountAddress,
439
+ chainName: _this.chainName,
440
+ password: password,
441
+ externalServerKeyShares: externalServerKeyShares,
442
+ onError: onError
443
+ })
444
+ ];
445
+ case 3:
446
+ signatureEd25519 = _state.sent();
447
+ formattedSignature = Buffer.from(signatureEd25519).toString('base64');
448
+ return [
449
+ 2,
450
+ formattedSignature
451
+ ];
452
+ case 4:
453
+ error = _state.sent();
454
+ logError({
455
+ message: ERROR_SIGN_MESSAGE,
456
+ error: error,
457
+ context: {
458
+ accountAddress: accountAddress
459
+ }
460
+ });
461
+ throw new Error(ERROR_SIGN_MESSAGE);
462
+ case 5:
463
+ return [
464
+ 2
465
+ ];
466
+ }
467
+ });
468
+ })();
469
+ }
470
+ },
471
+ {
472
+ key: "signTransaction",
473
+ value: /**
474
+ * Signs a transaction using MPC
475
+ * @param senderAddress - The sender address
476
+ * @param transaction - The serialized transaction to sign
477
+ * @param password - The password for encrypted backup shares
478
+ * @param externalServerKeyShares - The external server key shares
479
+ * @param onError - The function to call if an error occurs
480
+ * @returns The signature as a base64 string
481
+ */ function signTransaction(param) {
482
+ var senderAddress = param.senderAddress, transaction = param.transaction, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, externalServerKeyShares = param.externalServerKeyShares, onError = param.onError;
483
+ var _this = this;
484
+ return _async_to_generator(function() {
485
+ var signatureEd25519, formattedSignature, error;
486
+ return _ts_generator(this, function(_state) {
487
+ switch(_state.label){
488
+ case 0:
489
+ if (!senderAddress) {
490
+ throw new Error(ERROR_ACCOUNT_ADDRESS_REQUIRED);
491
+ }
492
+ return [
493
+ 4,
494
+ _this.verifyPassword({
495
+ accountAddress: senderAddress,
496
+ password: password,
497
+ walletOperation: WalletOperation.SIGN_TRANSACTION
498
+ })
499
+ ];
500
+ case 1:
501
+ _state.sent();
502
+ _state.label = 2;
503
+ case 2:
504
+ _state.trys.push([
505
+ 2,
506
+ 5,
507
+ ,
508
+ 6
509
+ ]);
510
+ // Attempt to recover key shares from backup if not provided
511
+ return [
512
+ 4,
513
+ _this.ensureKeySharesRecovered({
514
+ accountAddress: senderAddress,
515
+ password: password,
516
+ walletOperation: WalletOperation.SIGN_TRANSACTION,
517
+ externalServerKeyShares: externalServerKeyShares,
518
+ errorMessage: 'External server key shares are required to sign a transaction. No backup shares available for recovery.'
519
+ })
520
+ ];
521
+ case 3:
522
+ _state.sent();
523
+ return [
524
+ 4,
525
+ _this.sign({
526
+ message: transaction,
527
+ accountAddress: senderAddress,
528
+ chainName: _this.chainName,
529
+ password: password,
530
+ externalServerKeyShares: externalServerKeyShares,
531
+ onError: onError
532
+ })
533
+ ];
534
+ case 4:
535
+ signatureEd25519 = _state.sent();
536
+ formattedSignature = Buffer.from(signatureEd25519).toString('base64');
537
+ return [
538
+ 2,
539
+ formattedSignature
540
+ ];
541
+ case 5:
542
+ error = _state.sent();
543
+ logError({
544
+ message: ERROR_SIGN_TRANSACTION,
545
+ error: error,
546
+ context: {
547
+ senderAddress: senderAddress
548
+ }
549
+ });
550
+ throw new Error(ERROR_SIGN_TRANSACTION);
551
+ case 6:
552
+ return [
553
+ 2
554
+ ];
555
+ }
556
+ });
557
+ })();
558
+ }
559
+ },
560
+ {
561
+ key: "exportPrivateKey",
562
+ value: /**
563
+ * Exports the private key for a given account address
564
+ * @param accountAddress - The account address to export the private key for
565
+ * @param password - The password for encrypted backup shares
566
+ * @param externalServerKeyShares - The external server key shares
567
+ * @returns The private key as a hex string
568
+ */ function exportPrivateKey(param) {
569
+ var accountAddress = param.accountAddress, _param_password = param.password, password = _param_password === void 0 ? undefined : _param_password, externalServerKeyShares = param.externalServerKeyShares;
570
+ var _this = this;
571
+ return _async_to_generator(function() {
572
+ var derivedPrivateKey, privateScalarHex, error;
573
+ return _ts_generator(this, function(_state) {
574
+ switch(_state.label){
575
+ case 0:
576
+ _state.trys.push([
577
+ 0,
578
+ 4,
579
+ ,
580
+ 5
581
+ ]);
582
+ return [
583
+ 4,
584
+ _this.verifyPassword({
585
+ accountAddress: accountAddress,
586
+ password: password,
587
+ walletOperation: WalletOperation.EXPORT_PRIVATE_KEY
588
+ })
589
+ ];
590
+ case 1:
591
+ _state.sent();
592
+ // Attempt to recover key shares from backup if not provided
593
+ return [
594
+ 4,
595
+ _this.ensureKeySharesRecovered({
596
+ accountAddress: accountAddress,
597
+ password: password,
598
+ walletOperation: WalletOperation.EXPORT_PRIVATE_KEY,
599
+ externalServerKeyShares: externalServerKeyShares,
600
+ errorMessage: 'External server key shares are required to export private key. No backup shares available for recovery.'
601
+ })
602
+ ];
603
+ case 2:
604
+ _state.sent();
605
+ return [
606
+ 4,
607
+ _this.exportKey({
608
+ accountAddress: accountAddress,
609
+ chainName: _this.chainName,
610
+ password: password,
611
+ externalServerKeyShares: externalServerKeyShares
612
+ })
613
+ ];
614
+ case 3:
615
+ derivedPrivateKey = _state.sent().derivedPrivateKey;
616
+ if (!derivedPrivateKey) {
617
+ throw new Error('Derived private key is undefined');
618
+ }
619
+ // TON private keys are 64 hex characters (32 bytes)
620
+ privateScalarHex = derivedPrivateKey.slice(0, 64);
621
+ return [
622
+ 2,
623
+ privateScalarHex
624
+ ];
625
+ case 4:
626
+ error = _state.sent();
627
+ logError({
628
+ message: ERROR_EXPORT_PRIVATE_KEY,
629
+ error: error,
630
+ context: {
631
+ accountAddress: accountAddress
632
+ }
633
+ });
634
+ throw new Error(ERROR_EXPORT_PRIVATE_KEY);
635
+ case 5:
636
+ return [
637
+ 2
638
+ ];
639
+ }
640
+ });
641
+ })();
642
+ }
643
+ },
644
+ {
645
+ key: "offlineExportPrivateKey",
646
+ value: /**
647
+ * Exports the private key offline using key shares
648
+ * @param keyShares - The key shares to export the private key for
649
+ * @param derivationPath - The derivation path
650
+ * @returns The derived private key
651
+ */ function offlineExportPrivateKey(param) {
652
+ var keyShares = param.keyShares, derivationPath = param.derivationPath;
653
+ var _this = this;
654
+ return _async_to_generator(function() {
655
+ var derivedPrivateKey;
656
+ return _ts_generator(this, function(_state) {
657
+ switch(_state.label){
658
+ case 0:
659
+ return [
660
+ 4,
661
+ _this.offlineExportKey({
662
+ chainName: _this.chainName,
663
+ keyShares: keyShares,
664
+ derivationPath: derivationPath
665
+ })
666
+ ];
667
+ case 1:
668
+ derivedPrivateKey = _state.sent().derivedPrivateKey;
669
+ return [
670
+ 2,
671
+ {
672
+ derivedPrivateKey: derivedPrivateKey
673
+ }
674
+ ];
675
+ }
676
+ });
677
+ })();
678
+ }
679
+ },
680
+ {
681
+ key: "importPrivateKey",
682
+ value: /**
683
+ * Imports a private key and stores the key shares in the wallet map.
684
+ * @param privateKey - The private key to import.
685
+ * @param chainName - The chain name to use for the wallet.
686
+ * @param thresholdSignatureScheme - The threshold signature scheme to use for the wallet.
687
+ * @param password - The password to use for the wallet.
688
+ * @param onError - The function to call if an error occurs.
689
+ * @param backUpToClientShareService - Whether to back up the external server key shares to the client share service.
690
+ * @param publicAddressCheck - Optional public address to verify against the derived address.
691
+ * @returns The account address, public key hex, raw public key, and external server key shares.
692
+ */ function importPrivateKey(param) {
693
+ 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, _param_backUpToClientShareService = param.backUpToClientShareService, backUpToClientShareService = _param_backUpToClientShareService === void 0 ? false : _param_backUpToClientShareService, publicAddressCheck = param.publicAddressCheck;
694
+ var _this = this;
695
+ return _async_to_generator(function() {
696
+ var ceremonyCeremonyCompleteResolver, ceremonyCompletePromise, formattedPrivateKey, publicKeyHex, derivedAddress, _ref, rawPublicKey, externalServerKeyShares, resultPublicKeyHex, accountAddress, error;
697
+ return _ts_generator(this, function(_state) {
698
+ switch(_state.label){
699
+ case 0:
700
+ _state.trys.push([
701
+ 0,
702
+ 4,
703
+ ,
704
+ 5
705
+ ]);
706
+ ceremonyCompletePromise = new Promise(function(resolve) {
707
+ ceremonyCeremonyCompleteResolver = resolve;
708
+ });
709
+ formattedPrivateKey = privateKey.startsWith('0x') ? privateKey.slice(2) : privateKey;
710
+ publicKeyHex = _this.getPublicKeyFromPrivateKey(formattedPrivateKey);
711
+ derivedAddress = _this.deriveTonAddress({
712
+ publicKeyHex: publicKeyHex,
713
+ workchain: 0
714
+ });
715
+ if (publicAddressCheck && derivedAddress !== publicAddressCheck) {
716
+ throw new Error("Public address mismatch: derived address ".concat(derivedAddress, " !== public address ").concat(publicAddressCheck));
717
+ }
718
+ return [
719
+ 4,
720
+ _this.importRawPrivateKey({
721
+ chainName: chainName,
722
+ thresholdSignatureScheme: thresholdSignatureScheme,
723
+ privateKey: formattedPrivateKey,
724
+ onCeremonyComplete: function(accountAddress, walletId) {
725
+ var chainConfig = getMPCChainConfig(_this.chainName);
726
+ _this.initializeWalletMapEntry({
727
+ accountAddress: accountAddress,
728
+ walletId: walletId,
729
+ chainName: _this.chainName,
730
+ thresholdSignatureScheme: thresholdSignatureScheme,
731
+ derivationPath: JSON.stringify(Object.fromEntries(chainConfig.derivationPath.map(function(value, index) {
732
+ return [
733
+ index,
734
+ value
735
+ ];
736
+ })))
737
+ });
738
+ ceremonyCeremonyCompleteResolver(undefined);
739
+ },
740
+ onError: function(e) {
741
+ logError({
742
+ message: 'importPrivateKey: onError',
743
+ error: e,
744
+ context: {}
745
+ });
746
+ onError === null || onError === void 0 ? void 0 : onError(e);
747
+ }
748
+ })
749
+ ];
750
+ case 1:
751
+ _ref = _state.sent(), rawPublicKey = _ref.rawPublicKey, externalServerKeyShares = _ref.externalServerKeyShares;
752
+ return [
753
+ 4,
754
+ ceremonyCompletePromise
755
+ ];
756
+ case 2:
757
+ _state.sent();
758
+ if (!rawPublicKey || !externalServerKeyShares || !(typeof rawPublicKey === 'string' || _instanceof(rawPublicKey, Uint8Array))) {
759
+ throw new Error(ERROR_IMPORT_PRIVATE_KEY);
760
+ }
761
+ resultPublicKeyHex = typeof rawPublicKey === 'string' ? rawPublicKey : Buffer.from(rawPublicKey).toString('hex');
762
+ accountAddress = _this.deriveTonAddress({
763
+ publicKeyHex: resultPublicKeyHex,
764
+ workchain: 0
765
+ });
766
+ if (accountAddress !== derivedAddress) {
767
+ throw new Error("Public key mismatch: derived address ".concat(accountAddress, " !== expected ").concat(derivedAddress));
768
+ }
769
+ return [
770
+ 4,
771
+ _this.storeEncryptedBackupByWalletWithRetry({
772
+ accountAddress: accountAddress,
773
+ externalServerKeyShares: externalServerKeyShares,
774
+ password: password,
775
+ backUpToClientShareService: backUpToClientShareService
776
+ })
777
+ ];
778
+ case 3:
779
+ _state.sent();
780
+ return [
781
+ 2,
782
+ {
783
+ accountAddress: accountAddress,
784
+ publicKeyHex: resultPublicKeyHex,
785
+ rawPublicKey: rawPublicKey,
786
+ externalServerKeyShares: externalServerKeyShares
787
+ }
788
+ ];
789
+ case 4:
790
+ error = _state.sent();
791
+ logError({
792
+ message: ERROR_IMPORT_PRIVATE_KEY,
793
+ error: error,
794
+ context: {}
795
+ });
796
+ onError === null || onError === void 0 ? void 0 : onError(error);
797
+ throw new Error(ERROR_IMPORT_PRIVATE_KEY);
798
+ case 5:
799
+ return [
800
+ 2
801
+ ];
802
+ }
803
+ });
804
+ })();
805
+ }
806
+ },
807
+ {
808
+ /**
809
+ * Derives the public key from a private key
810
+ * @param privateKeyHex - The private key as a hex string
811
+ * @returns The public key as a hex string
812
+ */ key: "getPublicKeyFromPrivateKey",
813
+ value: function getPublicKeyFromPrivateKey(privateKeyHex) {
814
+ try {
815
+ var privateKeyBytes = Buffer.from(privateKeyHex, 'hex');
816
+ if (privateKeyBytes.length !== 32) {
817
+ throw new Error("Invalid private key length: ".concat(privateKeyBytes.length, ", expected 32"));
818
+ }
819
+ var keyPair = keyPairFromSeed(privateKeyBytes);
820
+ return keyPair.publicKey.toString('hex');
821
+ } catch (error) {
822
+ this.logger.error('Unable to derive public key from private key. Check private key format', _instanceof(error, Error) ? error.message : 'Unknown error');
823
+ throw error;
824
+ }
825
+ }
826
+ },
827
+ {
828
+ key: "getTonWallets",
829
+ value: /**
830
+ * Gets all TON wallets
831
+ * @returns Array of TON wallets
832
+ */ function getTonWallets() {
833
+ var _this = this;
834
+ return _async_to_generator(function() {
835
+ var wallets, tonWallets;
836
+ return _ts_generator(this, function(_state) {
837
+ switch(_state.label){
838
+ case 0:
839
+ return [
840
+ 4,
841
+ _this.getWallets()
842
+ ];
843
+ case 1:
844
+ wallets = _state.sent();
845
+ tonWallets = wallets.filter(function(wallet) {
846
+ return wallet.chainName === 'ton';
847
+ });
848
+ return [
849
+ 2,
850
+ tonWallets
851
+ ];
852
+ }
853
+ });
854
+ })();
855
+ }
856
+ }
857
+ ]);
858
+ return DynamicTonWalletClient;
859
+ }(DynamicWalletClient);
860
+
861
+ export { DynamicTonWalletClient, ERROR_ACCOUNT_ADDRESS_REQUIRED, ERROR_CREATE_WALLET_ACCOUNT, ERROR_EXPORT_PRIVATE_KEY, ERROR_IMPORT_PRIVATE_KEY, ERROR_KEYGEN_FAILED, ERROR_SIGN_MESSAGE, ERROR_SIGN_TRANSACTION };