-
Notifications
You must be signed in to change notification settings - Fork 76
/
index.html
1448 lines (1195 loc) · 48.2 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>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no"/>
<link rel="shortcut icon" type="image/png" href="favicon.png">
<link rel="preconnect" href="https://fonts.googleapis.com">
<title>Inscribe the planet</title>
<style>
* {
box-sizing: border-box;
font-size: 1.15rem;
font-family: monospace;
background-color: black;
color: white;
}
html {
max-width: 70ch;
padding: 3rem 1rem;
margin: auto;
line-height: 1.25;
}
ul li a{
text-decoration: none !important;
}
a.active:before
{
content : '['
}
a.active:after
{
content : ']'
}
h1 {
font-size: 2rem;
}
h2 {
font-size: 1.5rem;
}
label
{
display: block;
margin-bottom: 10px;
}
input {
line-height: 1.25;
width: 100%;
height: 1.8rem;
font-size: 1.15rem;
border: 1px solid white;
margin-bottom: 10px;
}
.black-bg{
display:none;
width:100%;
position:fixed;
top:0;
left:0;
background-color:black;
opacity:.5;
width:100vw;
height:100vh;
}
.modal {
display: none;
position: fixed;
box-sizing: border-box;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100%;
max-width: 560px;
max-height: 100vh;
background-color: white;
padding: 20px;
color: black;
text-align: center;
border-radius: 25px;
border: 2px solid var(--primary-color);
}
.modal-content {
overflow-y: auto;
max-height: 85vh;
background-color: white;
color: black;
text-align: center;
border: transparent;
}
.display {
display: none;
border: 1px solid white;
padding: 1rem;
border-radius: 1rem;
word-wrap: break-word;
text-align: center;
position: relative;
}
.display p {
text-align: left;
}
.checking_mempool, .checking_mempool span {
color: lightgreen;
}
.feerates {
display: flex;
justify-content: space-around;
}
.fee {
width: 100%;
max-width: 6rem;
margin: 0px 0.5rem;
text-align: center;
cursor: pointer;
}
.fee .num {
background-color: grey;
border: 1px solid white;
padding: .3rem;
}
.minfee .num {
background-color: green;
}
.safari_warning {
display: none;
}
.registration, .upload_file {
text-decoration: underline;
cursor: pointer;
}
.dns_form, .dns_checker, .timer, .brc20_deploy_form, .brc20_mint_form {
display: none;
}
</style>
<script src="https://bundle.run/[email protected]"></script>
<script> const buf = buffer </script>
<script src="bton.min.js"></script>
<script> const BTON = window.bton </script>
<script src="https://unpkg.com/@cmdcode/[email protected]"></script>
<script src="https://bundle.run/[email protected]"></script>
<script src="https://supertestnet.github.io/bitcoin-chess/js/qrcode.js"></script>
<script>
let $ = document.querySelector.bind(document);
let $$ = document.querySelectorAll.bind(document);
let url_params = new URLSearchParams(window.location.search);
let url_keys = url_params.keys();
let $_GET = {}
for (let key of url_keys) $_GET[key] = url_params.get(key);
</script>
<script>
function encodeBase64(file) {
return new Promise(function (resolve, reject) {
let imgReader = new FileReader();
imgReader.onloadend = function () {
resolve(imgReader.result.toString());
}
imgReader.readAsDataURL(file);
});
}
function base64ToHex(str) {
const raw = atob(str);
let result = '';
for (let i = 0; i < raw.length; i++) {
const hex = raw.charCodeAt(i).toString(16);
result += (hex.length === 2 ? hex : '0' + hex);
}
return result.toLowerCase();
}
function hexToBytes(hex) {
return Uint8Array.from(hex.match(/.{1,2}/g).map((byte) => parseInt(byte, 16)));
}
function bytesToHex(bytes) {
return bytes.reduce((str, byte) => str + byte.toString(16).padStart(2, "0"), "");
}
function textToHex(text) {
var encoder = new TextEncoder().encode(text);
return [...new Uint8Array(encoder)]
.map(x => x.toString(16).padStart(2, "0"))
.join("");
}
function createQR(content) {
let dataUriPngImage = document.createElement("img"),
s = QRCode.generatePNG(content, {
ecclevel: "M",
format: "html",
fillcolor: "#FFFFFF",
textcolor: "#000000",
margin: 4,
modulesize: 8,
});
dataUriPngImage.src = s;
dataUriPngImage.id = "qr_code";
return dataUriPngImage;
}
async function getBitcoinPriceFromCoinbase() {
let data = await getData("https://api.coinbase.com/v2/prices/BTC-USD/spot");
if ( !isValidJson( data ) ) return 0;
let json = JSON.parse(data);
let price = json["data"]["amount"];
return price;
}
async function getBitcoinPriceFromKraken() {
let data = await getData("https://api.kraken.com/0/public/Ticker?pair=XBTUSD");
if ( !isValidJson( data ) ) return 0;
let json = JSON.parse(data);
let price = json["result"]["XXBTZUSD"]["a"][0];
return price;
}
async function getBitcoinPriceFromCoindesk() {
let data = await getData("https://api.coindesk.com/v1/bpi/currentprice.json");
if ( !isValidJson( data ) ) return 0;
let json = JSON.parse(data);
let price = json["bpi"]["USD"]["rate_float"];
return price;
}
async function getBitcoinPriceFromGemini() {
let data = await getData("https://api.gemini.com/v2/ticker/BTCUSD");
if ( !isValidJson( data ) ) return 0;
let json = JSON.parse(data);
let price = json["bid"];
return price;
}
async function getBitcoinPriceFromBybit() {
let data = await getData("https://api-testnet.bybit.com/derivatives/v3/public/order-book/L2?category=linear&symbol=BTCUSDT");
if ( !isValidJson( data ) ) return 0;
let json = JSON.parse(data);
let price = json["result"]["b"][0][0];
return price;
}
async function getBitcoinPrice() {
let prices = [];
let cbprice = await getBitcoinPriceFromCoinbase();
let kprice = await getBitcoinPriceFromKraken();
let cdprice = await getBitcoinPriceFromCoindesk();
let gprice = await getBitcoinPriceFromGemini();
let bprice = await getBitcoinPriceFromBybit();
prices.push(Number(cbprice), Number(kprice), Number(cdprice), Number(gprice), Number(bprice));
prices.sort();
return prices[2];
}
</script>
</head>
<body>
<h1>Welcome to the online inscriber</h1>
<h2 class="safari_warning">This tool may not work in safari browser. If you are using that, consider switching.</h2>
<div id="setup">
<div class="mb-3">
<label for="taproot_address">Receiving address <span class="type_of_address">(taproot)</span></label>
<input id="taproot_address" class="address"
placeholder="Enter a taproot address from an ordinals wallet">
</div>
<p>Please choose what you want to inscribe:</p>
<ul>
<li>
<a id="upload_file_nav" class="upload_file active" href="javascript:void(0);">files</a>
</li>
<li>
<a id="registration_nav" class="registration" href="javascript:void(0);">.sats domains</a>
</li>
<li>
<a id="brc20_mint_nav" class="brc20_mint" href="javascript:void(0);">brc-20 mint</a>
</li>
<li class="nav-item">
<a id="brc20_deploy_nav" class="brc20_deploy" href="javascript:void(0);">brc-20 deploy</a>
</li>
</ul>
<form id="app-form">
<div class="file_form">
<input
accept=".json,
.pdf,
.asc,
.yaml,
.yml,
.flac,
.mp3,
.wav,
.apng,
.avif,
.gif,
.jpg,
.jpeg,
.png,
.svg,
.webp,
.glb,
.stl,
.html,
.txt,
.mp4,
.webm
" type="file" class="form" multiple>
<button style="margin-top: 15px;" id="bytes_checker" type="button" class="btn btn-outline-primary mb-3">
Check if file(s) are inscribed already
</button>
</div>
<div class="dns_form">
<textarea class="dns" style="width: 100%; height: 250px;"
placeholder="One domain per line. Example: ordi.sats btc.sats"></textarea>
</div>
<div class="brc20_mint_form">
<div class="mb-3">
<label for="brc20-mint-ticker">Ticker</label>
<input id="brc20-mint-ticker" type="text" maxlength="4" value=""
placeholder="e.g. ordi"/>
</div>
<div class="mb-3">
<label for="brc20-mint-amount">Amount</label>
<input id="brc20-mint-amount" type="text" value="" placeholder="e.g. 1000"/>
</div>
<div class="mb-3">
<label for="brc20-mint-repeat">Repeat</label>
<input id="brc20-mint-repeat" type="text" value="1"
placeholder="e.g. 10 to mint ten times"/>
</div>
</div>
<div class="brc20_deploy_form">
<div class="mb-3">
<label for="brc20-deploy-ticker">Ticker</label>
<input id="brc20-deploy-ticker" type="text" maxlength="4" value=""
placeholder="e.g. ordi"/>
</div>
<div class="mb-3">
<label for="brc20-deploy-max">Supply</label>
<input id="brc20-deploy-max" type="text" value="" placeholder="e.g. 21000000"/>
</div>
<div class="mb-3">
<label for="brc20-deploy-lim">Limit per mint</label>
<input id="brc20-deploy-lim" type="text" value="" placeholder="e.g. 1000"/>
</div>
</div>
<button class="dns_checker btn btn-outline-primary mt-3 mb-3" type="button">Check availability</button>
<span class="timer">61</span>
<p>Select a feerate (sats/vB)</p>
<div class="feerates">
<div class="fee minfee">
<div style="color: white;" class="num rounded">...</div>
<div class="name">Min</div>
</div>
<div class="fee midfee">
<div style="color: white;" class="num rounded">...</div>
<div class="name">Mid</div>
</div>
<div class="fee maxfee">
<div style="color: white;" class="num rounded">...</div>
<div class="name">Max</div>
</div>
</div>
<div id="sliderange">
<label for="sats_range">sats/vB: <span id="sats_per_byte">1</span></label>
<input class="form-range" id="sats_range" type="range" min="1" max="100" value="1">
</div>
<script>
var slider = document.getElementById("sats_range");
var output = document.getElementById("sats_per_byte");
output.innerHTML = slider.value;
slider.oninput = function () {
output.innerHTML = this.value;
sessionStorage["feerate"] = this.value;
$$('.fee .num').forEach(function (item) {
item.style.backgroundColor = "grey";
});
}
</script>
</form>
<div class="mb-3">
<label for="padding">Sats in inscription (padding)</label>
<input style="width: 25%" id="padding" type="text" value=""/>
</div>
</div>
<div style="margin-top: 20px; margin-bottom: 20px;">
<button class="submit btn btn-primary">Submit</button>
<button style="display:none;" class="startover btn btn-primary">Reset</button>
</div>
<div class="display"></div>
<div style="display: none;" class="file"></div>
<script>
// adjust for your needs
let padding = 10000; // default padding as of ord native wallet
let encodedAddressPrefix = 'bc'; // mainnet: 'bc', signet/testnet: 'tb'
let mempoolNetwork = ''; // mainnet: '', 'signet/', 'testnet/'
// no changes from here
const privkey = bytesToHex(cryptoUtils.Noble.utils.randomPrivateKey());
let pushing = false;
let files = [];
sessionStorage.clear();
window.onload = function () {
$('#padding').value = padding;
$('.upload_file').onclick = showUploader;
$('.registration').onclick = showRegister;
$('.brc20_mint').onclick = showBrc20Mint;
$('.brc20_deploy').onclick = showBrc20Deploy;
};
function showRegister() {
$('#padding').value = '546';
padding = '546';
files = [];
$('#app-form').reset();
$('.brc20_deploy_form').style.display = "none";
$('.brc20_mint_form').style.display = "none";
$('.file_form').style.display = "none";
$('.dns_form').style.display = "block";
$('.dns_checker').style.display = "inline";
$('.dns').value = "";
document.getElementById('brc20_mint_nav').classList.remove('active');
document.getElementById('brc20_deploy_nav').classList.remove('active');
document.getElementById('upload_file_nav').classList.remove('active');
document.getElementById('registration_nav').classList.add('active');
}
function showUploader() {
$('#padding').value = '10000';
padding = '10000';
files = [];
$('#app-form').reset();
$('.brc20_deploy_form').style.display = "none";
$('.brc20_mint_form').style.display = "none";
$('.file_form').style.display = "block";
$('.dns_form').style.display = "none";
$('.dns_checker').style.display = "none";
document.getElementById('brc20_mint_nav').classList.remove('active');
document.getElementById('brc20_deploy_nav').classList.remove('active');
document.getElementById('upload_file_nav').classList.add('active');
document.getElementById('registration_nav').classList.remove('active');
}
function showBrc20Deploy() {
$('#padding').value = '546';
padding = '546';
files = [];
$('#app-form').reset();
$('.brc20_deploy_form').style.display = "block";
$('.brc20_mint_form').style.display = "none";
$('.file_form').style.display = "none";
$('.dns_form').style.display = "none";
$('.dns_checker').style.display = "none";
$('.registration').onclick = showRegister;
document.getElementById('brc20_mint_nav').classList.remove('active');
document.getElementById('brc20_deploy_nav').classList.add('active');
document.getElementById('upload_file_nav').classList.remove('active');
document.getElementById('registration_nav').classList.remove('active');
}
function showBrc20Mint() {
$('#padding').value = '546';
padding = '546';
files = [];
$('#app-form').reset();
$('.brc20_deploy_form').style.display = "none";
$('.brc20_mint_form').style.display = "block";
$('.file_form').style.display = "none";
$('.dns_form').style.display = "none";
$('.dns_checker').style.display = "none";
$('.registration').onclick = showRegister;
document.getElementById('brc20_mint_nav').classList.add('active');
document.getElementById('brc20_deploy_nav').classList.remove('active');
document.getElementById('upload_file_nav').classList.remove('active');
document.getElementById('registration_nav').classList.remove('active');
}
showUploader();
$('.form').addEventListener("change", async function () {
files = [];
let limit_reached = 0;
for (let i = 0; i < this.files.length; i++) {
let b64;
let mimetype = this.files[i].type;
if (mimetype.includes("text/plain")) {
mimetype += ";charset=utf-8";
}
if (this.files[i].size >= 350000) {
limit_reached += 1;
} else {
b64 = await encodeBase64(this.files[i]);
let base64 = b64.substring(b64.indexOf("base64,") + 7);
let hex = base64ToHex(base64);
//console.log( "hex:", hex );
//console.log( "bytes:", hexToBytes( hex ) );
let sha256 = await fileToSha256Hex(this.files[i]);
files.push({name: this.files[i].name, hex: hex, mimetype: mimetype, sha256: sha256.replace('0x', '')});
}
}
if (limit_reached != 0) {
alert(limit_reached + " of your desired inscriptions exceed(s) the maximum of 350kb.")
}
console.log(files);
});
$('.startover').addEventListener("click", async function () {
location.reload();
});
$('.submit').addEventListener("click", async function () {
if (!isValidAddress()) {
alert('Invalid taproot address.');
return;
}
let mempool_success = await probeAddress($('.address').value, true);
if(!mempool_success)
{
alert('Could not establish a connection to Mempool.space. Most likely you got rate limited. Please wait a few minutes before you try inscribing.');
return;
}
if ($('.brc20_deploy_form').style.display != "none") {
files = [];
let deploy = '{ \n' +
' "p": "brc-20",\n' +
' "op": "deploy",\n' +
' "tick": "",\n' +
' "max": "",\n' +
' "lim": ""\n' +
'}';
if (isNaN(parseInt($('#brc20-deploy-max').value))) {
alert('Invalid supply.');
return;
}
if (isNaN(parseInt($('#brc20-deploy-lim').value))) {
alert('Invalid limit.');
return;
}
if ($('#brc20-deploy-ticker').value == '' || $('#brc20-deploy-ticker').value.length != 4) {
alert('Invalid ticker length. Must be 4 characters.');
return;
}
deploy = JSON.parse(deploy);
deploy.tick = $('#brc20-deploy-ticker').value;
deploy.max = $('#brc20-deploy-max').value;
deploy.lim = $('#brc20-deploy-lim').value;
let mimetype = "text/plain;charset=utf-8";
files.push({name: deploy.tick, hex: textToHex(JSON.stringify(deploy)), mimetype: mimetype, sha256: ''});
console.log(files);
}
if ($('.brc20_mint_form').style.display != "none") {
files = [];
let mint = '{ \n' +
' "p": "brc-20",\n' +
' "op": "mint",\n' +
' "tick": "",\n' +
' "amt": ""\n' +
'}';
if (isNaN(parseInt($('#brc20-mint-amount').value))) {
alert('Invalid mint amount.');
return;
}
if ($('#brc20-mint-ticker').value == '' || $('#brc20-mint-ticker').value.length != 4) {
alert('Invalid ticker length. Must be 4 characters.');
return;
}
mint = JSON.parse(mint);
mint.tick = $('#brc20-mint-ticker').value;
mint.amt = $('#brc20-mint-amount').value;
let repeat = parseInt($('#brc20-mint-repeat').value);
if (isNaN(repeat)) {
alert('Invalid repeat amount.');
return;
}
for (let i = 0; i < repeat; i++) {
let mimetype = "text/plain;charset=utf-8";
files.push({
name: mint.tick + '_' + i,
hex: textToHex(JSON.stringify(mint)),
mimetype: mimetype,
sha256: ''
});
}
console.log(files);
}
if ($('.dns_form').style.display != "none") {
files = [];
let sats_domains = $('.dns').value.split("\n");
let sats_domains_cleaned = [];
for (let sats_domain in sats_domains) {
let domain = sats_domains[sats_domain].trim();
if (domain == '' || sats_domains_cleaned.includes(domain)) {
continue;
}
sats_domains_cleaned.push(domain);
}
for (let sats_domain in sats_domains_cleaned) {
let mimetype = "text/plain;charset=utf-8";
let domain = {"p": "sns", "op": "reg", "name": sats_domains_cleaned[sats_domain].trim()};
files.push({
name: sats_domains_cleaned[sats_domain].trim(),
hex: textToHex(JSON.stringify(domain)),
mimetype: mimetype,
sha256: ''
});
console.log(domain);
}
}
if (files.length == 0) {
alert('Nothing to inscribe. Please upload some files or use one of the additional options.');
return;
}
if (files.length >= 26) {
alert('Max. batch size is 25. Please remove some of your inscriptions and split them into many batches.');
return;
}
let _padding = parseInt($('#padding').value);
if (!isNaN(_padding) && _padding <= Number.MAX_SAFE_INTEGER && _padding >= 1) {
padding = _padding;
} else {
alert('Invalid padding. Please enter a sats amount for each inscription.');
return;
}
alert("AFTER YOU SEND YOUR SATS DO _NOT_ CLOSE THE BROWSER TAB OR YOUR FUNDS MAY GET LOST.\n\nDO ALSO _NOT_ TRY TO BYPASS THE 25 BATCH LIMIT BY OPENING MULTIPLE TABS.\n\nTHIS IS A SELF-CUSTODIAL INSCRIBER NOT A CENTRALIZED ONE.\n\nCLICK OK AND ONLY PROCEED IF YOU UNDERSTAND THIS.");
$('.submit').style.display = "none";
$('.startover').style.display = "inline-block";
const KeyPair = cryptoUtils.KeyPair;
const seckey = new KeyPair(privkey);
const pubkey = seckey.pub.rawX;
const ec = new TextEncoder();
const init_script = [
pubkey,
'OP_CHECKSIG'
];
const init_leaf = await BTON.Tap.getLeaf(BTON.Script.encode(init_script));
const [init_tapkey] = await BTON.Tap.getPubkey(pubkey, [init_leaf]);
const init_cblock = await BTON.Tap.getPath(pubkey, init_leaf);
let inscriptions = [];
let total_fee = 0;
let feerate = await getMinFeeRate();
sessionStorage["determined_feerate"] = sessionStorage["feerate"];
if (sessionStorage["feerate"]) {
feerate = Number(sessionStorage["feerate"]);
sessionStorage["determined_feerate"] = sessionStorage["feerate"];
}
let base_size = 160;
for (let i = 0; i < files.length; i++) {
const hex = files[i].hex;
const data = hexToBytes(hex);
const mimetype = ec.encode(files[i].mimetype);
const script = [
pubkey,
'OP_CHECKSIG',
'OP_0',
'OP_IF',
ec.encode('ord'),
'01',
mimetype,
'OP_0',
data,
'OP_ENDIF'
];
const leaf = await BTON.Tap.getLeaf(BTON.Script.encode(script));
const [tapkey] = await BTON.Tap.getPubkey(pubkey, [leaf]);
const cblock = await BTON.Tap.getPath(pubkey, leaf);
let inscriptionAddress = BTON.Tap.encodeAddress(tapkey, encodedAddressPrefix);
console.log('Inscription address: ', inscriptionAddress);
console.log('Tapkey:', tapkey);
let txsize = 600 + Math.floor(data.length / 4);
if(files[i].sha256 == '')
{
base_size = Math.floor(data.length / 4) * i;
txsize = 200 + Math.floor(data.length / 4);
}
console.log("TXSIZE", txsize);
let fee = feerate * txsize;
total_fee += fee;
inscriptions.push(
{
leaf: leaf,
tapkey: tapkey,
cblock: cblock,
inscriptionAddress: inscriptionAddress,
txsize: txsize,
fee: fee,
script: script
}
);
}
let fundingAddress = BTON.Tap.encodeAddress(init_tapkey, encodedAddressPrefix);
console.log('Funding address: ', fundingAddress);
let toAddress = $('.address').value;
console.log('Address that will receive the inscription:', toAddress);
let decodedToAddress = "5120" + BTON.Tap.decodeAddress(toAddress).hex;
console.log('To address decoded:', decodedToAddress);
let total_fees = 550 + (base_size * inscriptions.length) + total_fee + (padding * inscriptions.length);
let sats_price = await satsToDollars(total_fees);
sats_price = Math.floor(sats_price * 100) / 100;
let html = `<p>Please send at least <strong>${total_fees} sats</strong> ($${sats_price}) to the address below (click to copy). Once you sent the amount, do NOT close this window!</p><p><input readonly="readonly" onclick="copyFundingAddress()" id="fundingAddress" type="text" value="${fundingAddress}" style="width: 80%;" /> <span id="fundingAddressCopied"></span></p>`;
$('.display').innerHTML = html;
let qr_value = "bitcoin:" + fundingAddress + "?amount=" + satsToBitcoin(total_fees);
console.log("qr:", qr_value);
$('.display').append(createQR(qr_value));
$('.display').innerHTML += `<p class="checking_mempool">Checking the mempool<span class="dots">.</span></p>`;
$('.display').innerHTML += '<p>' + (padding * inscriptions.length) + ` sats will go to the address</p><p>${total_fee} sats will go to miners as a mining fee</p>`;
$('.display').style.display = "block";
$('#setup').style.display = "none";
await loopTilAddressReceivesMoney(fundingAddress, true);
await waitSomeSeconds(2);
let txinfo = await addressReceivedMoneyInThisTx(fundingAddress);
let txid = txinfo[0];
let vout = txinfo[1];
let amt = txinfo[2];
console.log("yay! txid:", txid, "vout:", vout, "amount:", amt);
$('.modal-content').innerHTML = '<div id="funds-msg">Funds are on the way. Please wait...</div>';
$('.modal').style.display = "block";
let outputs = [];
for (let i = 0; i < inscriptions.length; i++) {
outputs.push(
{
value: padding + inscriptions[i].fee,
scriptPubKey: '5120' + inscriptions[i].tapkey
}
);
}
const init_redeemtx = {
version: 2,
input: [{
txid: txid,
vout: vout,
prevout: {value: amt, scriptPubKey: '5120' + init_tapkey},
witness: []
}],
output: outputs,
locktime: 0
};
const init_sig = await BTON.Sig.taproot.sign(seckey.raw, init_redeemtx, 0, {extention: init_leaf});
init_redeemtx.input[0].witness = [init_sig, init_script, init_cblock];
console.dir(init_redeemtx, {depth: null});
console.log('YOUR SECKEY', seckey);
let rawtx = BTON.Tx.encode(init_redeemtx);
let _txid = await pushBTCpmt(rawtx);
console.log('Init TX', _txid);
let include_mempool = true;
async function inscribe(inscription, vout) {
// we are running into an issue with 25 child transactions for unconfirmed parents.
// so once the limit is reached, we wait for the parent tx to confirm.
await loopTilAddressReceivesMoney(inscription.inscriptionAddress, include_mempool);
await waitSomeSeconds(2);
let txinfo2 = await addressReceivedMoneyInThisTx(inscription.inscriptionAddress);
document.getElementById('modal-reset').style.display = 'block';
document.getElementById('funds-msg').style.display = 'none';
let txid2 = txinfo2[0];
let amt2 = txinfo2[2];
const redeemtx = {
version: 2,
input: [{
txid: txid2,
vout: vout,
prevout: {value: amt2, scriptPubKey: '5120' + inscription.tapkey},
witness: []
}],
output: [{
value: amt2 - inscription.fee,
scriptPubKey: decodedToAddress
}],
locktime: 0
};
const sig = await BTON.Sig.taproot.sign(seckey.raw, redeemtx, 0, {extention: inscription.leaf});
redeemtx.input[0].witness = [sig, inscription.script, inscription.cblock];
console.dir(redeemtx, {depth: null});
let rawtx2 = BTON.Tx.encode(redeemtx);
let _txid2;
// since we don't know any mempool space api rate limits, we will be careful with spamming
await isPushing();
pushing = true;
_txid2 = await pushBTCpmt( rawtx2 );
await sleep(1000);
pushing = false;
if(_txid2.includes('descendant'))
{
include_mempool = false;
inscribe(inscription, vout);
$('#descendants-warning').style.display = 'inline-block';
return;
}
try {
JSON.parse(_txid2);
let html = `<p style="background-color: white; color: black;">Error: ${_txid2}</p>`;
html += '<hr/>';
$('.modal').innerHTML += html;
} catch (e) {
let html = `<p style="background-color: white; color: black;">Inscription #${vout} transaction:</p><p style="word-wrap: break-word;"><a href="https://mempool.space/${mempoolNetwork}tx/${_txid2}" target="_blank">https://mempool.space/${mempoolNetwork}tx/${_txid2}</a></p>`;
html += `<p style="background-color: white; color: black;">Ordinals explorer (after tx confirmation):</p><p style="word-wrap: break-word;"><a href="https://ordinals.com/inscription/${_txid2}i0" target="_blank">https://ordinals.com/inscription/${_txid2}i0</a></p>`;
html += '<hr/>';
$('.modal-content').innerHTML += html;
}
$('.modal').style.display = "block";
$('.black-bg').style.display = "block";
}
for (let i = 0; i < inscriptions.length; i++) {
inscribe(inscriptions[i], i);
}
});
function arrayBufferToBuffer(ab) {
var buffer = new buf.Buffer(ab.byteLength)
var view = new Uint8Array(ab)
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i]
}
return buffer
}
function hexString(buffer) {
const byteArray = new Uint8Array(buffer)
const hexCodes = [...byteArray].map(value => {
return value.toString(16).padStart(2, '0')
})
return '0x' + hexCodes.join('')
}
async function fileToArrayBuffer(file) {
return new Promise(function (resolve, reject) {
const reader = new FileReader()
const readFile = function (event) {
const buffer = reader.result
resolve(buffer)
}
reader.addEventListener('load', readFile)
reader.readAsArrayBuffer(file)
})
}
async function bufferToSha256(buffer) {
return window.crypto.subtle.digest('SHA-256', buffer)
}
async function fileToSha256Hex(file) {
const buffer = await fileToArrayBuffer(file)
const hash = await bufferToSha256(arrayBufferToBuffer(buffer))
return hexString(hash)
}
function copyFundingAddress() {
let copyText = document.getElementById("fundingAddress");
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.clipboard.writeText(copyText.value);
document.getElementById("fundingAddressCopied").innerHTML = ' Copied!';
setTimeout(function () {