-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutxosManager.js
More file actions
805 lines (683 loc) · 33.3 KB
/
utxosManager.js
File metadata and controls
805 lines (683 loc) · 33.3 KB
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
const CardanoWasm = require('@emurgo/cardano-serialization-lib-nodejs');
if (CardanoWasm.__wasm.memory.buffer.byteLength < 6000000)
CardanoWasm.__wasm.memory.grow(100);
const Common = require('./util/common');
const config = require('./config');
const UtxoSelectionService = require('./bizServices/utxoSelectionService');
class UtxosManager {
constructor(chainConnector, logUtil, bMainnet) {
this.connector = chainConnector;
this.bMainnet = bMainnet;
this.logger = logUtil;
this.ADDR_PREFIX = config.PlutusCfg.testnetPrefix;
this.network_id = CardanoWasm.NetworkInfo.testnet().network_id();
if (bMainnet) {
this.ADDR_PREFIX = config.PlutusCfg.mainnetPrefix;
this.network_id = CardanoWasm.NetworkInfo.mainnet().network_id();
}
this.maxPlutusUtxoNum = config.PlutusCfg.maxUtxoNum;
this.coinsPerUtxoWord = undefined;
this.minFeeA = undefined;
this.minFeeB = undefined;
this.protocolParams = undefined;
// to record the current gpk
this.curChainTip = undefined;
this.curLatestBlock = undefined;
this.groupPK = undefined;
// to record pending consumed utxos
this.mapPendingConsumedUTXO = new Map();
/* Modify By NFT Program:
add mapReservedNftUtxo to record nft utxo usage in memory
*/
this.mapReservedNftUtxo = new Map(); // utxoId -> {reservedTxId, reservedAmount(unit -> amount), reservedSlot}
this.mapAddressAvailableUtxos = new Map();
this.mapAccountLocker = new Map();
// to new common util instance
this.commonUtil = new Common(this.ADDR_PREFIX);
this.utxoSelectionService = new UtxoSelectionService(this.ADDR_PREFIX);
}
async init() {
return await this.getCurChainParams();
}
// set related address config
setSmgLeaderAddress(smgLeaderAddr) {
this.paymentAddress = smgLeaderAddr;
}
setTreasuryScAddress(treasuryScAddress) {
this.treasuryScAddress = treasuryScAddress;
}
setNftTreasuryScAddress(nftTreasuryScAddress) {
this.nftTreasuryScAddress = nftTreasuryScAddress;
}
// retrieve chain parameters
async getCurChainParams() {
let latestChainTip = undefined;
try {
latestChainTip = await this.connector.chainTip();
// this.logger.debug("..UtxosManager......latestChainTip: ", latestChainTip);
} catch (e) {
this.logger.debug("..UtxosManager......failed to get chainTip: ", e);
return false;
}
// step 2: to get lock
if ((undefined !== this.curChainTip)
&& ((this.curChainTip.slot + config.ChainStatusValidLatestSlot) > latestChainTip.slot)) {
return true;
}
while (this.mapAccountLocker.get("latestChainStatusLocker")) {
await this.commonUtil.sleep(1000);
}
this.mapAccountLocker.set("latestChainStatusLocker", true);
if ((undefined === this.curChainTip)
|| ((this.curChainTip.slot + config.ChainStatusValidLatestSlot) <= latestChainTip.slot)) {
try {
// to filter utxos in security block scopes
this.curLatestBlock = await this.connector.blocksLatest();
// this.logger.debug("..UtxosManager......this.curLatestBlock: ", this.curLatestBlock);
} catch (e) {
this.logger.debug("..UtxosManager......get blocksLatest failed: ", e);
this.mapAccountLocker.set("latestChainStatusLocker", false);
return false;
}
try {
let tmpProtocolParams = await this.connector.getCurrentProtocolParameters();
// this.logger.debug("..UtxosManager......protocolParams: ", this.protocolParams);
if ((undefined === tmpProtocolParams) || ("" === tmpProtocolParams)) {
this.logger.debug("..UtxosManager......getCurChainParams failed: ");
this.mapAccountLocker.set("latestChainStatusLocker", false);
return false;
}
this.protocolParams = tmpProtocolParams;
this.minFeeA = JSON.stringify(this.protocolParams.minFeeCoefficient);
this.minFeeB = JSON.stringify(this.protocolParams.minFeeConstant);
this.coinsPerUtxoWord = JSON.stringify(this.protocolParams.coinsPerUtxoByte * 2);
this.maxTxSize = JSON.stringify(this.protocolParams.maxTxSize);
} catch (e) {
this.logger.debug("..UtxosManager......getCurChainParams failed: ", e);
this.mapAccountLocker.set("latestChainStatusLocker", false);
return false;
}
try {
this.curChainTip = await this.connector.chainTip();
this.logger.debug("..UtxosManager......get this.curChainTip onchain: ", this.curChainTip);
} catch (e) {
this.logger.debug("..UtxosManager......get chainTip failed: ", e);
this.mapAccountLocker.set("latestChainStatusLocker", false);
return false;
}
}
this.mapAccountLocker.set("latestChainStatusLocker", false);
return true;
}
async getUtxo(address, bCheckDatum = true, coinValue = 0) {
const itemCount = 100;
let pageNumber = 1;
let utxos = new Array();
let ret = new Array();
let safeBlockNumber = 0;
try {
let rslt = await this.getCurChainParams();
if (false === rslt) {
this.logger.debug("..UtxosManager...getUtxo...getCurChainParams: ", rslt);
return ret;
}
} catch (e) {
this.logger.debug("..UtxosManager...getUtxo...getCurChainParams failed: ", e);
return ret;
}
// to check if need to query from ogmios service
let utxoRecordObj = this.mapAddressAvailableUtxos.get(address);
if ((undefined !== utxoRecordObj)
&& (utxoRecordObj.recordSlot > (this.curChainTip.slot - config.UtxoValidLatestSlot))) {
// pre-backup utxo is still valid
//this.logger.debug("..UtxosManager......getUtxo...utxoRecordObj.utxos: ", utxoRecordObj.utxoRecords);
return utxoRecordObj.utxoRecords;
} else {
// step 2: to check safe block height
while (this.mapAccountLocker.get(address)) {
await this.commonUtil.sleep(1000);
}
this.mapAccountLocker.set(address, true);
let curUtxoRecord = this.mapAddressAvailableUtxos.get(address);
if (((undefined === utxoRecordObj) && (undefined !== curUtxoRecord))
|| ((undefined !== utxoRecordObj) && (utxoRecordObj.recordSlot !== curUtxoRecord.recordSlot))) {
this.mapAccountLocker.set(address, false);
return curUtxoRecord.utxoRecords;
}
// add exception catch for connector
try {
do {
let rslt = await this.connector.getAddressUTXOsWithBlockHeight(address, pageNumber, itemCount, 'asc');
// this.logger.debug(`..UtxosManager...getAddressUTXOsWithBlockHeight ${address}...${rslt.utxos}`);
if (null == rslt) {
break;
} else {
utxos.push(...rslt.utxos);
}
if ("ogmios" === rslt.source) {
break;
} else if (itemCount > rslt.utxos.length) {
break;
} else {
pageNumber++;
}
} while (true);
} catch (e) {
this.logger.debug("..UtxosManager......getUtxo...getAddressUTXOs failed: ", e);
this.mapAccountLocker.set(address, false);
return ret;
}
}
// console.log(`..UtxosManager...getUtxo return ${utxos.length} utxo of ${address}`);
// this.logger.debug(`..UtxosManager...getUtxo return ${utxos.length} utxo of ${address}`);
// step 3: to filter safe utxos
// 2023/06/27 modify: to filter safe utxos in wanOgmiosService api
for (let i = 0; i < utxos.length; i++) {
const utxo = utxos[i];
let mapAsset = new Map();
let coinsAmount = undefined;
for (let j = 0; j < utxo.amount.length; j++) {
if ("lovelace" === utxo.amount[j].unit) {
// if (coinValue && CardanoWasm.BigNum.from_str(utxo.amount[j].quantity + '').compare(
// CardanoWasm.BigNum.from_str('' + coinValue)
// ) < 0) break;
let bnCoinAmount = mapAsset[utxo.amount[j].unit];
if (undefined === bnCoinAmount) {
bnCoinAmount = CardanoWasm.BigNum.from_str('0');
}
bnCoinAmount = bnCoinAmount.checked_add(CardanoWasm.BigNum.from_str(utxo.amount[j].quantity + ''));
coinsAmount = bnCoinAmount.to_str();
} else {
// this.logger.debug("..UtxosManager......asset unit: ", utxo.amount[j].unit, utxo.amount[j].quantity + '')
let bnAssetAmount = mapAsset[utxo.amount[j].unit];
if (undefined === bnAssetAmount) {
bnAssetAmount = CardanoWasm.BigNum.from_str('0');
}
bnAssetAmount = bnAssetAmount.checked_add(CardanoWasm.BigNum.from_str(utxo.amount[j].quantity + ''));
// let assetUnit = utxo.amount[j].unit.replace(".", "");
let assetUnit = utxo.amount[j].unit;
mapAsset[assetUnit] = bnAssetAmount.to_str();
}
}
// filter utxo with null datum
let utxoDatum = this.connector.bUseOgmios ? utxo.data_hash : utxo.inline_datum;
// console.log("utxoDatum: ", utxoDatum);
// this.logger.debug("..UtxosManager......utxo utxoDatum: ", utxo.data_hash)
if ((bCheckDatum && utxoDatum) || (!bCheckDatum)) {
ret.push({
txHash: utxo.tx_hash,
index: utxo.tx_index,
value: {
coins: coinsAmount,
assets: mapAsset
},
address: utxo.address,
datum: utxoDatum,
datumHash: utxo.datumHash,
script: utxo.script,
blockHeight: utxo.blockHeight
});
}
}
let newUtxoRecordObj = {
"utxoRecords": ret,
"recordSlot": this.curChainTip.slot
}
this.mapAddressAvailableUtxos.set(address, newUtxoRecordObj);
this.mapAccountLocker.set(address, false);
// this.logger.debug("..UtxosManager......ret len: ", ret.length);
// console.log("..UtxosManager......ret len: ", ret);
return ret;
}
checkPreReservedUtxo(availableUtxos, txId, amount) {
// Step 1: to check if there is preReserved utxo for this task
// reservedInfo = {
// "utxoId": preReservedUtxoId,
// "nftInfos": reservedAmount, // {unit -> amount} , and unit with no '.'
// "priority": undefined
// }
let reservedInfo = this.getPreReservedUtxoInfoByTxId(txId);
if (undefined === reservedInfo) {
// there is no reserved utxo for this task
let ret = {
"reservedUtxo": undefined,
"reservedStatus": "NoPreReserved", // "noPreReserved"
"marginAmount": amount
}
return ret;
}
// Step 2: to check whether the preReserved utxo is available
let preReservedUtxo = this.commonUtil.getUtxoByUtxoId(availableUtxos, reservedInfo.utxoId);
if (undefined === preReservedUtxo) {
// the preReserved utxos is no available by now
let ret = {
"reservedUtxo": undefined,
"reservedStatus": "PendingAvailable",
"marginAmount": undefined
}
return ret;
}
// Step 3: to check the amount of preReserved utxo whether has reached the transfer amount
let marginAmount = this.commonUtil.caculateMarginNftAmount(amount, reservedInfo.nftInfos);
let ret = {
// the preReserved utxo is available
"reservedUtxo": preReservedUtxo,
"reservedStatus": "Available",
"marginAmount": marginAmount
}
// Step 4: to update preReservedutxoInfo
this.updatePreReservedUtxoInfo();
return ret;
}
async getNftUtxoOfAmount(fromAddress, toAddress, amount, limit = undefined, uniqueId = undefined) {
// to verify the amount validity
if ((undefined === amount) || (0 === amount.length)) {
this.logger.debug("..getNftUtxoOfAmount......invalid transfer amount: ", uniqueId, amount);
return undefined;
}
// to get utxos of fromAddress
let utxos = await this.getUtxo(fromAddress, (this.paymentAddress !== fromAddress));
this.logger.debug("..getNftUtxoOfAmount......getUtxo utxos: ", this.paymentAddress, fromAddress, utxos.length);
if (0 === utxos.length) {
return undefined;
}
// to filter utxos in security block scopes
let pendingSelectionUtxos = new Array();
for (let i = 0; i < utxos.length; i++) {
if ((undefined !== utxos[i].blockHeight)
&& (utxos[i].blockHeight <= (this.curLatestBlock.height - config.SecurityBlocksForCoinSelection))) {
pendingSelectionUtxos.push(utxos[i]);
}
}
/* Modify By NFT Program:
in NFT task case, need to check if this cctask has taken preReserved utxos
*/
let selectedUtxos = new Array();
let retCheck = this.checkPreReservedUtxo(pendingSelectionUtxos, uniqueId, amount);
if ("PendingAvailable" === retCheck.reservedStatus) {
// in case the preReserved utxo is not available yet
let ret = {
"totalUtxos": utxos,
"selectedUtxos": undefined,
"marginAmount": undefined,
"checkStatus": "PendingAvailable"
}
return ret;
} else if ("Available" === retCheck.reservedStatus) {
// in case the reserved utxo is available
selectedUtxos.push(retCheck.reservedUtxo);
amount = retCheck.marginAmount;
if (0 === retCheck.marginAmount.length) {
// in case the reserved utxo satisfy the required amount
let ret = {
"totalUtxos": utxos,
"selectedUtxos": selectedUtxos,
"marginAmount": retCheck.marginAmount, // in this case, margin amount is empty array
"checkStatus": "Available"
}
return ret;
}
} else {
// in case there is no preReserved utxo
this.logger.debug("there is no preReserved utxo for this ccTask: ", uniqueId);
}
// add asset type as filter params
let availableUtxos = new Array();
for (let m = 0; m < amount.length; m++) {
let assetUnit = ("lovelace" === amount[m].unit) ? "lovelace" : (amount[m].unit + "." + amount[m].name);
/* Modify By NFT Program:
checkAvailableUtxos need to do further to parse preReserved utxos
*/
let availableUtxosByUnit = this.checkAvailableUtxos(fromAddress,
pendingSelectionUtxos,
false,
assetUnit,
true);
if (undefined === availableUtxosByUnit) {
continue;
}
/* Modify By NFT Program:
need to do further to unique utxo
*/
availableUtxos = this.commonUtil.uniqueUtxosInArray(availableUtxos, availableUtxosByUnit);
}
if (0 === availableUtxos.length) {
this.logger.debug("..UtxosManager......checkAvailableUtxos: no available utxo");
// in case no available utxos
let ret = {
"totalUtxos": utxos,
"selectedUtxos": selectedUtxos,
"marginAmount": amount,
"checkStatus": "NoAvailable"
}
return ret;
}
this.logger.debug("..UtxosManager......checkAvailableUtxos: ", availableUtxos.length);
limit = (undefined === limit) ? limit : (limit - selectedUtxos.length);
this.utxoSelectionService.setProtocolParameters(this.coinsPerUtxoWord, this.minFeeA, this.minFeeB, '10000');
let filtedUtxo = this.utxoSelectionService.selectUtxos(availableUtxos, toAddress, amount, limit, true);
if (0 === filtedUtxo.length) {
// in case no any suitable utxo is selected
let ret = {
"totalUtxos": utxos,
"selectedUtxos": selectedUtxos,
"marginAmount": amount,
"checkStatus": "InSufficent"
}
return ret;
}
// to update selected utxos status to pendingConsumed
for (let j = 0; j < filtedUtxo.length; j++) {
let utxoObj = filtedUtxo[j];
let txId = utxoObj.txIn.txId;
let txIndex = utxoObj.txIn.index;
for (let k = 0; k < utxos.length; k++) {
let utxo = utxos[k];
if ((txId === utxo.txHash) && (txIndex === utxo.index)) {
selectedUtxos.push(utxo);
// to add new pending consumed utxos
let mapConsumedUtxos = this.mapPendingConsumedUTXO.get(fromAddress);
let encUtxo = this.commonUtil.encodeUtxo(utxoObj);
let utxoId = encUtxo.input().to_hex();
mapConsumedUtxos.set(utxoId, this.curChainTip.slot);
this.mapPendingConsumedUTXO.set(fromAddress, mapConsumedUtxos);
break;
}
}
}
this.logger.debug("..UtxosManager......selectUtxos ret: ", selectedUtxos.length);
let ret = {
"totalUtxos": utxos,
"selectedUtxos": selectedUtxos,
"marginAmount": amount, // in this case, margin amount is empty array
"checkStatus": "Available"
}
return ret;
}
async getUtxoOfAmount(fromAddress, toAddress, amount, limit) {
// to verify the amount validity
if ((undefined === amount) || (0 === amount.length)) {
this.logger.debug("..getUtxoOfAmount......invalid transfer amount: ", amount);
return undefined;
}
let assetUnit = ("lovelace" === amount[0].unit) ? "lovelace" : (amount[0].unit + amount[0].name);
// to get utxos of fromAddress
let utxos = await this.getUtxo(fromAddress, (this.paymentAddress !== fromAddress));
this.logger.debug("..UtxosManager......getUtxo utxos: ", fromAddress, utxos.length);
if (0 === utxos.length) {
this.logger.debug("..getUtxoOfAmount......failed to get utxo: ", fromAddress);
return undefined;
}
// to filter utxos in security block scopes
let pendingSelectionUtxos = new Array();
for (let i = 0; i < utxos.length; i++) {
if ((undefined !== utxos[i].blockHeight)
&& (utxos[i].blockHeight <= (this.curLatestBlock.height - config.SecurityBlocksForCoinSelection))) {
pendingSelectionUtxos.push(utxos[i]);
}
}
// add asset type as filter params
let selectedUtxos = new Array();
let availableUtxos = this.checkAvailableUtxos(fromAddress, pendingSelectionUtxos, false, assetUnit);
if (undefined === availableUtxos) {
this.logger.debug("..UtxosManager......checkAvailableUtxos: no available utxo");
let ret = {
"totalUtxos": utxos,
"selectedUtxos": selectedUtxos
}
return ret;
}
// this.logger.debug("..UtxosManager......checkAvailableUtxos: ", availableUtxos.length);
this.utxoSelectionService.setProtocolParameters(this.coinsPerUtxoWord, this.minFeeA, this.minFeeB, '10000');
let filtedUtxo = this.utxoSelectionService.selectUtxos(availableUtxos, toAddress, amount, limit);
// to update selected utxos status to pendingConsumed
for (let j = 0; j < filtedUtxo.length; j++) {
let utxoObj = filtedUtxo[j];
let txId = utxoObj.txIn.txId;
let txIndex = utxoObj.txIn.index;
for (let k = 0; k < utxos.length; k++) {
let utxo = utxos[k];
if ((txId === utxo.txHash) && (txIndex === utxo.index)) {
selectedUtxos.push(utxo);
// to add new pending consumed utxos
let mapConsumedUtxos = this.mapPendingConsumedUTXO.get(fromAddress);
let encUtxo = this.commonUtil.encodeUtxo(utxoObj);
let utxoId = encUtxo.input().to_hex();
mapConsumedUtxos.set(utxoId, this.curChainTip.slot);
this.mapPendingConsumedUTXO.set(fromAddress, mapConsumedUtxos);
break;
}
}
}
this.logger.debug("..UtxosManager......selectUtxos ret: ", selectedUtxos.length);
let ret = {
"totalUtxos": utxos,
"selectedUtxos": selectedUtxos
}
return ret;
}
checkAvailableUtxos(fromAddress, utxos, bCheckUtxoAddress, assetUnit = undefined, bNFT = false) {
// Step1: to format utxos
let formatUtxos = this.commonUtil.formatUtxoData(utxos);
// Step2: to filter multi-asset utxos
let availableUtxos = new Array();
for (let k = 0; k < formatUtxos.length; k++) {
let mapAssetUnit = new Map();
let itemTxOut = formatUtxos[k].txOut;
for (let v = 0; v < itemTxOut.value.length; v++) {
let itemValue = itemTxOut.value[v];
mapAssetUnit.set(itemValue.unit, true);
// this.logger.debug("..UtxosManager......mapAssetUnit set :", itemValue.unit, assetUnit);
}
// to filter multi-asset utxos
//this.logger.debug("..UtxosManager......mapAssetUnit size :", mapAssetUnit.size);
if ((2 >= mapAssetUnit.size) || bNFT) {
if (!assetUnit) {
availableUtxos.push(formatUtxos[k]);
} else if (("lovelace" === assetUnit) && (1 === mapAssetUnit.size)) {
availableUtxos.push(formatUtxos[k]);
} else if (("lovelace" !== assetUnit) && (mapAssetUnit.get(assetUnit.replace(".", "")))) {
availableUtxos.push(formatUtxos[k]);
}
}
}
// this.logger.debug("..UtxosManager......availableUtxos length:", fromAddress, assetUnit, availableUtxos.length);
// Step3: to filter pending consumed utxo
let filteredAvailableUtxos = undefined;
let mapConsumedUtxos = this.mapPendingConsumedUTXO.get(fromAddress);
if (undefined === mapConsumedUtxos) {
filteredAvailableUtxos = availableUtxos;
mapConsumedUtxos = new Map();
this.mapPendingConsumedUTXO.set(fromAddress, mapConsumedUtxos);
} else {
// Step3-1: to update pending consumed utxos
let maxPendingTTL = bCheckUtxoAddress ? config.MaxConsumedCheckUtxoTTL : config.MaxConsumedUtxoTTL;
for (let key of mapConsumedUtxos.keys()) {
let consumedInitialSlot = mapConsumedUtxos.get(key);
let durSlot = this.curChainTip.slot - consumedInitialSlot;
if (maxPendingTTL <= durSlot) {
mapConsumedUtxos.delete(key);
}
this.mapPendingConsumedUTXO.set(fromAddress, mapConsumedUtxos);
}
// Step3-2: to filter pending consumed utxo
for (let i = 0; i < availableUtxos.length; i++) {
// this.logger.debug("..UtxosManager......filteredAvailableUtxos...available Utxo:", i, availableUtxos[i]);
let encUtxo = this.commonUtil.encodeUtxo(availableUtxos[i]);
let utxoId = encUtxo.input().to_hex();
// to filter the pending consumed utxo
let consumedInitialSlot = mapConsumedUtxos.get(utxoId);
if (undefined !== consumedInitialSlot) {
// this.logger.debug("..UtxosManager......filteredAvailableUtxos...consumedInitialSlot:",availableUtxos[i], utxoId, consumedInitialSlot, this.curChainTip.slot);
continue;
}
/* Modify By NFT Program:
need also to filter the preReserved utxo
*/
let reservedUtxoInfo = this.mapReservedNftUtxo.get(utxoId);
if (undefined !== reservedUtxoInfo) {
// this.logger.debug("..plutusNftTxBuilder......filteredAvailableUtxos...consumedInitialSlot:",availableUtxos[i], utxoId, consumedInitialSlot, this.curChainTip.slot);
continue;
}
// confirm available utxos
if (undefined === filteredAvailableUtxos) {
filteredAvailableUtxos = new Array();
}
filteredAvailableUtxos.push(availableUtxos[i]);
// this.logger.debug("..UtxosManager......filteredAvailableUtxos...:", i, availableUtxos[i], utxoId);
}
}
// this.logger.debug("..UtxosManager......filteredAvailableUtxos :", fromAddress);
return filteredAvailableUtxos;
}
///////////////////////////////////////////
// Part 2: pending comsumed utxo management
///////////////////////////////////////////
revertUtxoPendingComsumedStatus(inputUtxos) {
for (let i = 0; i < inputUtxos.length; i++) {
// to generate tx input based on txId&index
let transaction_id = CardanoWasm.TransactionHash.from_bytes(Buffer.from(inputUtxos[i].txId, 'hex'));
let txInput = CardanoWasm.TransactionInput.new(transaction_id, inputUtxos[i].index);
// to generate utxoId by txInput
let utxoId = txInput.to_hex();
// this.logger.debug(`..UtxosManager..release utxo: ${inputUtxos[i].txId + '#' + inputUtxos[i].index} related to Key: ${utxoId}`);
for (let address of this.mapPendingConsumedUTXO.keys()) {
let mapConsumedUtxos = this.mapPendingConsumedUTXO.get(address);
this.logger.debug("..UtxosManager...release origin mapConsumedUtxos: ", address, mapConsumedUtxos);
if (mapConsumedUtxos.get(utxoId)) {
// this.logger.debug(`..UtxosManager..release utxoId: #${utxoId} in pendingUtxo of address: ${address}`);
mapConsumedUtxos.delete(utxoId);
this.mapPendingConsumedUTXO.set(address, mapConsumedUtxos);
this.logger.debug("..UtxosManager...release updated mapConsumedUtxos: ", mapConsumedUtxos);
break;
};
}
}
}
releaseUtxos(utxos) {
let aryUtxos = undefined;
if (utxos instanceof Array) {
aryUtxos = utxos;
} else {
aryUtxos = [utxos];
}
let revertedUtxos = new Array();
for (let i = 0; i < aryUtxos.length; i++) {
let utxoItem = {
"txId": aryUtxos[i].txHash,
"index": aryUtxos[i].index
}
revertedUtxos.push(utxoItem);
// this.logger.debug(`..UtxosManager...release utxo: ${utxoItem.txId + '#' + utxoItem.index}`);
}
this.revertUtxoPendingComsumedStatus(revertedUtxos);
}
getPendingComsumedUtxoByAddress(address) {
let mapConsumedUtxos = this.mapPendingConsumedUTXO.get(address);
return mapConsumedUtxos;
}
appendPendingComsumedUtxo(address, utxo, curSlot) {
let mapConsumedUtxos = this.mapPendingConsumedUTXO.get(address);
if (undefined === mapConsumedUtxos) {
mapConsumedUtxos = new Map();
}
let encUtxo = this.commonUtil.encodeUtxo(utxo);
let utxoId = encUtxo.input().to_hex();
mapConsumedUtxos.set(utxoId, curSlot);
this.mapPendingConsumedUTXO.set(address, mapConsumedUtxos);
}
deletePendingComsumedUtxoById(address, utxoId) {
let mapConsumedUtxos = this.mapPendingConsumedUTXO.get(address);
if (undefined === mapConsumedUtxos) {
return;
}
mapConsumedUtxos.delete(utxoId);
this.mapPendingConsumedUTXO.set(address, mapConsumedUtxos);
return;
}
updatePendingComsumedUtxoByAddress(address, curSlot, bCheckUtxoAddress) {
let maxPendingTTL = bCheckUtxoAddress ? config.MaxConsumedCheckUtxoTTL : config.MaxConsumedUtxoTTL;
let mapConsumedUtxos = this.mapPendingConsumedUTXO.get(address);
if (undefined === mapConsumedUtxos) {
// filteredAvailableUtxos = availableUtxos;
mapConsumedUtxos = new Map();
this.mapPendingConsumedUTXO.set(address, mapConsumedUtxos);
}
for (let key of mapConsumedUtxos.keys()) {
let consumedInitialSlot = mapConsumedUtxos.get(key);
let durSlot = curSlot - consumedInitialSlot;
if (maxPendingTTL <= durSlot) {
mapConsumedUtxos.delete(key);
}
this.mapPendingConsumedUTXO.set(address, mapConsumedUtxos);
}
}
parsePendingUtxoRatio(scAddress, availableUtxos) {
let availableUtxosNum = availableUtxos.length;
let mapConsumedUtxos = this.mapPendingConsumedUTXO.get(scAddress);
if (undefined === mapConsumedUtxos) {
mapConsumedUtxos = new Map();
}
let pendingUtxoNum = 0;
for (let i = 0; i < availableUtxos.length; i++) {
let utxoObj = availableUtxos[i];
let encUtxo = this.commonUtil.encodeUtxo(utxoObj);
let utxoId = encUtxo.input().to_hex();
if (mapConsumedUtxos.get(utxoId)) {
pendingUtxoNum++;
}
}
let pendingUtxoRatio = parseFloat(pendingUtxoNum * 100 / availableUtxosNum);
return pendingUtxoRatio;
}
///////////////////////////////////////
// Part 3: Pre-reserved utxo management
///////////////////////////////////////
updatePreReservedUtxoInfo() {
/* Modify By NFT Program:
and also need to filter pre-reserved utxos for nft balance
*/
for (let utxoId of this.mapReservedNftUtxo.keys()) {
let reservedUtxoInfo = this.mapReservedNftUtxo.get(utxoId);
let durSlot = this.curChainTip.slot - reservedUtxoInfo.reservedSlot;
if (config.MaxNftUtxoOccupiedTs < durSlot) {
this.mapReservedNftUtxo.delete(utxoId);
}
}
}
getPreReservedUtxoInfoByTxId(txId) {
// mapReservedNftUtxo: utxoId -> {reservedTxId, reservedAmount, reservedSlot}
for (let [utxoId, reservedInfo] of this.mapReservedNftUtxo) {
// let reservedInfo = this.mapReservedNftUtxo.get(utxoId);
if (txId === reservedInfo.reservedTxId) {
let reservedUtxoInfo = {
"utxoId": utxoId,
"nftInfos": reservedInfo.reservedAmount,
"priority": undefined
}
return reservedUtxoInfo;
}
}
return undefined;
}
getPreReservedInfoByUtxoId(utxoId, txId) {
// mapReservedNftUtxo: utxoId -> {reservedTxId, reservedAmount, reservedSlot}
let reservedInfo = this.mapReservedNftUtxo.get(utxoId);
if (undefined === reservedInfo) {
return undefined;
}
if (txId === reservedInfo.reservedTxId) {
let reservedUtxoInfo = {
"utxoId": utxoId,
"nftInfos": reservedInfo.reservedAmount,
"priority": undefined
}
return reservedUtxoInfo;
}
return undefined;
}
appendPreReservedUtxoInfo(utxoId, reservedInfo) {
this.mapReservedNftUtxo.set(utxoId, reservedInfo);
}
}
module.exports = UtxosManager;