-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackground.js
1211 lines (945 loc) · 36.5 KB
/
background.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @name ScaleWallet - Everscale browser wallet and injector
* @copyright SVOI.dev Labs - https://svoi.dev
* @license Apache-2.0
* @version 1.0
*/
import ExtensionMessenger from "./modules/ExtensionMessenger.mjs";
import TonClientWrapper from "./modules/TonClientWrapper.mjs";
import PrivateStorage from "./modules/PrivateStorage.mjs";
import NameStorage from "./modules/NameStorage.mjs";
import Keyring from "./modules/Keyring.mjs";
import Utils from "./modules/utils.mjs";
import EXCEPTIONS from "./modules/const/Exceptions.mjs";
import NetworkManager from "./modules/NetworkManager.mjs";
import MESSAGES from "./modules/const/Messages.mjs";
import AccountManager from "./modules/AccountManager.mjs";
import uiUtils from "./modules/ui/uiUtils.mjs";
import Wallet from "./modules/freeton/contracts/Wallet.mjs";
import FreetonInstance from "./modules/freeton/FreetonInstance.mjs";
import FreetonCrypto from "./modules/freeton/FreetonCrypto.mjs";
import FreetonDeploy from "./modules/freeton/FreetonDeploy.mjs";
import BroxusTIP3 from "./modules/freeton/contracts/tokens/tip3-fungible/broxus/BroxusTIP3.mjs";
import TokenManager from "./modules/TokenManager.mjs";
import Token from "./modules/Token.mjs";
import MISC from "./modules/const/Misc.mjs";
import LOCALIZATION from "./modules/Localization.mjs";
import TIP3Contract from "./modules/const/TIP3Contract.mjs";
import ActionProgressManager from "./modules/ActionProgressManager.mjs";
import init, * as nt from './modules/freeton/nekoton/nekoton_wasm.js';
import {unpackFromCell} from "./modules/freeton/nekoton/nekoton_wasm.js";
const _ = LOCALIZATION._;
import LocalStorage from "./modules/LocalStorage.mjs";
import FingerprintAuth from "./modules/ui/FingerprintAuth.mjs";
let localStorage = new LocalStorage();
console.log('IM BACKGROUND');
const wait = (timeout = 500) => {
return new Promise(resolve => {
setTimeout(resolve, timeout)
})
}
const RPC = {
sender: null,
'test': async (a, b) => {
return a + b;
},
'fall': async () => {
throw EXCEPTIONS.testException;
},
/**
* Open popup
* @returns {Promise<*>}
*/
mainOpenPopup: function async(options) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
return uiUtils.openPopup(options);
},
/**
* Contract run
* @param publicKey
* @param data
* @returns {Promise<boolean>}
*/
main_run: async (publicKey, data) => {
data.keyPair = await getKeysFromDeployAcceptence(publicKey, 'run', data);
actionManager.startActionOnce('main_run');
try {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
let runResult = await ton.contracts.run(data);
actionManager.endAction('main_run');
return runResult;
} catch (e) {
actionManager.endAction('main_run');
throw e;
}
},
/**
* Run contract local
* This method can save some ram for FreeTON instance
* @param publicKey
* @param data
* @returns {Promise<*>}
*/
main_runLocal: async (publicKey, data) => {
data.keyPair = await getKeysFromDeployAcceptence(publicKey, 'runLocal', data);
actionManager.startActionOnce('main_runLocal');
try {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
let runResult = await ton.contracts.runLocal(data);
actionManager.endAction('main_runLocal');
return runResult;
} catch (e) {
actionManager.endAction('main_runLocal');
throw e;
}
},
/**
* createRunMessage mock
* @param {string} publicKey
* @param {object} data
* @returns {Promise<*>}
*/
main_createRunMessage: async (publicKey, data) => {
data.keyPair = await getKeysFromDeployAcceptence(publicKey, 'createRunMessage', data)
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
return await ton.contracts.createRunMessage(data);
},
/**
* createDeployMessage mock
* @param {string} publicKey
* @param {object} data
* @returns {Promise<*>}
*/
main_createDeployMessage: async (publicKey, data) => {
data.keyPair = await getKeysFromDeployAcceptence(publicKey, 'createDeployMessage', data)
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
return await ton.contracts.createDeployMessage(data);
},
/**
* Returns keys in keyring
* @returns {Promise<string[]>}
*/
main_getPublicKeys: async () => {
return await keyring.getPublicKeys();
},
/**
* Check is public key in keyring
* @param publicKey
* @returns {Promise<*>}
*/
main_isKeyInKeyring: async (publicKey) => {
return await keyring.isKeyInKeyring(publicKey);
},
/**
* Get current network
* @param name
* @returns {Promise<{name: string, network: *}>}
*/
main_getNetwork: async (name = undefined) => {
let network = await networkManager.getNetwork(name);
/* //Reformat network endpoints to new format
network.network.urls = Utils.unpackNetworks(network.network.url);
//Deprecated
network.network.url = network.network.urls[0];*/
return await networkManager.getNetwork(name);
},
/**
* Get existsing networks
* @returns {Promise<*>}
*/
main_getNetworks: async () => {
return await networkManager.getNetworks();
},
/**
* Change current network
* @param network
* @returns {Promise<*>}
*/
main_changeNetwork: async function (network) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
return await networkManager.changeNetwork(network);
},
/**
* Add custom network to list
* @param networkName
* @param url
* @param description
* @returns {Promise<void>}
*/
main_addCustomNetwork: async function (networkName, url, description) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
await networkManager.addNetwork(networkName, url, description);
return await networkManager.changeNetwork(networkName);
},
/**
* Change current account
* @param publicKey
* @returns {Promise<boolean>}
*/
main_changeAccount: async function (publicKey) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
if(!await keyring.isKeyInKeyring(publicKey)) {
await messenger.rpcCall('popup_alert', [_('Public key not found')], 'popup');
throw EXCEPTIONS.publicKeyNotFound
}
await accountManager.changeAccount(publicKey);
return true;
},
/**
* Returns account info
* @returns {Promise<*>}
*/
main_getAccount: async () => {
return await accountManager.getAccount();
},
/**
* Set wallet object for public key
* @param {string} publicKey
* @param {string} network
* @param {object} wallet
* @returns {Promise<void>}
*/
main_setNetworkWallet: async function (publicKey, network, wallet) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
return await accountManager.setPublicKeyNetworkWallet(publicKey, network, wallet);
},
/**
* Returns wallet balance
* @param {string} address
* @returns {Promise<*>}
*/
main_getWalletBalance: async (address) => {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
let wallet = await (new Wallet(address, ton)).init();
window.wallet = wallet;
return await wallet.getBalance();
},
/**
* Returns wallet history
* @param address
* @param amount
* @returns {Promise<Wallet>}
*/
main_getWalletHistory: async function (address, amount = 20) {
console.log('getWalletHistory', address, amount);
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
let wallet = await (new Wallet(address, ton)).init();
window.wallet = wallet;
return await wallet.getHistory(amount);
},
/**
* Check wallet deployed
* @param {string} address
* @returns {Promise<boolean>}
*/
main_getWalletDeployed: async (address) => {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
let wallet = await (new Wallet(address, ton)).init();
return await wallet.contractDeployed();
},
/**
* Transfer money to another account
* @param from
* @param publicKey
* @param to
* @param amount
* @param payload
* @param bounce
* @param openPopup
* @returns {Promise<void>}
*/
main_transfer: async function (from, publicKey, to, amount, payload = '', bounce = false, openPopup = true) {
/*if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}*/
let sender = this.sender;
console.log('SENDER', sender);
actionManager.startActionOnce('main_transfer');
try {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
let wallet = await (new Wallet(from, ton)).init();
let network = await networkManager.getNetwork();
console.log(amount);
let keyPair = await getKeysFromDeployAcceptence(publicKey, 'transfer', {
address: from,
additionalMessage: `${_('This action sends')} <b>${Utils.showToken(Utils.unsignedNumberToSigned(amount))}</b> ${network.network.tokenIcon} ${_('to')} <span class="intextWallet">${to}</span> ${_('wallet')}.`,
}, undefined, !openPopup);
await messenger.rpcCall('popup_showToast', [_('Transaction created')], 'popup');
let transferResult = await wallet.transferNew(to, amount, payload, bounce, keyPair);
actionManager.endAction('main_transfer');
if(sender === 'page' && openPopup && window._isApp) {
window.messenger.rpcCall('page_showBrowser', [], 'page');
}
return transferResult;
} catch (e) {
actionManager.endAction('main_transfer');
if(sender === 'page' && openPopup && window._isApp) {
window.messenger.rpcCall('page_showBrowser', [], 'page');
}
throw e;
}
},
/**
* Create or change wallet
* @param publicKey
* @param type
* @returns {Promise<*>}
*/
main_createWallet: async function (publicKey, type) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
let network = await networkManager.getNetwork();
let contractDeployer = new FreetonDeploy(network.network.url);
return await contractDeployer.createWallet(publicKey, type);
},
/**
* Deploy multisig wallet
* @param publicKey
* @param type
* @returns {Promise<*>}
*/
main_deployWallet: async function (publicKey, type) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
actionManager.startActionOnce('main_deployWallet');
try {
let network = await networkManager.getNetwork();
let keyPair = await getKeysFromDeployAcceptence(publicKey, _('Deploy contract'), {
//address: from,
additionalMessage: `${_('Ths action deploys')} ${type} ${_('wallet contract')}.`,
}, undefined, true);
let contractDeployer = new FreetonDeploy(network.network.url);
let deployResult = await contractDeployer.deployWallet(keyPair, type);
actionManager.endAction('main_deployWallet');
return deployResult;
} catch (e) {
actionManager.endAction('main_deployWallet');
throw e;
}
},
/**
* Generates seed phrase
* @returns {Promise<*>}
*/
main_generateSeedPhrase: async () => {
return await freetonCrypto.generateSeed();
},
/**
* Generates seed phrase
* @returns {Promise<*>}
*/
main_getKeysFromSeedPhrase: async (seed) => {
return await freetonCrypto.seedOrPrivateToKeypair(seed);
},
/**
* Returns encoded comment payload
* @param comment
* @returns {Promise<*>}
*/
main_encodePayloadComment: async (comment) => {
return await Utils.encodePayloadComment(comment);
},
/**
* Add account to storage
* @returns {Promise<*>}
*/
main_addAccount: async function (publicKey, privateKey, seedPhrase, password) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
return await accountManager.addAccount(publicKey, privateKey, seedPhrase, password);
},
/**
* Add account to storage
* @returns {Promise<*>}
*/
main_getAccountInfo: async function (publicKey) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
let password = await messenger.rpcCall('popup_password', ['', publicKey], 'popup');
if(!password) {
throw EXCEPTIONS.rejectedByUser;
}
let keyPair = {};
try {
keyPair = await keyring.extractKey(publicKey, password);
} catch (e) {
//Retry password
let password = await messenger.rpcCall('popup_password', ['<span style="color: red">' + _('Invalid password') + '</span><br>', publicKey], 'popup');
if(!password) {
throw EXCEPTIONS.rejectedByUser;
}
try {
keyPair = await keyring.extractKey(publicKey, password);
} catch (e) {
throw EXCEPTIONS.invalidPassword;
}
}
return keyPair;
},
/**
* Get account name from storage
* @returns {Promise<*>}
*/
main_getAccountName: async function (publicKey) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
return await NameStorage.get(publicKey);
},
/**
* Add account name to storage
* @returns {Promise<*>}
*/
main_setAccountName: async function (publicKey, name) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
let password = await messenger.rpcCall('popup_password', ['', publicKey], 'popup');
if(!password) {
throw EXCEPTIONS.rejectedByUser;
}
let keyPair = {};
try {
keyPair = await keyring.extractKey(publicKey, password);
} catch (e) {
//Retry password
let password = await messenger.rpcCall('popup_password', ['<span style="color: red">' + _('Invalid password') + '</span><br>', publicKey], 'popup');
if(!password) {
throw EXCEPTIONS.rejectedByUser;
}
try {
keyPair = await keyring.extractKey(publicKey, password);
} catch (e) {
throw EXCEPTIONS.invalidPassword;
}
}
return await NameStorage.set(publicKey, name);
},
/**
* Delete account from storage
* @returns {Promise<*>}
*/
main_deleteAccount: async function (publicKey) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
let password = await messenger.rpcCall('popup_password', ['', publicKey], 'popup');
if(!password) {
throw EXCEPTIONS.rejectedByUser;
}
let keyPair = {};
try {
keyPair = await keyring.extractKey(publicKey, password);
} catch (e) {
//Retry password
let password = await messenger.rpcCall('popup_password', ['<span style="color: red">' + _('Invalid password') + '</span><br>', publicKey], 'popup');
if(!password) {
throw EXCEPTIONS.rejectedByUser;
}
try {
keyPair = await keyring.extractKey(publicKey, password);
} catch (e) {
throw EXCEPTIONS.invalidPassword;
}
}
await accountManager.removeAccount(publicKey)
return await keyring.removeKey(publicKey);
},
/**
* Get account tokens
* @returns {Promise<*>}
*/
main_getAccountTokens: async function (publicKey, network) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
const tokenManager = await (new TokenManager()).init()
return await tokenManager.getAccountTokens(publicKey, network);
},
/**
* Get token info
* @param {string} tokenRootAddress
* @returns {Promise<{symbol, totalSupply: number, rootAddress: *, decimals: number, name, icon: null|string, fungible: boolean, type: string|{ERC20_TOKENS: {}, TIP3_NONFUNGIBLE_TOKENS: {}, TIP3_FUNGIBLE_TOKENS: {broxus: string}}|*}>}
*/
main_getTokenInfo: async function (tokenRootAddress) {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
const token = await (new Token(tokenRootAddress, ton)).init();
return await token.getInfo();
},
/**
* Get token balance
* @param tokenRootAddress
* @param publicKey
* @param walletAddress
* @returns {Promise<*>}
*/
main_getTokenBalance: async function (tokenRootAddress, publicKey, walletAddress) {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
const token = await (new Token(tokenRootAddress, ton)).init();
//return await token.getPubkeyBalance(publicKey);
return await token.getMultisigBalance(walletAddress);
},
/**
* Get token wallet address by public key
* @param tokenRootAddress
* @param publicKey
* @param walletAddress
* @returns {Promise<string>}
*/
main_getTokenWalletAddress: async function (tokenRootAddress, publicKey, walletAddress) {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
const token = await (new Token(tokenRootAddress, ton)).init();
//return await token.getPubkeyWalletAddress(publicKey);
return await token.getMultisigWalletAddress(walletAddress);
},
/**
* Add token to account
* @param publicKey
* @param tokenRootAddress
* @param network
* @returns {Promise<boolean>}
*/
main_addAccountToken: async function (publicKey, tokenRootAddress, network) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
const tokenManager = await (new TokenManager()).init();
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
const token = await (new Token(tokenRootAddress, ton)).init();
await tokenManager.addAccountToken(publicKey, network, tokenRootAddress, await token.getInfo());
return true;
},
/**
* Remove token from account
* @param publicKey
* @param tokenRootAddress
* @param network
* @returns {Promise<boolean>}
*/
main_removeAccountToken: async function (publicKey, tokenRootAddress, network) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
const tokenManager = await (new TokenManager()).init();
await tokenManager.removeAccountToken(publicKey, tokenRootAddress, network);
return true;
},
/**
* Transfer token
* @param {string} rootTokenAddress Token Root address
* @param {string} walletAddress Current wallet
* @param {string} publicKey
* @param to
* @param amount
* @param multisigAddress
* @returns {Promise<*>}
*/
main_tokenTransfer: async function (rootTokenAddress, walletAddress, publicKey, to, amount, multisigAddress) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
actionManager.startActionOnce('main_tokenTransfer');
try {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
const token = await (new Token(rootTokenAddress, ton)).init();
let tokenInfo = await token.getInfo();
let keyPair = await getKeysFromDeployAcceptence(publicKey, 'token_transfer', {
address: walletAddress,
additionalMessage: `${_('This action sends')} <b>${Utils.showToken(Utils.unsignedNumberToSigned(amount, tokenInfo.decimals))}</b> ${_('tokens to')} <span class="intextWallet">${to}</span> ${_('wallet.')}`,
}, undefined, true);
await messenger.rpcCall('popup_showToast', [_('Token transaction created')], 'popup');
let txInfo = await token.multisigTransfer(to, amount, keyPair, multisigAddress);
console.log(txInfo);
await messenger.rpcCall('popup_showToast', [_('Token transfer complete')], 'popup');
actionManager.endAction('main_tokenTransfer');
} catch (e) {
actionManager.endAction('main_tokenTransfer');
throw e;
}
return true;
},
/**
* Get constant from MISC constants
* @param {string} constant
* @returns {Promise<string>}
*/
main_getMiscConstant: async function (constant = 'VERSION') {
return MISC[constant]
},
/**
* Create TIP3 token
* @param type
* @param options
* @param fromWallet
* @param publicKey
* @returns {Promise<boolean>}
*/
main_createTip3Token: async function (type = TIP3Contract.ROOT_TYPES.BroxusTIP3, options, fromWallet, publicKey) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
actionManager.startActionOnce('main_createTip3Token');
try {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
console.log('CREATE TIP3', type, options);
let network = await networkManager.getNetwork();
let contractDeployer = new FreetonDeploy(network.network.url);
let newRootAddress = await contractDeployer.predictTIP3RootAddress(type, options, publicKey);
console.log('ROOT ADDRESS', newRootAddress);
let keyPair = await getKeysFromDeployAcceptence(publicKey, 'create_token', {
address: newRootAddress,
additionalMessage: `${_('This action deploy new TIP3 token contract')} 1 TON`,
}, undefined, true);
//Transfer tokens for contact deploy
let transferResult = await wallet.transfer(newRootAddress, 1e9, '', keyPair);
console.log('TIP3 deploy transfer result', transferResult);
let deployResult = await contractDeployer.deployTIP3Root(type, options, keyPair);
console.log('TIP3 deploy ROOT result', deployResult);
const token = await (new Token(newRootAddress, ton)).init();
let deployWalletResult = await token.deployWallet(options.initialMint, await (new Wallet(fromWallet, ton)).init(), keyPair);
console.log('TIP3 deploy WALLET result', deployWalletResult);
const tokenManager = await (new TokenManager()).init();
await tokenManager.addAccountToken(publicKey, network.name, newRootAddress, await token.getInfo());
console.log('TOKEN ADDED');
console.log(await tokenManager.getAccountTokens(publicKey, network.name))
actionManager.endAction('main_createTip3Token');
} catch (e) {
actionManager.endAction('main_createTip3Token');
console.error(e);
throw e;
}
return true;
},
/**
* Get any active actions
* @returns {Promise<*[]>}
*/
main_getActiveActions: async function () {
return actionManager.getActiveActions();
},
async main_signDataRaw(publicKey, data = '') {
actionManager.startActionOnce('main_signDataRaw');
try {
let keyPair = await getKeysFromDeployAcceptence(publicKey, 'sign_data_raw', {
//address: tokenWalletAddress,
additionalMessage: `${_('You are signing data')}: ${_(data)}`, //TODO fix injection
}, 'Sign', false);
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
let sign = await ton.lowLevel.crypto.sign({unsigned: data, keys: keyPair});
actionManager.endAction('main_signDataRaw');
return {
signature: Buffer.from(sign.signature, 'hex').toString('base64'),
signatureFull: sign.signed,
signatureHex: sign.signature,
signatureParts: {
high: `0x${sign.signature.slice(0, 64)}`,
low: `0x${sign.signature.slice(64, 128)}`,
}
}
} catch (e) {
actionManager.endAction('main_signDataRaw');
throw e;
}
},
async main_packIntoCell(params) {
const {structure, data} = params;
return {boc: await nt.packIntoCell(structure, data)}
},
async main_unpackFromCell(params) {
const {structure, boc, allowPartial} = params;
return {data: nt.unpackFromCell(structure, boc, allowPartial)};
},
async main_verifySignature(params) {
const {publicKey, dataHash, signature} = params;
return {isValid: nt.verifySignature(publicKey, dataHash, signature)};
},
async main_decodeTransactionEvents(params) {
const {transaction, abi} = params;
return {events: nt.decodeTransactionEvents(transaction, abi)};
},
async main_base64toHex(data) {
return Buffer.from(data, 'base64').toString('hex');
},
async main_hex2Base64(data) {
return Buffer.from(data, 'hex').toString('base64');
},
main_deployTokenWallet: async function (publicKey, walletAddress, tokenRootAddress, ownerAddress = null) {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
actionManager.startActionOnce('main_deployTokenWallet');
try {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
const token = await (new Token(tokenRootAddress, ton)).init();
console.log('DEPLOY TOKEN WALLET', publicKey, walletAddress, tokenRootAddress, ownerAddress);
let tokenWalletAddress = await token.getMultisigWalletAddress(ownerAddress);
//if we create wallet for other user
if(!ownerAddress) {
tokenWalletAddress = await token.getPubkeyWalletAddress(publicKey);
}
let keyPair = await getKeysFromDeployAcceptence(publicKey, 'create_token', {
address: tokenWalletAddress,
additionalMessage: `${_('This action deploy new token wallet')} 1 TON`,
}, undefined, true);
let tokenWallet = await (new Wallet(tokenWalletAddress, ton)).init();
let wallet = await (new Wallet(walletAddress, ton)).init();
let tokenWaletTONBalance = 0;
try {
tokenWaletTONBalance = await tokenWallet.getBalance();
} catch (e) {
}
if(tokenWaletTONBalance < 1e9) {
console.log('Transfering from', walletAddress, 'to', tokenWalletAddress);
//Transfer tokens for contact deploy
let transferResult = await wallet.transfer(tokenWalletAddress, 1e9, '', keyPair);
console.log('TIP3 wallet deploy transfer result', transferResult);
} else {
console.log('Wallet balance more than 1 TON, no pretransfer needed', tokenWalletAddress);
}
let deployWalletResult = await token.deployWallet(0, await (new Wallet(walletAddress, ton)).init(), keyPair, ownerAddress);
console.log('TIP3 deploy WALLET result', deployWalletResult);
actionManager.endAction('main_deployTokenWallet');
return deployResult;
} catch (e) {
actionManager.endAction('main_deployTokenWallet');
throw e;
}
},
/**
* @deprecated
* @param address
* @returns {Promise<boolean>}
*/
main_isMultisigAddress: async function (address) {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
try {
let wallet = await (new Wallet(address, ton)).init();
await wallet.getBalance();
return await wallet.contractDeployed()
} catch (e) {
return false;
}
},
/**
* Detects is TIP3 token
* @param tokenRoot
* @param address
* @returns {Promise<boolean>}
*/
main_isTokenWalletAddress: async function (tokenRoot, address) {
let ton = await FreetonInstance.getFreeTON((await networkManager.getNetwork()).network.url);
try {
const token = await (new Token(tokenRoot, ton)).init();
await token.getBalance(address);
return true;
} catch (e) {
return false;
}
},
/**
* Returns inpage config script
* @returns {Promise<string>}
*/
async main_getConfigScript() {
let config = {};
if(await localStorage.get('everWalletEmulation', window._isApp ? true : false)) {
config.EVERWalletEmulation = true;
}
return `
window._everscaleWalletConfig = ${JSON.stringify(config)};
`;
},
/**
* Add account to storage
* @returns {Promise<*>}
*/
main_popupHeartbeat: async function () {
if(this.sender !== 'popup') {
throw EXCEPTIONS.invalidInvoker;
}
window.hasActivePopup = true;
window.hasActivePopupSecondCheck = false;
},
}
/**
* Open accept sign message
* @param publicKey
* @param type
* @param callingData
* @param acceptMessage
* @param dontCreatePopup
* @returns {Promise<{public, secret: *}>}
*/
async function getKeysFromDeployAcceptence(publicKey, type = 'run', callingData, acceptMessage = '', dontCreatePopup = false) {
if(!dontCreatePopup) {