forked from sirduney/dunes-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dunes.js
executable file
·1762 lines (1460 loc) · 45.7 KB
/
dunes.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
#!/usr/bin/env node
const dogecore = require("bitcore-lib-doge");
const axios = require("axios");
const axiosRetry = require("axios-retry").default;
const cheerio = require("cheerio");
const fs = require("fs");
const dotenv = require("dotenv");
const { PrivateKey, Address, Transaction, Script, Opcode } = dogecore;
const { program } = require("commander");
const bb26 = require("base26");
const prompts = require("prompts");
const axiosRetryOptions = {
retries: 10,
retryDelay: axiosRetry.exponentialDelay,
};
axiosRetry(axios, axiosRetryOptions);
dotenv.config();
if (process.env.TESTNET == "true") {
dogecore.Networks.defaultNetwork = dogecore.Networks.testnet;
}
if (process.env.FEE_PER_KB) {
Transaction.FEE_PER_KB = parseInt(process.env.FEE_PER_KB);
} else {
Transaction.FEE_PER_KB = 100000000;
}
const WALLET_PATH = process.env.WALLET || ".wallet.json";
const IDENTIFIER = stringToCharCodes(process.env.PROTOCOL_IDENTIFIER);
const MAX_SCRIPT_ELEMENT_SIZE = 520;
class PushBytes {
constructor(bytes) {
this.bytes = Buffer.from(bytes);
}
static fromSliceUnchecked(bytes) {
return new PushBytes(bytes);
}
static fromMutSliceUnchecked(bytes) {
return new PushBytes(bytes);
}
static empty() {
return new PushBytes([]);
}
asBytes() {
return this.bytes;
}
asMutBytes() {
return this.bytes;
}
}
// Encode a u128 value to a byte array
function varIntEncode(n) {
const out = new Array(19).fill(0);
let i = 18;
out[i] = Number(BigInt(n) & 0b01111111n);
while (BigInt(n) > 0b01111111n) {
n = BigInt(n) / 128n - 1n;
i -= 1;
out[i] = Number(BigInt(n) | 0b10000000n);
}
return out.slice(i);
}
class Tag {
static Body = 0;
static Flags = 2;
static Dune = 4;
static Limit = 6;
static OffsetEnd = 8;
static Deadline = 10;
static Pointer = 12;
static HeightStart = 14;
static OffsetStart = 16;
static HeightEnd = 18;
static Cap = 20;
static Premine = 22;
static Cenotaph = 254;
static Divisibility = 1;
static Spacers = 3;
static Symbol = 5;
static Nop = 255;
static take(tag, fields) {
return fields[tag];
}
static encode(tag, value, payload) {
payload.push(varIntEncode(tag));
if (tag == Tag.Dune) payload.push(encodeToTuple(value));
else payload.push(varIntEncode(value));
}
}
class Flag {
static Etch = 0;
static Terms = 1;
static Turbo = 2;
static Cenotaph = 127;
static mask(flag) {
return BigInt(1) << BigInt(flag);
}
static take(flag, flags) {
const mask = Flag.mask(flag);
const set = (flags & mask) !== 0n;
flags &= ~mask;
return set;
}
static set(flag, flags) {
flags |= Flag.mask(flag);
}
}
// Construct the OP_RETURN dune script with encoding of given values
function constructScript(
etching = null,
pointer = undefined,
cenotaph = null,
edicts = []
) {
const payload = [];
if (etching) {
// Setting flags for etching and minting
let flags = Number(Flag.mask(Flag.Etch));
if (etching.turbo) flags |= Number(Flag.mask(Flag.Turbo));
if (etching.terms) flags |= Number(Flag.mask(Flag.Terms));
Tag.encode(Tag.Flags, flags, payload);
if (etching.dune) Tag.encode(Tag.Dune, etching.dune, payload);
if (etching.terms) {
if (etching.terms.limit)
Tag.encode(Tag.Limit, etching.terms.limit, payload);
if (etching.terms.cap) Tag.encode(Tag.Cap, etching.terms.cap, payload);
if (etching.terms.offsetStart)
Tag.encode(Tag.OffsetStart, etching.terms.offsetStart, payload);
if (etching.terms.offsetEnd)
Tag.encode(Tag.OffsetEnd, etching.terms.offsetEnd, payload);
if (etching.terms.heightStart)
Tag.encode(Tag.HeightStart, etching.terms.heightStart, payload);
if (etching.terms.heightEnd)
Tag.encode(Tag.HeightEnd, etching.terms.heightEnd, payload);
}
if (etching.divisibility !== 0)
Tag.encode(Tag.Divisibility, etching.divisibility, payload);
if (etching.spacers !== 0)
Tag.encode(Tag.Spacers, etching.spacers, payload);
if (etching.symbol) Tag.encode(Tag.Symbol, etching.symbol, payload);
if (etching.premine) Tag.encode(Tag.Premine, etching.premine, payload);
}
if (pointer !== undefined) {
Tag.encode(Tag.Pointer, pointer, payload);
}
if (cenotaph) {
Tag.encode(Tag.Cenotaph, 0, payload);
}
if (edicts && edicts.length > 0) {
payload.push(varIntEncode(Tag.Body));
const sortedEdicts = edicts.slice().sort((a, b) => {
const idA = BigInt(a.id);
const idB = BigInt(b.id);
return idA < idB ? -1 : idA > idB ? 1 : 0;
});
let id = 0;
for (const edict of sortedEdicts) {
if (typeof edict.id === "bigint")
payload.push(varIntEncode(edict.id - BigInt(id)));
else payload.push(varIntEncode(edict.id - id));
payload.push(varIntEncode(edict.amount));
payload.push(varIntEncode(edict.output));
id = edict.id;
}
}
// Create script with protocol message
let script = createScriptWithProtocolMsg();
// Flatten the nested arrays in the tuple representation
const flattenedTuple = payload.flat();
// Push payload bytes to script
for (let i = 0; i < flattenedTuple.length; i += MAX_SCRIPT_ELEMENT_SIZE) {
const chunk = flattenedTuple.slice(i, i + MAX_SCRIPT_ELEMENT_SIZE);
const push = PushBytes.fromSliceUnchecked(chunk);
script.add(Buffer.from(push.asBytes()));
}
return script;
}
class SpacedDune {
constructor(dune, spacers) {
this.dune = parseDuneFromString(dune);
this.spacers = spacers;
}
}
class Dune {
constructor(value) {
this.value = BigInt(value);
}
}
function parseDuneFromString(s) {
let x = BigInt(0);
for (let i = 0; i < s.length; i++) {
if (i > 0) {
x += BigInt(1);
}
x *= BigInt(26);
const charCode = s.charCodeAt(i);
if (charCode >= "A".charCodeAt(0) && charCode <= "Z".charCodeAt(0)) {
x += BigInt(charCode - "A".charCodeAt(0));
} else {
throw new Error(`Invalid character in dune name: ${s[i]}`);
}
}
return new Dune(x);
}
// Function to parse a string into a SpacedDune in Node.js
function spacedDunefromStr(s) {
let dune = "";
let spacers = 0;
for (const c of s) {
switch (true) {
case /[A-Z]/.test(c):
dune += c;
break;
case /[.•]/.test(c):
const flag = 1 << (dune.length - 1);
if ((spacers & flag) !== 0) {
throw new Error("double spacer");
}
spacers |= flag;
break;
default:
throw new Error("invalid character");
}
}
if (32 - Math.clz32(spacers) >= dune.length) {
throw new Error("trailing spacer");
}
return new SpacedDune(dune, spacers);
}
class Edict {
// Constructor for Edict
constructor(id, amount, output) {
this.id = id;
this.amount = amount;
this.output = output;
}
}
class Terms {
constructor(limit, cap, offsetStart, offsetEnd, heightStart, heightEnd) {
this.limit = limit !== undefined ? limit : null;
this.cap = cap !== undefined ? cap : null;
this.offsetStart = offsetStart !== undefined ? offsetStart : null;
this.offsetEnd = offsetEnd !== undefined ? offsetEnd : null;
this.heightStart = heightStart !== undefined ? heightStart : null;
this.heightEnd = heightEnd !== undefined ? heightEnd : null;
}
}
class Etching {
// Constructor for Etching
constructor(divisibility, terms, turbo, premine, dune, spacers, symbol) {
this.divisibility = divisibility;
this.terms = terms !== undefined ? terms : null;
this.turbo = turbo !== undefined ? turbo : null;
this.premine = premine !== undefined ? premine : null;
this.dune = dune;
this.spacers = spacers;
this.symbol = symbol;
}
}
function stringToCharCodes(inputString) {
const charCodes = [];
for (let i = 0; i < inputString.length; i++) {
charCodes.push(inputString.charCodeAt(i));
}
return charCodes;
}
const STEPS = [
0n,
26n,
702n,
18278n,
475254n,
12356630n,
321272406n,
8353082582n,
217180147158n,
5646683826134n,
146813779479510n,
3817158266467286n,
99246114928149462n,
2580398988131886038n,
67090373691429037014n,
1744349715977154962390n,
45353092615406029022166n,
1179180408000556754576342n,
30658690608014475618984918n,
797125955808376366093607894n,
20725274851017785518433805270n,
538857146126462423479278937046n,
14010285799288023010461252363222n,
364267430781488598271992561443798n,
9470953200318703555071806597538774n,
246244783208286292431866971536008150n,
6402364363415443603228541259936211926n,
166461473448801533683942072758341510102n,
];
const SUBSIDY_HALVING_INTERVAL_10X = 2100000n;
const FIRST_DUNE_HEIGHT = 5084000n;
const ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
function format(formatter) {
let n = BigInt(this._value);
if (n === 2n ** 128n - 1n) {
return formatter.write("BCGDENLQRQWDSLRUGSNLBTMFIJAV");
}
n += 1n;
let symbol = "";
while (n > 0n) {
symbol += ALPHABET.charAt(Number((n - 1n) % 26n));
n = (n - 1n) / 26n;
}
for (const c of symbol.split("").reverse()) {
formatter.write(c);
}
}
const formatter = {
output: "",
write(str) {
this.output += str;
return this;
},
};
function minimumAtHeight(height) {
const offset = BigInt(height) + 1n;
const INTERVAL = SUBSIDY_HALVING_INTERVAL_10X / 12n;
const start = FIRST_DUNE_HEIGHT;
const end = start + SUBSIDY_HALVING_INTERVAL_10X;
if (offset < start) {
return BigInt(STEPS[12]);
}
if (offset >= end) {
return 0n;
}
const progress = offset - start;
const length = BigInt(12 - Math.floor(Number(progress / INTERVAL)));
const endValue = BigInt(STEPS[length - 1n]);
const startValue = BigInt(STEPS[length]);
const remainder = progress % INTERVAL;
return startValue - ((startValue - endValue) * remainder) / INTERVAL;
}
function encodeToTuple(n) {
const tupleRepresentation = [];
tupleRepresentation.push(Number(n & BigInt(0b0111_1111)));
while (n > BigInt(0b0111_1111)) {
n = n / BigInt(128) - BigInt(1);
tupleRepresentation.unshift(
Number((n & BigInt(0b0111_1111)) | BigInt(0b1000_0000))
);
}
return tupleRepresentation;
}
program
.command("printDunes")
.description("Prints dunes of wallet")
.action(async () => {
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH));
const dunes = [];
const getUtxosWithDunes = [];
const CHUNK_SIZE = 10;
// Helper function to process a chunk of UTXOs
async function processChunk(utxosChunk, startIndex) {
const promises = utxosChunk.map((utxo, index) => {
console.log(
`Processing utxo number ${startIndex + index} of ${
wallet.utxos.length
}`
);
return getDunesForUtxo(`${utxo.txid}:${utxo.vout}`).then(
(dunesOnUtxo) => {
if (dunesOnUtxo.length > 0) {
getUtxosWithDunes.push(utxo);
}
return dunesOnUtxo;
}
);
});
const results = await Promise.all(promises);
for (const result of results) {
dunes.push(...result);
}
}
// Process UTXOs in chunks
for (let i = 0; i < wallet.utxos.length; i += CHUNK_SIZE) {
const chunk = wallet.utxos.slice(i, i + CHUNK_SIZE);
await processChunk(chunk, i);
}
console.log(dunes);
console.log(`Total dunes: ${dunes.length}`);
console.log(`Number of utxos with dunes: ${getUtxosWithDunes.length}`);
});
program
.command("printDuneBalance")
.argument("<dune_name>", "Dune name")
.argument("<address>", "Wallet address")
.description("Prints tick balance of wallet")
.action(async (dune_name, address) => {
const utxos = await fetchAllUnspentOutputs(address);
let balance = 0n;
const utxoHashes = utxos.map((utxo) => `${utxo.txid}:${utxo.vout}`);
const chunkSize = 10; // Size of each chunk
// Function to chunk the utxoHashes array
const chunkedUtxoHashes = [];
for (let i = 0; i < utxoHashes.length; i += chunkSize) {
chunkedUtxoHashes.push(utxoHashes.slice(i, i + chunkSize));
}
// Process each chunk
for (const chunk of chunkedUtxoHashes) {
const allDunes = await getDunesForUtxos(chunk);
for (const dunesInfo of allDunes) {
for (const singleDunesInfo of dunesInfo.dunes) {
const [name, { amount }] = singleDunesInfo;
if (name === dune_name) {
balance += BigInt(amount);
}
}
}
}
// Output the total balance
console.log(`${balance.toString()} ${dune_name}`);
});
program
.command("printSafeUtxos")
.description("Prints utxos that are safe to spend")
.action(async () => {
const safeUtxos = await getUtxosWithOutDunes();
console.log(safeUtxos);
console.log(`Number of safe utxos: ${safeUtxos.length}`);
});
const getUtxosWithOutDunes = async () => {
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH));
const walletBalanceFromOrd = await axios.get(
`${process.env.ORD}dunes/balance/${wallet.address}?show_all=true`
);
const duneOutputMap = new Map();
for (const dune of walletBalanceFromOrd.data.dunes) {
for (const balance of dune.balances) {
duneOutputMap.set(`${balance.txid}:${balance.vout}`, {
...balance,
dune: dune.dune,
});
}
}
return wallet.utxos.filter(
(utxo) => !duneOutputMap.has(`${utxo.txid}:${utxo.vout}`)
);
};
const parseDuneId = (id, claim = false) => {
// Check if Dune ID is in the expected format
const regex1 = /^\d+\:\d+$/;
const regex2 = /^\d+\/\d+$/;
if (!regex1.test(id) && !regex2.test(id))
console.log(
`Dune ID ${id} is not in the expected format e.g. 1234:1 or 1234/1`
);
// Parse the id string to get height and index
const [heightStr, indexStr] = regex1.test(id) ? id.split(":") : id.split("/");
const height = parseInt(heightStr, 10);
const index = parseInt(indexStr, 10);
// Set the bits in the id using bitwise OR
let duneId = (BigInt(height) << BigInt(16)) | BigInt(index);
// For minting set CLAIM_BIT
if (claim) {
const CLAIM_BIT = BigInt(1) << BigInt(48);
duneId |= CLAIM_BIT;
}
return duneId;
};
const createScriptWithProtocolMsg = () => {
// create an OP_RETURN script with the protocol message
return new dogecore.Script().add("OP_RETURN").add(Buffer.from(IDENTIFIER));
};
program
.command("sendDuneMulti")
.description("Send dune from the utxo to multiple receivers")
.argument("<txhash>", "Hash from tx")
.argument("<vout>", "Output from tx")
.argument("<dune>", "Dune to send")
.argument("<decimals>", "Decimals of the dune to send")
.argument("<amounts>", "Amounts to send, separated by comma")
.argument("<addresses>", "Receiver's addresses, separated by comma")
.action(async (txhash, vout, dune, decimals, amounts, addresses) => {
const amountsAsArray = amounts.split(",").map((amount) => Number(amount));
const addressesAsArray = addresses.split(",");
if (amountsAsArray.length != addressesAsArray.length) {
console.error(
`length of amounts ${amountsAsArray.length} and addresses ${addressesAsArray.length} are different`
);
process.exit(1);
}
try {
await walletSendDunes(
txhash,
vout,
dune,
decimals,
amountsAsArray,
addressesAsArray
);
} catch (error) {
console.error(error);
process.exit(1);
}
});
program
.command("sendDunesNoProtocol")
.description("Send dunes but without a protocol message")
.argument("<address>", "Receiver's address")
.argument("<utxo-amount>", "Number of dune utxos to send")
.argument("<dune>", "Dune to send")
.action(async (address, utxoAmount, dune) => {
try {
const res = await walletSendDunesNoProtocol(
address,
parseInt(utxoAmount),
dune
);
console.info(`Broadcasted transaction: ${JSON.stringify(res)}`);
} catch (error) {
console.error(error);
process.exit(1);
}
});
// sends the full balance of the specified dune
async function walletSendDunes(
txhash,
vout,
dune,
decimals,
amounts,
addresses
) {
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH));
const dune_utxo = wallet.utxos.find(
(utxo) => utxo.txid == txhash && utxo.vout == vout
);
if (!dune_utxo) {
console.error(`utxo ${txhash}:${vout} not found`);
throw new Error(`utxo ${txhash}:${vout} not found`);
}
const dunes = await getDunesForUtxo(`${dune_utxo.txid}:${dune_utxo.vout}`);
if (dunes.length == 0) throw new Error("no dunes");
// check if the dune is in the utxo and if we have enough amount
const duneOnUtxo = dunes.find((d) => d.dune == dune);
// Extract the numeric part from duneOnUtxo.amount as a BigInt
let duneOnUtxoAmount = BigInt(duneOnUtxo.amount.match(/\d+/)[0]);
// Add the decimals
duneOnUtxoAmount *= BigInt(10 ** decimals);
if (!dune) throw new Error("dune not found");
const totalAmount = amounts.reduce(
(acc, curr) => acc + BigInt(curr),
BigInt(0)
);
console.log("totalAmount", totalAmount);
if (duneOnUtxoAmount < totalAmount) throw new Error("not enough dunes");
// Define default output where the sender receives unallocated dunes
const DEFAULT_OUTPUT = 1;
// Define output offset for receivers of dunes
const OFFSET = 2;
// ask the user to confirm in the cli
const response = await prompts({
type: "confirm",
name: "value",
message: `Transferring ${totalAmount} of ${dune}. Are you sure you want to proceed?`,
initial: true,
});
if (!response.value) {
throw new Error("Transaction aborted");
}
let tx = new Transaction();
tx.from(dune_utxo);
// we get the dune
const { id, divisibility, limit } = await getDune(dune);
console.log("id", id);
// parse given id string to dune id
const duneId = parseDuneId(id);
/**
* we have an index-offset of 2
* - the first output (index 0) is the protocol message
* - the second output (index 1) is where we put the dunes which are on input utxos which shouldn't be transfered
* */
const edicts = [];
for (let i = 0; i < amounts.length; i++) {
edicts.push(new Edict(duneId, amounts[i], i + OFFSET));
}
// Create payload and parse it into an OP_RETURN script with protocol message
const script = constructScript(null, DEFAULT_OUTPUT, null, edicts);
// Add output with OP_RETURN Dune assignment script
tx.addOutput(
new dogecore.Transaction.Output({ script: script, satoshis: 0 })
);
// add one output to the sender for the dunes that are not transferred
tx.to(wallet.address, 100_000);
// the output after the protocol message will carry the dune balance if no payload is specified
for (const address of addresses) {
tx.to(address, 100_000);
}
// we fund the tx
await fund(wallet, tx);
if (tx.inputAmount < tx.outputAmount + tx.getFee()) {
throw new Error("not enough funds");
}
console.log(tx.toObject());
await broadcast(tx, true);
console.log(tx.hash);
}
async function walletSendDunesNoProtocol(address, utxoAmount, dune) {
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH));
const walletBalanceFromOrd = await axios.get(
`${process.env.ORD}dunes/balance/${wallet.address}?show_all=true`
);
const duneOutputMap = new Map();
for (const dune of walletBalanceFromOrd.data.dunes) {
for (const balance of dune.balances) {
duneOutputMap.set(balance.txid, {
...balance,
dune: dune.dune,
});
}
}
const nonDuneUtxos = wallet.utxos.filter(
(utxo) => !duneOutputMap.has(utxo.txid)
);
if (nonDuneUtxos.length === 0) {
throw new Error("no utxos without dunes found");
}
const gasUtxo = nonDuneUtxos.find((utxo) => utxo.satoshis > 100_000_000);
if (!gasUtxo) {
throw new Error(`no gas utxo found`);
}
let dunesUtxosValue = 0;
const dunesUtxos = [];
for (const utxo of wallet.utxos) {
if (dunesUtxos.length >= utxoAmount) {
break;
}
if (duneOutputMap.has(utxo.txid)) {
const duneOutput = duneOutputMap.get(utxo.txid);
if (duneOutput.dune === dune) {
dunesUtxos.push(utxo);
dunesUtxosValue += utxo.satoshis;
}
}
}
if (dunesUtxos.length < utxoAmount) {
throw new Error(`not enough dune utxos found`);
}
const response = await prompts({
type: "confirm",
name: "value",
message: `Transferring ${utxoAmount} utxos of ${dune}. Are you sure you want to proceed?`,
initial: true,
});
if (!response.value) {
throw new Error("Transaction aborted");
}
let tx = new Transaction();
tx.from(dunesUtxos);
tx.to(address, dunesUtxosValue);
await fund(wallet, tx);
return await broadcast(tx, true);
}
const _mintDune = async (id, amount, receiver) => {
console.log("Minting Dune...");
console.log(id, amount, receiver);
// Parse given id string to dune id
const duneId = parseDuneId(id, true);
if (amount == 0) {
const { id_, divisibility, limit } = await getDune(id);
amount = BigInt(limit) * BigInt(10 ** divisibility);
}
// mint dune with encoded id, amount on output 1
const edicts = [new Edict(duneId, amount, 1)];
console.log(edicts);
// Create script for given dune statements
const script = constructScript(null, undefined, null, edicts);
// getting the wallet balance
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH));
let balance = wallet.utxos.reduce((acc, curr) => acc + curr.satoshis, 0);
if (balance == 0) throw new Error("no funds");
// creating new tx
let tx = new Transaction();
// output carries the protocol message
tx.addOutput(
new dogecore.Transaction.Output({ script: script, satoshis: 0 })
);
// add receiver output holding dune amount
tx.to(receiver, 100_000);
await fund(wallet, tx);
try {
await broadcast(tx, true);
} catch (e) {
console.log(e);
}
console.log(tx.hash);
};
program
.command("mintDune")
.description("Mint a Dune")
.argument("<id>", "id of the dune in format block:index e.g. 5927764:2")
.argument(
"<amount>",
"amount to mint (0 takes the limit of the dune as amount)"
)
.argument("<receiver>", "address of the receiver")
.action(_mintDune);
function isSingleEmoji(str) {
const emojiRegex = /[\p{Emoji}]/gu;
const matches = str.match(emojiRegex);
return matches ? matches.length === 1 : false;
}
program
.command("deployOpenDune")
.description("Deploy a Dune that is open for mint")
.argument("<tick>", "Tick for the dune")
.argument("<symbol>", "symbol")
.argument("<limit>", "Max amount that can be minted in one transaction")
.argument("<divisibility>", "divisibility of the dune. Max 38")
.argument("<cap>", "Max limit that can be minted overall")
.argument("<heightStart>", "Absolute block height where minting opens")
.argument("<heightEnd>", "Absolute block height where minting closes")
.argument("<offsetStart>", "Relative block height where minting opens")
.argument(
"<offsetEnd>",
"Relative block height where minting closes (former known as term)"
)
.argument(
"<premine>",
"Amount of allocated dunes to the etcher while etching"
)
.argument(
"<turbo>",
"Marks this etching as opting into future protocol changes."
)
.argument(
"<openMint>",
"Set this to true to allow minting, taking terms (limit, cap, height, offset) as restrictions"
)
.action(
async (
tick,
symbol,
limit,
divisibility,
cap,
heightStart,
heightEnd,
offsetStart,
offsetEnd,
premine,
turbo,
openMint
) => {
console.log("Deploying open Dune...");
console.log(
tick,
symbol,
limit,
divisibility,
cap,
heightStart,
heightEnd,
offsetStart,
offsetEnd,
premine,
turbo,
openMint
);
cap = cap === "null" ? null : cap;
heightStart = heightStart === "null" ? null : heightStart;
heightEnd = heightEnd === "null" ? null : heightEnd;
offsetStart = offsetStart === "null" ? null : offsetStart;
offsetEnd = offsetEnd === "null" ? null : offsetEnd;
premine = premine === "null" ? null : premine;
turbo = turbo === "null" ? null : turbo === "true";
openMint = openMint.toLowerCase() === "true";
if (symbol) {
if (symbol.length !== 1 && !isSingleEmoji(symbol)) {
console.error(
`Error: The argument symbol should have exactly 1 character, but is '${symbol}'`
);
process.exit(1);
}
}
const spacedDune = spacedDunefromStr(tick);
const blockcount = await getblockcount();
const mininumAtCurrentHeight = minimumAtHeight(blockcount.data.result);
if (spacedDune.dune.value < mininumAtCurrentHeight) {
const minAtCurrentHeightObj = { _value: mininumAtCurrentHeight };
format.call(minAtCurrentHeightObj, formatter);
console.error("Dune characters are invalid at current height.");
process.stdout.write(
`minimum at current height: ${mininumAtCurrentHeight} possible lowest tick: ${formatter.output}\n`
);
console.log(`dune: ${tick} value: ${spacedDune.dune.value}`);
process.exit(1);
}
const terms = openMint
? new Terms(limit, cap, offsetStart, offsetEnd, heightStart, heightEnd)
: null;
const etching = new Etching(
divisibility,
terms,
turbo,
premine,
spacedDune.dune.value,
spacedDune.spacers,
symbol.codePointAt()
);
// create script for given dune statements
const script = constructScript(etching, undefined, null, null);
// getting the wallet balance
let wallet = JSON.parse(fs.readFileSync(WALLET_PATH));
let balance = wallet.utxos.reduce((acc, curr) => acc + curr.satoshis, 0);
if (balance == 0) throw new Error("no funds");
// creating new tx
let tx = new Transaction();
// first output carries the protocol message
tx.addOutput(
new dogecore.Transaction.Output({ script: script, satoshis: 0 })
);
// Create second output to sender if dunes are directly allocated in etching
if (premine > 0) tx.to(wallet.address, 100_000);
await fund(wallet, tx);
await broadcast(tx, true);
console.log(tx.hash);
}
);