-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.html
1672 lines (1374 loc) · 62.7 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en" translate="no">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no,viewport-fit=cover">
<title>TON Vesting Wallet</title>
<script src="lib/tonweb-0.0.62.js"></script>
<!-- <script src="lib/tonconnect-ui-1.0.0-beta.5.min.js"></script>-->
<script src="https://unpkg.com/@tonconnect/ui@latest/dist/tonconnect-ui.min.js"></script>
<script src="js/check-smart-contract.js?4"></script>
<link rel="stylesheet" href="css/main.css?3">
</head>
<body>
<div class="testnet-badge" style="display: none">
ATTENTION! This is the test network — don’t send real Toncoin!
</div>
<!--Header-->
<div id="header">
<!-- Badge -->
<a href="https://ton.org">
<div id="header_logo"></div>
</a>
<div id="header_slash">/</div>
<div id="header_title">Vesting</div>
<!-- Header search -->
<div id="header_input-container">
<input id="header_input" type="text" placeholder="Enter address">
<svg class="header_input-icon" width="18" height="18" viewBox="0 0 24 24" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M13.0666 17.8667C16.8958 17.8667 20 14.7625 20 10.9333C20 7.10416 16.8958 4 13.0666 4C9.23746 4 6.1333 7.10416 6.1333 10.9333C6.1333 14.7625 9.23746 17.8667 13.0666 17.8667Z"
stroke="#98B2BF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M8 16L4 20" stroke="#98B2BF" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round"></path>
</svg>
</div>
<div id="header_grow"></div>
<!-- TON Connect Button -->
<div id="tonConnectButton"></div>
</div>
<!-- Main Screen -->
<div id="mainScreen" class="screen">
<div class="main_header">
Vesting Manager
</div>
<div class="main_info">
Manage wallets with Toncoin locked for some time.
</div>
<div class="main_input-container">
<input class="main_input" placeholder="Enter address">
<svg class="main_input-icon" width="24" height="24" viewBox="0 0 24 24" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M13.0666 17.8667C16.8958 17.8667 20 14.7625 20 10.9333C20 7.10416 16.8958 4 13.0666 4C9.23746 4 6.1333 7.10416 6.1333 10.9333C6.1333 14.7625 9.23746 17.8667 13.0666 17.8667Z"
stroke="#98B2BF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
<path d="M8 16L4 20" stroke="#98B2BF" stroke-width="2" stroke-linecap="round"
stroke-linejoin="round"></path>
</svg>
</div>
</div>
<!-- Loading Screen -->
<div id="loadingScreen" class="screen">
<div class="loading"></div>
</div>
<!-- Address Screen-->
<div id="addressScreen" class="screen">
<div class="address_header">Address</div>
<div id="address_userAddress" class="address"></div>
<div id="address_info"></div>
<div id="address_loading" class="loading"></div>
<button id="wallet_createButton" class="btn">Create new vesting for this user</button>
<div id="vesting_container"></div>
</div>
<!-- Create Screen -->
<div id="createScreen" class="screen">
<div class="create_header">Create new vesting wallet for user</div>
<div id="create_userAddress" class="address"></div>
<div style="text-align: center; margin-bottom: 30px; line-height: 150%; color: orangered">
<b>Do not create vesting smart contracts for addresses managed by SafePal, bots, exchanges etc.</b><br>
Create vesting only for regular wallets or Ledger from which the recipient knows the seed phrase.
</div>
<div id="create_panel">
<div class="create_label">Vesting start time (local timezone):</div>
<div class="create_input">
<input id="create_startTimeInput" type="datetime-local">
</div>
<div class="create_label">Total vesting amount (TON):</div>
<div class="create_input">
<input id="create_totalAmountInput" type="number">
</div>
<div class="create_label">Total vesting duration (days):</div>
<div class="create_input">
<input id="create_totalDurationInput" type="number">
</div>
<div class="create_label">Cliff duration (days):</div>
<div class="create_input">
<input id="create_cliffDurationInput" type="number">
</div>
<div class="create_label">Unlock period (days):</div>
<div class="create_input">
<input id="create_unlockPeriodInput" type="number">
</div>
<label class="checkbox-container"> In masterchain (for direct validation)
<input type="checkbox" id="create_inMasterchainCheckbox">
<span class="checkmark"></span>
</label>
<div class="create_label">Whitelist:
<button id="create_addWhitelistButton" class="create_whitelist-btn">+</button>
<!-- <button id="create_addTonstakersWhitelistButton" class="create_whitelist-btn">Add Tonstakers</button>-->
<!-- <button id="create_addElectorWhitelistButton" class="create_whitelist-btn">Add Elector</button>-->
</div>
<div id="create_whitelist-container" class="create_whitelist-container"></div>
<div id="create_error"></div>
<div id="create_info"></div>
<button id="create_createButton" class="btn">Create</button>
</div>
<div id="create_backBtn">Cancel</div>
</div>
<!-- Modal -->
<div id="modal" style="display: none">
<!-- Add Whitelist Popup-->
<div id="addWhitelistPopup">
<div id="whitelist_label">
Enter Address:
</div>
<input id="whitelist_addressInput" type="text">
<div id="whitelist_info"></div>
<button id="whitelist_addButton" class="btn">Add</button>
<button id="whitelist_useTonstakersPoolButton" class="btn">Use Tonstakers Pool</button>
<button id="whitelist_useTonstakersJettonButton" class="btn" disabled>Use Tonstakers Jetton</button>
<button id="whitelist_useElectorButton" class="btn">Use Elector</button>
</div>
<!-- Send Popup -->
<div id="sendPopup" class="sendPopup">
<input id="sendPopup_toAddressInput" placeholder="Enter destination address" class="sendPopup_input">
<input id="sendPopup_amountInput" placeholder="Enter amount" class="sendPopup_input" type="number">
<select id="sendPopup_payloadTypeInput" class="sendPopup_input">
<option value="text">Text</option>
<option value="boc">BOC</option>
<option value="base64">Base64</option>
<option value="hex">HEX</option>
</select>
<input id="sendPopup_payloadInput" placeholder="Enter comment (optional)" class="sendPopup_input">
<button id="sendPopup_sendButton" class="btn sendPopup_button">Send</button>
</div>
<!-- Stake Popup -->
<div id="stakePopup" class="sendPopup">
<div id="stakePopup_label" class="stakePopup_label">
Stake with Tonstakers:
</div>
<input id="stakePopup_amountInput" placeholder="Enter amount" class="sendPopup_input" type="number">
<div id="stakePopup_availableToStake" class="stakePopup_note"></div>
<button id="stakePopup_sendButton" class="btn sendPopup_button">Stake</button>
</div>
<!-- Unstake Popup -->
<div id="unstakePopup" class="sendPopup">
<div id="unstakePopup_label" class="stakePopup_label">
Unstake with Tonstakers:
</div>
<input id="unstakePopup_amountInput" placeholder="Enter amount" class="sendPopup_input" type="number">
<div id="unstakePopup_stakingJettonWalletBalance" class="stakePopup_note"></div>
<button id="unstakePopup_sendButton" class="btn sendPopup_button">Unstake</button>
</div>
</div>
<script>
// UI COMMON
/**
* @param selector {string}
* @return {HTMLElement | null}
*/
const $ = (selector) => document.querySelector(selector);
/**
* @param selector {string}
* @return {NodeListOf<HTMLElement>}
*/
const $$ = (selector) => document.querySelectorAll(selector);
/**
* @param element {HTMLElement}
* @param isVisible {boolean}
*/
const toggle = (element, isVisible) => {
element.style.display = isVisible ? 'flex' : 'none';
}
/**
* @param input {HTMLElement}
* @param handler {() => void}
*/
function onInput(input, handler) {
input.addEventListener('change', handler);
input.addEventListener('input', handler);
input.addEventListener('cut', handler);
input.addEventListener('paste', handler);
}
/**
* @param s {string}
*/
const checkHTML = (s) => {
if (s.indexOf('<') > -1 || s.indexOf('>') > -1) throw new Error('html injection');
}
/**
* @param s {string}
* @return {string}
*/
const bold = (s) => {
checkHTML(s);
return '<b>' + s + '</b>';
}
/**
* @param address {string}
* @return {string}
*/
const scanLink = (address) => {
checkHTML(address);
if (!TonWeb.utils.Address.isValid(address)) throw new Error('invalid address');
return `https://${IS_TESTNET ? 'testnet.' : ''}tonscan.org/address/${address}`;
}
/**
* @param name {'addWhitelistPopup' | 'sendPopup' | 'stakePopup' | 'unstakePopup'}
*/
const showPopup = (name) => {
const popups = ['addWhitelistPopup', 'sendPopup', 'stakePopup', 'unstakePopup'];
toggle($('#modal'), true);
for (const popup of popups) {
toggle($('#' + popup), popup === name);
}
}
const hidePopup = () => {
toggle($('#modal'), false);
}
$('#modal').addEventListener('click', () => hidePopup());
/**
* @type {'mainScreen' | 'addressScreen' | 'createScreen' | 'loadingScreen'}
*/
let currentScreen = 'mainScreen';
/**
* @param name {'mainScreen' | 'addressScreen' | 'createScreen' | 'loadingScreen'}
*/
const showScreen = (name) => {
const screens = ['mainScreen', 'addressScreen', 'createScreen', 'loadingScreen']
currentScreen = name;
for (const screen of screens) {
toggle($('#' + screen), screen === name);
}
$('#header_input-container').style.visibility = name !== 'mainScreen' ? 'visible' : 'hidden';
if (name === 'mainScreen') {
setTimeout(() => {
$('.main_input').focus();
}, 10);
}
hidePopup();
}
showScreen('mainScreen');
// PAGE
/** @type {string} */
const browserLang = navigator.language || navigator.userLanguage;
/** @type {'ru' | 'en'} */
const lang = (browserLang === 'ru-RU') || (browserLang === 'ru') || (browserLang === 'be-BY') || (browserLang === 'be') || (browserLang === 'kk-KZ') || (browserLang === 'kk') ? 'ru' : 'en';
/** @type {boolean} */
const IS_TESTNET = window.location.href.indexOf('testnet=true') > -1;
const IS_CUSTOM_OWNERS = window.location.href.indexOf('custom_owners=true') > -1;
if (IS_TESTNET) {
$('.testnet-badge').style.display = 'block';
document.body.classList.add('testnet-padding');
}
// TONCONNECT
/** @type {TonConnectUI} */
const tonConnectUI = new TON_CONNECT_UI.TonConnectUI({
manifestUrl: 'https://vesting.ton.org/tonconnect-manifest.json',
buttonRootId: 'tonConnectButton'
});
tonConnectUI.uiOptions = {
uiPreferences: {
theme: TON_CONNECT_UI.THEME.LIGHT
}
};
const tonConnectUnsubscribe = tonConnectUI.onStatusChange(info => {
if (info === null) {
onWalletDisconnected();
} else if (info.account) {
onWalletConnected(info.account);
}
});
// TONWEB COMMON
const BN = TonWeb.utils.BN;
const fromNano = TonWeb.utils.fromNano;
const toNano = TonWeb.utils.toNano;
/** @type {string} */
const TONCENTER_API_KEY = IS_TESTNET ? 'd843619b379084d133f061606beecbf72ae2bf60e0622e808f2a3f631673599b' : 'd843619b379084d133f061606beecbf72ae2bf60e0622e808f2a3f631673599b';
/** @type {string} */
const TONCENTER_URL = IS_TESTNET ? 'https://testnet.toncenter.com/api/v2/jsonRPC' : 'https://toncenter.com/api/v2/jsonRPC';
/** @type {string} */
const TONCENTER_INDEX_URL = IS_TESTNET ? 'https://testnet.toncenter.com/api/v3/' : 'https://toncenter.com/api/v3/';
/** @type {TonWeb} */
const tonweb = new TonWeb(new TonWeb.HttpProvider(TONCENTER_URL, {apiKey: TONCENTER_API_KEY}));
// STAKING COMMON
/** @type {string} */
const STAKING_CONTRACT_ADDRESS = IS_TESTNET ? 'kQCu_j-5niSEIN_R3qJMWvcjKSdpBJOFz1sJE9JXt549GAW8' : 'EQCkWxfyhAkim3g2DjKQQg8T5P4g-Q1-K_jErGcDJZ4i-vqR';
/** @type {string} */
const STAKE_TOKEN_NAME = 'tsTON';
/** @type {string} */
const UNSTAKE_PAYLOAD = 0x595f07bc
/** @type {string} */
const STAKE_PAYLOAD = 0x47d54391
/** @type {string} */
const REF_PAYLOAD = 0x000000106796caef
/** @type {string} */
const STAKING_FEE_RES = "1.5"
/** @type {string} */
const STAKE_FEE = "1"
/** @type {string} */
const UNSTAKE_FEE = "1.05"
// ELECTOR COMMON
/** @type {string} */
const ELECTOR_CONTRACT_ADDRESS = 'Ef8zMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzM0vF';
// VESTING COMMON
/**
* @return {string}
*/
const nowToInputValue = () => {
const now = new Date();
now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
return now.toISOString().slice(0, 16);
}
/**
* in UTC timezone
* @param timestamp {number} unixtime
* @return {string}
*/
const formatDateTime = (timestamp) => {
const date = new Date(timestamp * 1000);
return date.toUTCString();
}
/**
* @param seconds {number}
* @return {string}
*/
const formatPeriod = (seconds) => {
const d = Math.floor(seconds / (3600 * 24));
const h = Math.floor(seconds % (3600 * 24) / 3600);
const m = Math.floor(seconds % 3600 / 60);
const s = Math.floor(seconds % 60);
const arr = [
d === 0 ? '' : d + ' days',
h === 0 ? '' : h + ' hours',
m === 0 ? '' : m + ' min',
s === 0 ? '' : s + ' sec'
]
return arr.filter(s => s !== '').join(' ');
}
/**
* @param nano {BN}
* @param token {string}
* @return {string}
*/
const formatAmount = (nano, token = 'TON') => {
return fromNano(nano) + ' ' + token;
}
/**
*
* @param info {{vestingStartTime: number, vestingTotalDuration: number, unlockPeriod: number, cliffDuration: number, vestingTotalAmount: BN }}
* @return {string}
*/
const formatVestingInfo = (info) => {
/** @type {number} */
const cliffEndTime = info.vestingStartTime + info.cliffDuration;
/** @type {number} */
const vestingEndTime = info.vestingStartTime + info.vestingTotalDuration;
/** @type {BN} */
const cliffPeriodsCount = new BN(info.cliffDuration).div(new BN(info.unlockPeriod));
/** @type {BN} */
const periodsCount = new BN(info.vestingTotalDuration).div(new BN(info.unlockPeriod));
/** @type {BN} */
const cliffAmount = info.vestingTotalAmount.mul(cliffPeriodsCount).div(periodsCount);
/** @type {BN} */
const unlockAmount = info.unlockPeriod === info.vestingTotalDuration ? new BN(0) :
info.vestingTotalAmount.div(periodsCount);
/** @type {string} */
const startsString = `Vesting starts at ${bold(formatDateTime(info.vestingStartTime))}.`;
/** @type {string} */
const cliffString = info.cliffDuration ? ` Cliff period ends in ${bold(formatPeriod(info.cliffDuration))} at ${bold(formatDateTime(cliffEndTime))}, at this moment ${bold(formatAmount(cliffAmount))} will be unlocked.` : ` No cliff period.`;
/** @type {string} */
const unlockString = info.unlockPeriod < info.vestingTotalDuration ? ` After that ${bold(formatAmount(unlockAmount))} will be unlock every ${bold(formatPeriod(info.unlockPeriod))}.` : ``;
return `${startsString} ${cliffString} ${unlockString}<br>
Total amount ${bold(formatAmount(info.vestingTotalAmount))} will be unlocked in ${bold(formatPeriod(info.vestingTotalDuration))} at ${bold(formatDateTime(vestingEndTime))}.
`
}
/**
* @param address {string}
* @return {string}
*/
const formatAddress = (address) => {
checkHTML(address);
if (!TonWeb.utils.Address.isValid(address)) throw new Error('invalid address');
return `${address.substring(0, address.length / 2)}<wbr>${address.substring(address.length / 2)}`
}
/**
* @param container {HTMLElement}
* @param list {string[]}
* @param senderAddressString {string}
* @param isCreateScreen {boolean}
*/
const renderWhitelist = (container, list, senderAddressString, isCreateScreen) => {
/** @type {string} */
const senderBadge = ` <div class="badge badge-blue">Sender</div>`;
/** @type {string} */
const tonstakersBadge = ` <div class="badge badge-blue">Tonstakers</div>`;
/** @type {string} */
const electorBadge = isCreateScreen ? `` : ` <div class="badge badge-blue">Elector</div>`; // do not fit in create mobile screen
/**
* @param i {number}
* @return {string}
*/
const removeButton = (i) => isCreateScreen ? `<button class="create_whitelist-btn" onclick="removeWhitelist(${i})">-</button>` : ``;
/** @type {string} */
let s = '';
for (let i = 0; i < list.length; i++) {
/** @type {string} */
const address = list[i];
const isSender = address === senderAddressString;
const isTonstakersPool = address === STAKING_CONTRACT_ADDRESS;
const isTonstakersJetton = address === stakingJettonWalletAddress || address === createState?.stakingJettonWalletAddress;
const isElector = address === ELECTOR_CONTRACT_ADDRESS;
const badge = isSender ? senderBadge : (isTonstakersPool || isTonstakersJetton ? tonstakersBadge : (isElector ? electorBadge : ''));
const title = isSender ? 'Sender address' : (isTonstakersPool ? 'Tonstakers Pool' : (isTonstakersJetton ? 'Tonstakers Jetton' : (isElector ? 'Elector' : 'Address')));
s += `<div class="create_whitelist-row">
<div class="create_whitelist-num">${i + 1}.</div>
<a class="create_whitelist-address address" href="${scanLink(address)}" title="${title}" target="_blank">
${formatAddress(address)}
</a>
${badge + (isSender ? '' : removeButton(i))}
</div>`;
}
container.innerHTML = s;
}
// STATE
/** @type {string | null} */
let currentAddress = null; // user-friendly
/** @type {string | null} */
let myAddress = null; // user-friendly
/** @type {string | null} */
let userAddress = null;
/** @type {string | null} */
let userPublicKey = null; // hex
/** @type {VestingWalletV1 | null} */
let vestingWallet = null;
/** @type {string | null} */
let stakingJettonWalletAddress = null;
// NAVIGATE
/** @type {number} */
let reloadTimeoutId = 0;
const clear = () => {
currentAddress = null;
vestingWallet = null;
clearTimeout(reloadTimeoutId);
}
const goHome = () => {
clear();
window.history.pushState('', 'TON Vesting ', '#');
showScreen('mainScreen');
}
$('#header_title').addEventListener('click', () => {
goHome();
});
/**
* @param address {string}
*/
const getStakingJettonWalletAddress = async (address) => {
const STAKING_JETTON_MINTER_ADDRESS_INDEX = 12;
try {
const stakingContractResponse = await tonweb.provider.call2(STAKING_CONTRACT_ADDRESS, 'get_pool_full_data');
const stakingJettonMinterAddress = stakingContractResponse[STAKING_JETTON_MINTER_ADDRESS_INDEX]?.beginParse().loadAddress();
if (!stakingJettonMinterAddress) throw new Error("stakingJetton minter address is not found.");
const queryAddress = new TonWeb.utils.Address(address);
const addressCell = new TonWeb.boc.Cell();
addressCell.bits.writeAddress(queryAddress);
const serializedQueryAddress = TonWeb.utils.bytesToBase64(await addressCell.toBoc(false));
const walletResponse = await tonweb.provider.call2(stakingJettonMinterAddress.toString(), 'get_wallet_address', [['tvm.Slice', serializedQueryAddress]]);
if (!walletResponse) throw new Error("stakingJetton wallet is not found.");
const stakingJettonWalletAddress = walletResponse.beginParse().loadAddress()
return stakingJettonWalletAddress.toString(true, true, true, IS_TESTNET)
} catch (error) {
throw error;
}
};
/**
* @param address {string}
*/
const setAddress = (address) => {
currentAddress = address;
vestingWallet = null;
stakingJettonWalletAddress = null;
$('.address_header').innerText = 'Address';
$('#address_info').innerText = '';
showScreen('addressScreen');
$('#address_userAddress').innerHTML = `<a href="${scanLink(address)}" target="_blank">${formatAddress(address)}</a>`;
toggle($('#wallet_createButton'), false);
toggle($('#vesting_container'), false);
toggle($('#address_loading'), true);
$('#header_input').value = '';
$('.main_input').value = '';
clearTimeout(reloadTimeoutId);
const loadAddress = async () => {
let walletInfo;
try {
walletInfo = await tonweb.provider.getWalletInfo(address);
} catch (e) {
console.error(e);
}
if (address !== currentAddress) return;
console.log(walletInfo);
try {
stakingJettonWalletAddress = await getStakingJettonWalletAddress(address);
} catch (e) {
console.error("Error fetching stakingJetton wallet:", e);
}
if (!walletInfo) {
toggle($('#address_loading'), false);
$('#address_info').innerText = `Can't get this address. Try again..`;
reloadTimeoutId = setTimeout(loadAddress, 5 * 1000); // reload after 5 seconds
} else if (walletInfo.account_state === 'uninitialized') {
toggle($('#address_loading'), false);
$('#address_info').innerText = 'Address uninitialized yet';
reloadTimeoutId = setTimeout(loadAddress, 5 * 1000); // reload after 5 seconds
} else if (walletInfo.wallet === true) {
toggle($('#address_loading'), false);
$('.address_header').innerText = 'Wallet';
toggle($('#wallet_createButton'), true);
$('#address_info').innerHTML = 'This is a normal wallet.<br>' +
'You can create a vesting for this user.';
} else {
const addressInfo = await tonweb.provider.getAddressInfo(address);
if (address !== currentAddress) return;
/** @type {string} */
const code098hash = '28030eb57f905fda5cbdc1b08955faf53065759063b958f36c6f861b2bcfc7be';
/** @type {string} */
const code099hash = '320ae22be268161d685a7900de30dfec797b797ec9801069ac5b7850750254a2';
/**
* @param codeHexOrBytes {string | Uint8Array}
* @return {Promise<string>} hash hex
*/
const getCodeHash = async (codeHexOrBytes) => {
/** @type {Cell} */
const codeCell = TonWeb.boc.Cell.oneFromBoc(codeHexOrBytes);
return TonWeb.utils.bytesToHex(await codeCell.hash());
}
const VestingWalletClass = TonWeb.LockupWallets.VestingWalletV1;
/** @type {string} */
const vestingWalletCodeHash = await getCodeHash(VestingWalletClass.codeHex);
/** @type {string} */
const addressInfoCodeHash = await getCodeHash(TonWeb.utils.base64ToBytes(addressInfo.code));
if (addressInfoCodeHash === code098hash) {
console.log('Its not production vesting-v0.98 smart contract. Please use vesting-v1.00');
}
if (addressInfoCodeHash === code099hash) {
console.log('Its not production vesting-v0.99 smart contract. Please use vesting-v1.00');
}
if (vestingWalletCodeHash === addressInfoCodeHash) {
const newVestingWallet = new VestingWalletClass(tonweb.provider, {
address: new TonWeb.utils.Address(address)
});
/** @type {BN} */
const lockedAmount = await newVestingWallet.getLockedAmount(Math.floor(Date.now() / 1000));
const vestingData = await newVestingWallet.getVestingData();
console.log(vestingData);
vestingData.index = 0;
vestingData.address = address;
vestingData.balance = new BN(addressInfo.balance);
vestingData.lockedAmount = lockedAmount;
vestingData.ownerAddress = vestingData.ownerAddress.toString(true, true, false, IS_TESTNET);
vestingData.vestingSenderAddress = vestingData.vestingSenderAddress.toString(true, true, false, IS_TESTNET);
const whitelist = await newVestingWallet.getWhitelist();
vestingData.whitelist = [];
/**
* @param address {string}
* @return {Promise<boolean>}
*/
const checkIsWallet = async (address) => {
const value = localStorage.getItem('format_' + address);
if (value === 'true' || value === 'false') {
return value === 'true';
}
const walletInfoRaw = await fetch(TONCENTER_INDEX_URL + 'wallet?address=' + address, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-API-Key': TONCENTER_API_KEY
},
});
const walletInfo = await walletInfoRaw.json();
const isWallet = (walletInfo.wallet_type && walletInfo.wallet_type.startsWith('wallet')) || (walletInfo.status === 'uninit');
localStorage.setItem('format_' + address, isWallet.toString());
return isWallet;
}
if (stakingJettonWalletAddress) {
const unstakeStakingJettonBalanceEl = $('#unstakePopup_stakingJettonWalletBalance');
const vestingStakingJettonBalanceEl = $('#vesting_stakingJettonBalance');
const jettonAddressButton = $('#whitelist_useTonstakersJettonButton')
if (jettonAddressButton) {
jettonAddressButton.disabled = false;
}
try {
const stakingJettonWallet = new TonWeb.token.jetton.JettonWallet(tonweb.provider, { address: stakingJettonWalletAddress });
const stakingJettonWalletData = await stakingJettonWallet.getData();
vestingData.jettonBalance = stakingJettonWalletData.balance;
if (unstakeStakingJettonBalanceEl) {
unstakeStakingJettonBalanceEl.innerHTML =
`Available: ${bold(formatAmount(vestingData.jettonBalance, STAKE_TOKEN_NAME))}<br/>
Additionally, ${UNSTAKE_FEE} TON will be sent from the vesting wallet to settle fees`;
}
} catch (e) {
// Can't get stakingJetton wallet data
}
}
for (const address of whitelist) {
const isWallet = await checkIsWallet(address.toString(false));
vestingData.whitelist.push(address.toString(true, true, !isWallet, IS_TESTNET));
}
if (address !== currentAddress) return;
hidePopup(); // close probably opened popups related to old vestingWallet
vestingWallet = newVestingWallet;
$('#address_info').innerText = '';
toggle($('#address_loading'), false);
$('.address_header').innerText = 'Vesting';
toggle($('#vesting_container'), true);
$('#vesting_container').innerHTML = '';
$('#vesting_container').appendChild(renderVestingWallet(vestingData));
} else {
toggle($('#address_loading'), false);
$('#address_info').innerText = 'Unknown smart contract on this address';
toggle($('#wallet_createButton'), IS_CUSTOM_OWNERS);
}
}
}
loadAddress();
}
/**
* @param e {KeyboardEvent}
*/
const onAddressInput = e => {
if (e.key === 'Enter') {
let addressString = e.target.value.trim();
if (!TonWeb.utils.Address.isValid(addressString)) {
alert('Invalid address');
} else {
window.history.pushState(addressString, 'TON Vesting - ' + addressString, '#' + addressString);
setAddress(addressString);
}
}
}
$('.main_input').addEventListener('keydown', onAddressInput);
$('#header_input').addEventListener('keydown', onAddressInput);
const processUrl = () => {
clear();
const addressFromUrl = window.location.hash.substring(1);
if (addressFromUrl) {
if (TonWeb.utils.Address.isValid(addressFromUrl)) {
setAddress(addressFromUrl);
} else {
showScreen('mainScreen')
}
} else {
showScreen('mainScreen')
}
}
processUrl();
window.onpopstate = () => processUrl();
// TONCONNECT CONNECT/DISCONNECT
/**
* @param account {{address: string, publicKey: string}}
*/
const onWalletConnected = account => {
myAddress = new TonWeb.utils.Address(account.address).toString(true, true, false, IS_TESTNET);
console.log('my address ', myAddress);
if (currentScreen !== 'mainScreen') {
setAddress(currentAddress); // refresh
}
hidePopup();
};
const onWalletDisconnected = () => {
if (currentScreen !== 'mainScreen') {
setAddress(currentAddress); // refresh
}
hidePopup();
myAddress = null;
}
// WALLET SCREEN
$('#wallet_createButton').addEventListener('click', async (event) => {
if (!tonConnectUI.connected || !myAddress) {
alert('Connect wallet first');
return;
}
const newCreateState = {
myAddress,
currentAddress
};
showScreen('loadingScreen');
/** @type {BN} */
let publicKey;
try {
publicKey = await tonweb.provider.call2(currentAddress, 'get_public_key');
} catch (e) {
console.error(e);
if (IS_CUSTOM_OWNERS) {
publicKey = new BN(0);
}
}
if (!publicKey) {
alert('Cant get publicKey of target wallet');
showScreen('addressScreen');
return;
}
if (currentScreen !== 'loadingScreen' || myAddress !== newCreateState.myAddress || currentAddress !== newCreateState.currentAddress) {
return;
}
userAddress = currentAddress;
userPublicKey = publicKey.toString(16);
if (userPublicKey.length % 2 !== 0) userPublicKey = '0' + userPublicKey;
console.log('user address ', userAddress);
console.log('user key ', userPublicKey);
renderCreateScreen();
showScreen('createScreen');
});
// VESTING SCREEN
/**
* @param vestingWalletInfo {{index: number, address: string, balance: BN, lockedAmount: BN, ownerAddress: string, vestingSenderAddress: string, whitelist: string[], vestingStartTime: number, vestingTotalDuration: number, unlockPeriod: number, cliffDuration: number, vestingTotalAmount: BN}}
* @return {HTMLDivElement}
*/
const renderVestingWallet = (vestingWalletInfo) => {
/** @type {BN} */
let liquidAmount = vestingWalletInfo.balance.sub(vestingWalletInfo.lockedAmount);
if (liquidAmount.lt(new BN(0))) liquidAmount = new BN(0);
/** @type {BN} */
let stakingAvailableAmount = vestingWalletInfo.balance.sub(toNano(STAKING_FEE_RES));
if (stakingAvailableAmount.lt(new BN(0))) stakingAvailableAmount = new BN(0);
/** @type {string} */
const unlockString = vestingWalletInfo.unlockPeriod === vestingWalletInfo.vestingTotalDuration ? '-' :
`Every ${formatPeriod(vestingWalletInfo.unlockPeriod)} ${vestingWalletInfo.cliffDuration > 0 ? 'after cliff period' : ''}`;
/** @type {number} */
const index = vestingWalletInfo.index;
/** @type {string[]} */
const whitelist = [vestingWalletInfo.vestingSenderAddress].concat(vestingWalletInfo.whitelist);
/** @type {boolean} */
const isSender = myAddress === vestingWalletInfo.vestingSenderAddress;
/** @type {boolean} */
const isOwner = myAddress === vestingWalletInfo.ownerAddress;
/** @type {boolean} */
const isStakingContractWhitelisted = vestingWalletInfo.whitelist.includes(STAKING_CONTRACT_ADDRESS);
const div = document.createElement('div');
div.innerHTML =
`
<div class="vesting_panel">
${isSender ? `<div class="badge panel-badge badge-blue">You are sender</div>` : ``}
${isOwner ? `<div class="badge panel-badge badge-blue">You are owner</div>` : ``}
<div class="vesting_key">
Vesting for user:
</div>
<div class="vesting_value">
<a href="${scanLink(vestingWalletInfo.ownerAddress)}" target="_blank" class="address vesting_address">${formatAddress(vestingWalletInfo.ownerAddress)}</a>
</div>
<div class="vesting_key">
Current Balance: <div class="vesting_hint">i<div class="vesting_hint_body">The current balance of the vesting address.</div></div>
</div>
<div class="vesting_value">
${formatAmount(vestingWalletInfo.balance)}
${vestingWalletInfo.jettonBalance ? `<div id="vesting_stakingJettonBalance">${formatAmount(vestingWalletInfo.jettonBalance, STAKE_TOKEN_NAME)}</div>` : ''}
</div>
<div class="vesting_key">
Liquid: <div class="vesting_hint">i<div class="vesting_hint_body">The owner may transfer that amount from the vesting address.</div></div>
</div>
<div class="vesting_value">
${formatAmount(liquidAmount)}
</div>
<div class="vesting_key">
Unvested: <div class="vesting_hint">i<div class="vesting_hint_body">This amount is subject to restriction on transfer from the vesting address. The owner may transfer that amount only to whitelisted addresses.</div></div>
</div>
<div class="vesting_value strong">
${formatAmount(BN.min(vestingWalletInfo.lockedAmount, vestingWalletInfo.balance))}
</div>
<div class="vesting_key">
Total Vesting Amount: <div class="vesting_hint">i<div class="vesting_hint_body">Total amount to be vested during the vesting period according to the initial contract parameters. The actual balance may be more or less than this amount.</div></div>
</div>
<div class="vesting_value">
${formatAmount(vestingWalletInfo.vestingTotalAmount)}
</div>
<div class="vesting_key">
Vesting Start Date: <div class="vesting_hint">i<div class="vesting_hint_body">The date-time when the vesting starts. Before that time coins will not be vested.</div></div>
</div>
<div class="vesting_value">
${formatDateTime(vestingWalletInfo.vestingStartTime)}
</div>
<div class="vesting_key">
Vesting Duration: <div class="vesting_hint">i<div class="vesting_hint_body">The total duration of the vesting. On that date all coins will be vested.</div></div>
</div>
<div class="vesting_value">
${formatPeriod(vestingWalletInfo.vestingTotalDuration)}
</div>
<div class="vesting_key">
Cliff Duration: <div class="vesting_hint">i<div class="vesting_hint_body">During this period vesting will be accumulated but coins won't be released. At expiration of the cliff all accumulated coins will be vested all at once.</div></div>
</div>
<div class="vesting_value">
${vestingWalletInfo.cliffDuration === 0 ? 'No cliff' : formatPeriod(vestingWalletInfo.cliffDuration)}
</div>
<div class="vesting_key">
Unlock Period: <div class="vesting_hint">i<div class="vesting_hint_body">Granularity of the vesting calculation.</div></div>
</div>
<div class="vesting_value strong">
${unlockString}
</div>
<div class="vesting_key">
Vested Amount: <div class="vesting_hint">i<div class="vesting_hint_body">The amount that should be vested by now from the initially set Total Vesting Amount.</div></div>
</div>
<div class="vesting_value">
${formatAmount(vestingWalletInfo.vestingTotalAmount.sub(vestingWalletInfo.lockedAmount))}
</div>
<div class="vesting_key">
Unvested Amount: <div class="vesting_hint">i<div class="vesting_hint_body">The amount that should stay restricted by now from the initially set Total Vesting Amount.</div></div>
</div>
<div class="vesting_value strong">
${formatAmount(vestingWalletInfo.lockedAmount)}
</div>