-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplutusTxBuilder.js
More file actions
2817 lines (2374 loc) · 132 KB
/
plutusTxBuilder.js
File metadata and controls
2817 lines (2374 loc) · 132 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
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
const CardanoWasm = require('@emurgo/cardano-serialization-lib-nodejs');
if (CardanoWasm.__wasm.memory.buffer.byteLength < 6000000)
CardanoWasm.__wasm.memory.grow(100);
const contracts = require('./cross-chain-js/contracts');
const contractsMgr = require('./cross-chain-js/contracts-mgr');
const utils = require('./cross-chain-js/utils');
const common = require('./util/common');
const config = require('./config');
const cbor = require('cbor-sync');
class PlutusTxBuilder {
constructor(chainConnector, coinSelectionInst, scriptRefOwnerAddr, logUtil, bMainnet) {
this.connector = chainConnector;
this.coinSelectionInst = coinSelectionInst;
this.scriptRefOwnerAddr = scriptRefOwnerAddr;
// this.collateralAmount = config.PlutusCfg.collateralAmount;
this.bMainnet = bMainnet;
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;
contracts.init(bMainnet);
if (0 === config.SignAlgorithmMode) {
this.signMode = contracts.TreasuryScript.MODE_ECDSA;
} else if (2 === config.SignAlgorithmMode) {
this.signMode = contracts.TreasuryScript.MODE_ED25519;
} else {
this.signMode = contracts.TreasuryScript.MODE_SCHNORR340;
}
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();
// this.mapMultiAssetUTXO = new Map();
this.mapScBalancedMarkRecord = new Map();
this.mapForcedBalancedStatus = new Map();
this.mapAddressAvailableUtxos = new Map();
this.mapAccountLocker = new Map();
// supportted token
this.mapValidAssetType = new Map();
this.mapBalancedDirection = new Map();
this.mapAssetBalancedTs = new Map();
this.mapAssetAdaSptrippedTs = new Map();
// to new common util instance
this.commonUtil = new common(this.ADDR_PREFIX);
this.logger = logUtil;
}
async init() {
let stakeCred = await this.getGroupInfoStkVh();
this.lockerScAddress = contracts.TreasuryScript.address(stakeCred).to_bech32(this.ADDR_PREFIX);
console.log("\n\n\n\******* this.lockerScAddress: ", this.lockerScAddress);
}
getLockerScAddress() {
return this.lockerScAddress;
}
getValidPolicyId() {
let validPolicyId = contracts.MappingTokenScript.policy_id();
return validPolicyId
}
addressToPkhOrScriptHash(address) {
let phk = utils.addressToPkhOrScriptHash(address);
return phk;
}
async convertSlotToTimestamp(slot) {
try {
const eraSummaries = await this.connector.queryEraSummaries();
const genisis = await this.connector.queryGenesisConfig();
return this.slotToTimestamp(slot, eraSummaries, genisis);
} catch (err) {
throw `convertSlotToTimestamp failed: ${err}`;
}
}
slotToTimestamp(slot, eraSummaries, genisis) {
let earIndexNumber = undefined;
for (let i = 0; i < eraSummaries.length; i++) {
const ear = eraSummaries[i];
if ((slot >= ear.start.slot) && (slot <= ear.end.slot)) {
earIndexNumber = i;
break;
} else if (slot > ear.end.slot) {
continue;
} else if (slot < ear.end.slot) {
throw `Bad slot ${slot}`;
}
}
if (undefined === earIndexNumber) {
throw `Bad slot ${slot}`;
}
let sysStartTimeStamp = Date.parse(genisis.systemStart);
const targetEar = eraSummaries[earIndexNumber];
return sysStartTimeStamp + targetEar.start.time * 1000 + (slot - targetEar.start.slot) * targetEar.parameters.slotLength * 1000;
}
async updateGroupInfoToken() {
this.groupInfoToken = await this.getGroupInfoToken();
// this.logger.debug("..PlutusTxBuilder......updateGroupInfoToken..groupInfoToken: ", groupInfoToken);
if (false === this.groupInfoToken) {
this.logger.debug("..PlutusTxBuilder......failed to get groupInfoToken: ");
return false;
}
const groupInfo = contractsMgr.GroupNFT.groupInfoFromDatum(this.groupInfoToken.datum);
this.groupPK = groupInfo[contractsMgr.GroupNFT.GPK];
return true;
}
async getCurChainParams() {
let latestChainTip = undefined;
try {
latestChainTip = await this.connector.chainTip();
// this.logger.debug("..PlutusTxBuilder......latestChainTip: ", latestChainTip);
} catch (e) {
this.logger.debug("..PlutusTxBuilder......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("..PlutusTxBuilder......this.curLatestBlock: ", this.curLatestBlock);
} catch (e) {
this.logger.debug("..PlutusTxBuilder......get blocksLatest failed: ", e);
this.mapAccountLocker.set("latestChainStatusLocker", false);
return false;
}
try {
let tmpProtocolParams = await this.connector.getCurrentProtocolParameters();
// this.logger.debug("..PlutusTxBuilder......protocolParams: ", this.protocolParams);
if ((undefined === tmpProtocolParams) || ("" === tmpProtocolParams)) {
this.logger.debug("..PlutusTxBuilder......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);
const v1 = CardanoWasm.CostModel.new();
let index = 0;
for (const key in this.protocolParams.costModels["plutus:v1"]) {
v1.set(index, CardanoWasm.Int.new_i32(this.protocolParams.costModels["plutus:v1"][key]));
index++;
}
const v2 = CardanoWasm.CostModel.new();
index = 0;
for (const key in this.protocolParams.costModels["plutus:v2"]) {
v2.set(index, CardanoWasm.Int.new_i32(this.protocolParams.costModels["plutus:v2"][key]));
index++;
}
this.protocolParams.costModels = CardanoWasm.Costmdls.new();
this.protocolParams.costModels.insert(CardanoWasm.Language.new_plutus_v1(), v1);
this.protocolParams.costModels.insert(CardanoWasm.Language.new_plutus_v2(), v2);
} catch (e) {
this.logger.debug("..PlutusTxBuilder......getCurChainParams failed: ", e);
this.mapAccountLocker.set("latestChainStatusLocker", false);
return false;
}
try {
this.curChainTip = await this.connector.chainTip();
this.logger.debug("..PlutusTxBuilder......get this.curChainTip onchain: ", this.curChainTip);
} catch (e) {
this.logger.debug("..PlutusTxBuilder......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;
// this.logger.debug("..PlutusTxBuilder......getUtxo address: ", address, bCheckDatum);
//if (undefined === this.curChainTip) {
try {
let rslt = await this.getCurChainParams();
if (false === rslt) {
this.logger.debug("..PlutusTxBuilder...getUtxo...getCurChainParams: ", rslt);
return ret;
}
} catch (e) {
this.logger.debug("..PlutusTxBuilder...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("..PlutusTxBuilder......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');
// console.log("\n\n getAddressUTXOsWithBlockHeight... rslt: ", rslt);
// this.logger.debug(`..PlutusTxBuilder...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("..PlutusTxBuilder......getUtxo...getAddressUTXOs failed: ", e);
this.mapAccountLocker.set(address, false);
return ret;
}
}
// this.logger.debug(`..PlutusTxBuilder...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("..PlutusTxBuilder......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;
// this.logger.debug("..PlutusTxBuilder......utxo utxoDatum: ", bCheckDatum, 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("..PlutusTxBuilder......ret len: ", ret.length);
return ret;
}
async getGroupInfoToken() {
const groupInfoHolder = contractsMgr.GroupInfoNFTHolderScript.address().to_bech32(this.ADDR_PREFIX);
this.logger.debug("..PlutusTxBuilder......GroupInfoNFTHolderScript address: ", groupInfoHolder);
let expectedTokenId = contractsMgr.GroupNFT.tokenId(); // need liulin confirm
expectedTokenId = expectedTokenId.replace(".", "")
const groupInfoToken = (await this.getUtxo(groupInfoHolder)).find(o => {
for (let tokenId in o.value.assets) {
tokenId = tokenId.replace(".", "");
if (tokenId == expectedTokenId) return true;
}
return false;
});
//this.logger.debug("..PlutusTxBuilder......groupInfoToken ", groupInfoToken);
if (undefined === groupInfoToken) {
return false;
}
return groupInfoToken;
}
async getGroupInfoStkVh() {
this.groupInfoToken = await this.getGroupInfoToken();
//this.logger.debug("..PlutusTxBuilder......getGroupInfoToken...: ", this.groupInfoToken);
if (false === this.groupInfoToken) {
throw "exception network during get group info token";
}
const groupInfo = contractsMgr.GroupNFT.groupInfoFromDatum(this.groupInfoToken.datum);
//this.logger.debug("..PlutusTxBuilder......groupInfoFromDatum...groupInfo: ", groupInfo);
let StkVh = groupInfo[contractsMgr.GroupNFT.StkVh];
//this.logger.debug("..PlutusTxBuilder......groupInfoFromDatum...StkVh: ", StkVh);
return StkVh;
}
async getTreasuryCheckAddress(bMintCheck) {
this.groupInfoToken = await this.getGroupInfoToken();
// this.logger.debug("..PlutusTxBuilder......getGroupInfoToken...: ", this.groupInfoToken);
if (false === this.groupInfoToken) {
throw "exception network during get group info token";
}
const groupInfo = contractsMgr.GroupNFT.groupInfoFromDatum(this.groupInfoToken.datum);
// this.logger.debug("..PlutusTxBuilder......groupInfoFromDatum...groupInfo: ", groupInfo);
let checkStkVh = groupInfo[contractsMgr.GroupNFT.StkVh];
// this.logger.debug("..PlutusTxBuilder......groupInfoFromDatum...stkVh: ", checkStkVh);
let vhItemName = bMintCheck ? contractsMgr.GroupNFT.MintCheckVH : contractsMgr.GroupNFT.TreasuryCheckVH;
let checkPayVh = groupInfo[vhItemName];
// this.logger.debug("..PlutusTxBuilder......groupInfoFromDatum...checkPayVh: ", bMintCheck, vhItemName, checkPayVh);
let checkStkKeyHash = CardanoWasm.ScriptHash.from_hex(checkStkVh); //Ed25519KeyHash
let checkPayKeyHash = CardanoWasm.ScriptHash.from_hex(checkPayVh);
let checkAddress = CardanoWasm.BaseAddress.new(
this.network_id,
CardanoWasm.StakeCredential.from_scripthash(checkPayKeyHash),
CardanoWasm.StakeCredential.from_scripthash(checkStkKeyHash) //from_keyhash
);
let strCheckAddress = checkAddress.to_address().to_bech32(this.ADDR_PREFIX);
// this.logger.debug("..PlutusTxBuilder......groupInfoFromDatum...strCheckAddress: ", strCheckAddress);
if (bMintCheck) {
let mintCheckTokenPolicyId = contracts.MintCheckTokenScript.policy_id();
// this.logger.debug("..PlutusTxBuilder......groupInfoFromDatum...mintCheckTokenPolicyId: ", mintCheckTokenPolicyId);
} else {
let checkTokenPolicyId = contracts.TreasuryCheckTokenScript.policy_id();
// this.logger.debug("..PlutusTxBuilder......groupInfoFromDatum...checkTokenPolicyId: ", checkTokenPolicyId);
}
return strCheckAddress;
}
///modify_2.21: add new valid asset tyep interface
addSupportedAssetType(tokenId) {
this.mapValidAssetType.set(tokenId, true);
}
async buildSignedTx(basicArgs, internalSignFunc, partialRedeemerArgs) {
//this.logger.debug("..PlutusTxBuilder...buildSignedTx......basicArgs:", basicArgs);
//this.logger.debug("..PlutusTxBuilder...buildSignedTx......partialRedeemerArgs:", partialRedeemerArgs);
this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...begin to build Signed Tx! ");
this.paymentAddress = basicArgs.paymentAddress;
this.paymentSkey = basicArgs.paymentSKey;
if (undefined === this.lockerScAddress) {
throw "failed to initial sdk!";
}
//Step 1: to get groupInfoToken and fetch group pk
let encodedGpk = this.commonUtil.encodeGpk(basicArgs.gpk);
// this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...this.groupInfoToken: ", this.groupInfoToken);
if (this.groupPK !== encodedGpk) {
this.groupInfoToken = await this.getGroupInfoToken();
//this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...getGroupInfoToken...: ", this.groupInfoToken);
if (false === this.groupInfoToken) {
throw "exception network during get group info token";
}
const groupInfo = contractsMgr.GroupNFT.groupInfoFromDatum(this.groupInfoToken.datum);
//this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...groupInfoFromDatum...groupInfo: ", groupInfo);
this.groupPK = groupInfo[contractsMgr.GroupNFT.GPK];
this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...groupInfoFromDatum...groupPK: ", this.groupPK);
if (this.groupPK !== encodedGpk) {
throw "inconsistent gpk";
}
}
console.log("\n\n... this.groupPK: ", this.groupPK);
// to register valid asset type
if (undefined === this.mapValidAssetType.get(basicArgs.tokenId)) {
this.addSupportedAssetType(basicArgs.tokenId);
}
// Step 2: to get cardano current netParams
let bRet = await this.getCurChainParams();
// this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...getCurChainParams......bRet:", bRet);
if (false === bRet) {
throw "exception network during update protocal params";
}
bRet = await this.fetchBalancedParams();
// this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...fetchBalancedParams......bRet:", bRet);
if (false === bRet) {
throw "exception network during update balanced params";
}
// Step 3: to build cardano cross-chain tx
let signedTx = await this.genSignedTxData(basicArgs, partialRedeemerArgs, internalSignFunc);
// this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...genSignedTxData......ret:", signedTx);
return signedTx;
}
async genSignedTxData(basicArgs, partialRedeemerArgs, internalSignFunc) {
const owner = basicArgs.crossAddress;
const ccTaskAmount = basicArgs.amount;
const tokenId = basicArgs.tokenId;
///this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...basicArgs: ", basicArgs);
// to confirm transfer asset value
let adaAmount = 0;
let tokenAmount = 0;
const datum = CardanoWasm.PlutusData.new_empty_constr_plutus_data(CardanoWasm.BigNum.from_str('0'));
if (config.AdaTokenId === tokenId) {
adaAmount = ccTaskAmount;
const minAda = this.commonUtil.getMinAdaOfUtxo(this.protocolParams, owner, { coins: adaAmount, assets: {} }, datum);
// this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...getMinAdaOfUtxo: ", minAda, typeof (minAda));
if (adaAmount < minAda) {
this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...adaAmount: ", adaAmount, typeof (adaAmount));
throw 'lt than minAda';
}
} else {
tokenAmount = ccTaskAmount;
const minAda = this.commonUtil.getMinAdaOfUtxo(this.protocolParams, owner, { coins: 0, assets: { [tokenId]: tokenAmount } }, datum);
// this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...getMinAdaOfUtxo: ", minAda, typeof (minAda));
adaAmount = minAda;
}
// this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...enough token amount: ", adaAmount, tokenId, tokenAmount);
// to build & sign normal cc tx or token mint tx by basciArgs params
let buildRet = undefined;
if (!basicArgs.bMint) {
buildRet = await this.buildAndSignRawTx(internalSignFunc, basicArgs, tokenAmount, adaAmount, partialRedeemerArgs);
} else {
buildRet = await this.buildAndSignMintRawTx(internalSignFunc, basicArgs, tokenAmount, partialRedeemerArgs);
}
this.logger.debug("..PlutusTxBuilder...", basicArgs.hashX, "...buildAndSignRawTx...signedTxData: ", buildRet);
return buildRet;
}
// add filter param of asset units
filterAvailableUtxos(availableUtxos, value) {
// this.logger.debug("..PlutusTxBuilder......filterAvailableUtxos value: ", value);
// to static the asset units
let filterUnits = new Array();
for (let k = 0; k < value.length; k++) {
let assetAmount = value[k];
let assetUnit = assetAmount.unit
if ("lovelace" !== assetUnit) {
assetUnit = assetUnit + assetAmount.name;
}
let kIndex = filterUnits.indexOf(assetUnit);
if (-1 === kIndex) {
filterUnits.push(assetUnit);
}
}
let selectionParam_inputs = new Array();
//this.logger.debug("..PlutusTxBuilder......filterAvailableUtxos... utxo pool: ", availableUtxos);
for (let i = 0; i < availableUtxos.length; i++) {
// to filter the utxo by asset unit
let bAssetUnitMatched = true;
let utxoValueArray = availableUtxos[i].txOut.value;
for (let j = 0; j < utxoValueArray.length; j++) {
let assetAmount = utxoValueArray[j];
if (("lovelace" !== assetAmount.unit) && (-1 === filterUnits.indexOf(assetAmount.unit))) {
bAssetUnitMatched = false;
break;
}
}
if (bAssetUnitMatched) {
let encUtxoObj = this.commonUtil.encodeUtxo(availableUtxos[i]);
selectionParam_inputs.push(encUtxoObj);
}
}
// this.logger.debug("..PlutusTxBuilder......filterAvailableUtxos... filtered utxo: ", selectionParam_inputs);
return selectionParam_inputs;
}
selectUtxos(utxos, toAddress, value, limit) {
if (undefined === limit) {
limit = config.PlutusCfg.leaderUtxoNumLimit;
}
this.coinSelectionInst.setProtocolParameters(this.coinsPerUtxoWord, this.minFeeA, this.minFeeB, '10000');
// this.logger.debug("..PlutusTxBuilder......selectUtxos toAddress: ", toAddress);
// step 1: to build output params
// this.logger.debug("..PlutusTxBuilder......buildOutputValue value: ", value);
let outputAddress = CardanoWasm.Address.from_bech32(toAddress);
// this.logger.debug("..PlutusTxBuilder......outputAddress: ", outputAddress);
let outputValue = this.commonUtil.buildOutputValue(value, undefined, this.coinsPerUtxoWord);
// this.logger.debug("..PlutusTxBuilder......buildOutputValue ret: ", outputValue);
let txOutput = CardanoWasm.TransactionOutput.new(outputAddress, outputValue);
// this.logger.debug("..PlutusTxBuilder......TransactionOutput ret: ", txOutput);
let selectionParam_outputs = CardanoWasm.TransactionOutputs.new();
selectionParam_outputs.add(txOutput);
// step 2: to filter available utxo and build input params
let selectedUtxos = new Array();
let selectionParam_inputs = this.filterAvailableUtxos(utxos, value);
// this.logger.debug("..PlutusTxBuilder......filterAvailableUtxos inputs len: ", selectionParam_inputs.length);
if (0 === selectionParam_inputs.length) {
return selectedUtxos;
} else {
try {
this.logger.debug("..PlutusTxBuilder......try to select utxos limited by 1 !");
let selectedRet = this.coinSelectionInst.randomImprove(selectionParam_inputs,
selectionParam_outputs,
1); // the 3rd param should be changed into 20+tokenAssets
for (let i = 0; i < selectedRet.input.length; i++) {
let utxo = selectedRet.input[i];
let utxoInfoObj = this.commonUtil.decodeUtxo(utxo);
selectedUtxos.push(utxoInfoObj);
}
// this.logger.debug("..PlutusTxBuilder......selectUtxos randomImprove:", selectedUtxos);
} catch (e) {
this.logger.debug("..PlutusTxBuilder......select by limit 1 failed! retry by default limit: ", limit);
try {
let selectedRet = this.coinSelectionInst.randomImprove(selectionParam_inputs,
selectionParam_outputs,
limit); // the 3rd param should be changed into 20+tokenAssets
for (let i = 0; i < selectedRet.input.length; i++) {
let utxo = selectedRet.input[i];
let utxoInfoObj = this.commonUtil.decodeUtxo(utxo);
selectedUtxos.push(utxoInfoObj);
}
// this.logger.debug("..PlutusTxBuilder......selectUtxos randomImprove:", selectedUtxos.length);
} catch (error) {
this.logger.debug("..PlutusTxBuilder......selectUtxo warning : INPUTS EXHAUSTED!");
return selectedUtxos;
}
}
}
return selectedUtxos;
}
checkAvailableUtxos(payAddress, utxos, bCheckUtxoAddress, assetUnit = undefined) {
// 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("..PlutusTxBuilder......mapAssetUnit set :", itemValue.unit, assetUnit);
}
// to filter multi-asset utxos
//this.logger.debug("..PlutusTxBuilder......mapAssetUnit size :", mapAssetUnit.size);
if (2 >= mapAssetUnit.size) {
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("..PlutusTxBuilder......availableUtxos length:", payAddress, assetUnit, availableUtxos.length);
// Step3: to filter pending consumed utxo
let filteredAvailableUtxos = undefined;
let mapConsumedUtxos = this.mapPendingConsumedUTXO.get(payAddress);
if (undefined === mapConsumedUtxos) {
filteredAvailableUtxos = availableUtxos;
mapConsumedUtxos = new Map();
this.mapPendingConsumedUTXO.set(payAddress, 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(payAddress, mapConsumedUtxos);
}
// Step3-2: to filter pending consumed utxo
for (let i = 0; i < availableUtxos.length; i++) {
// this.logger.debug("..PlutusTxBuilder......filteredAvailableUtxos...available Utxo:", i, availableUtxos[i]);
let encUtxo = this.commonUtil.encodeUtxo(availableUtxos[i]);
let utxoId = encUtxo.input().to_hex();
let consumedInitialSlot = mapConsumedUtxos.get(utxoId);
if (undefined !== consumedInitialSlot) {
// this.logger.debug("..PlutusTxBuilder......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("..PlutusTxBuilder......filteredAvailableUtxos...:", i, availableUtxos[i], utxoId);
}
}
this.logger.debug("..PlutusTxBuilder......filteredAvailableUtxos :", payAddress);
return filteredAvailableUtxos;
}
async getScriptCheckRefAvailableUtxo(scriptCheckRefAddress) {
let utxos = await this.getUtxo(scriptCheckRefAddress, false);
this.logger.debug("..PlutusTxBuilder......get scriptCheckRef utxos: ", scriptCheckRefAddress, utxos.length);
if (0 === utxos.length) {
this.logger.debug("..PlutusTxBuilder.....warning: get no scriptCheckRef utxos.");
return undefined;
}
let availableUtxos = this.checkAvailableUtxos(scriptCheckRefAddress, utxos, true);
// this.logger.debug("..PlutusTxBuilder......availableUtxos: ", availableUtxos);
if ((undefined === availableUtxos) || (availableUtxos.length < 1)) {
this.logger.debug("..PlutusTxBuilder...getScriptCheckRefAvailableUtxo...warning: no available check utxo");
return undefined;
}
let treasuryCheckUxto = undefined; // availableTreasuryCheckUxto
let txId = availableUtxos[0].txIn.txId;
let txIndex = availableUtxos[0].txIn.index;
for (let k = 0; k < utxos.length; k++) {
let utxo = utxos[k];
if ((txId === utxo.txHash) && (txIndex === utxo.index)) {
treasuryCheckUxto = utxo;
// this.logger.debug("..PlutusTxBuilder......selected availableUtxos: ", utxo);
// to add new pending consumed utxos for scriptCheckRefAddress
let mapConsumedUtxos = this.mapPendingConsumedUTXO.get(scriptCheckRefAddress);
if (undefined === mapConsumedUtxos) {
mapConsumedUtxos = new Map();
}
let encUtxo = this.commonUtil.encodeUtxo(availableUtxos[0]);
let utxoId = encUtxo.input().to_hex();
mapConsumedUtxos.set(utxoId, this.curChainTip.slot);
this.mapPendingConsumedUTXO.set(scriptCheckRefAddress, mapConsumedUtxos);
break;
}
}
return treasuryCheckUxto;
}
async getUtxoOfAmount(payAddress, toAddress, amount, limit) {
// to verify the amount validity
if ((undefined === amount) || (0 === amount.length)) {
return undefined;
}
let assetUnit = ("lovelace" === amount[0].unit) ? "lovelace" : (amount[0].unit + amount[0].name);
// to get utxos of payAddress
let utxos = await this.getUtxo(payAddress, (this.paymentAddress !== payAddress));
this.logger.debug("..PlutusTxBuilder......getUtxo utxos: ", payAddress, utxos.length, assetUnit);
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 ((this.paymentAddress === payAddress) ||
((undefined !== utxos[i].blockHeight)
&& (utxos[i].blockHeight <= (this.curLatestBlock.height - config.SecurityBlocksForCoinSelection)))) {
pendingSelectionUtxos.push(utxos[i]);
}
}
// add asset type as filter params
let availableUtxos = this.checkAvailableUtxos(payAddress, pendingSelectionUtxos, false, assetUnit);
if (undefined === availableUtxos) {
return undefined;
}
// this.logger.debug("..PlutusTxBuilder......checkAvailableUtxos: ", availableUtxos, amount);
// to coin select utxos
let filtedUtxo = this.selectUtxos(availableUtxos, toAddress, amount, limit);
// this.logger.debug("..PlutusTxBuilder......selectUtxos filtedUtxo: ", filtedUtxo);
// to update selected utxos status to pendingConsumed
let selectedUtxos = new Array();
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(payAddress);
let encUtxo = this.commonUtil.encodeUtxo(utxoObj);
let utxoId = encUtxo.input().to_hex();
mapConsumedUtxos.set(utxoId, this.curChainTip.slot);
this.mapPendingConsumedUTXO.set(payAddress, mapConsumedUtxos);
break;
}
}
}
this.logger.debug("..PlutusTxBuilder......selectUtxos ret: ", selectedUtxos.length);
let ret = {
"selectedUtxos": selectedUtxos,
"totalUtxos": utxos
}
return ret;
}
async getScriptRefUtxoByVH(checkVH) {
let refUtxo = await this.getUtxo(this.scriptRefOwnerAddr, false);
// this.logger.debug(`..PlutusTxBuilder....getScriptRefUtxoByVH ${refUtxo.length} utxos of scriptRefOwner: ${this.scriptRefOwnerAddr} `);
const ref = refUtxo.find(o => {
const buf = Buffer.from(o.script['plutus:v2'], 'hex');
const cborHex = cbor.encode(buf, 'buffer');
return CardanoWasm.PlutusScript.from_bytes_v2(cborHex).hash().to_hex() == checkVH
});
if (undefined === ref) {
return undefined;
}
// this.logger.debug(`..PlutusTxBuilder.... getScriptRefUtxoByVH's ref-utxo: ${JSON.stringify(ref)} `);
return ref;
}
async getScriptRefUtxo(script) {
let refUtxo = await this.getUtxo(this.scriptRefOwnerAddr, false);
// this.logger.debug(`..PlutusTxBuilder....get ${refUtxo.length} utxos of scriptRefOwner: ${this.scriptRefOwnerAddr} `);
const ref = refUtxo.find(o => script.to_hex().indexOf(o.script['plutus:v2']) >= 0);
if (undefined === ref) {
return undefined;
}
// this.logger.debug(`..PlutusTxBuilder.... scriptRefOwner's ref-utxo: ${JSON.stringify(ref)} `);
return ref;
}
signFn(hash) {
const payPrvKey = CardanoWasm.PrivateKey.from_normal_bytes(Buffer.from(this.paymentSkey, 'hex'));
const signature = payPrvKey.sign(Buffer.from(hash, 'hex')).to_hex();
const vkey = payPrvKey.to_public().to_bech32();
// this.logger.debug("..PlutusTxBuilder......signFn: ", vkey, signature);
return { vkey, signature };
}
async evaluateFn(rawTx) {
// add exception catch for connector
try {
return await this.connector.evaluateTx(CardanoWasm.Transaction.from_hex(rawTx).to_bytes());
} catch (e) {
this.logger.debug("..PlutusTxBuilder......evaluateTx error: ", e);
throw e;
}
}
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(`..PlutusTxBuilder..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("..PlutusTxBuilder...release origin mapConsumedUtxos: ", address, mapConsumedUtxos);
if (mapConsumedUtxos.get(utxoId)) {
// this.logger.debug(`..PlutusTxBuilder..release utxoId: #${utxoId} in pendingUtxo of address: ${address}`);
mapConsumedUtxos.delete(utxoId);
this.mapPendingConsumedUTXO.set(address, mapConsumedUtxos);
this.logger.debug("..PlutusTxBuilder...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(`..PlutusTxBuilder...release utxo: ${utxoItem.txId + '#' + utxoItem.index}`);
}
this.revertUtxoPendingComsumedStatus(revertedUtxos);
}
parseTreasuryUtxoChangeData(balancedParseRet, transferAmount, tokenAmount) {
let datum = CardanoWasm.PlutusData.new_empty_constr_plutus_data(CardanoWasm.BigNum.from_str('0'));
let bnOutputNum = CardanoWasm.BigNum.from_str(this.commonUtil.number2String(balancedParseRet.outputNum));
let formatUtxos = this.commonUtil.formatUtxoData(balancedParseRet.coordinateUtxos);
let totalInputAmount = this.caculateInputValue(formatUtxos);
let bnInputCoinValue = totalInputAmount.coin;
let adaAmount = CardanoWasm.BigNum.from_str('0');
let marginAda = CardanoWasm.BigNum.from_str('0');
if ("lovelace" === transferAmount.unit) {
console.log("\n..parseTreasuryUtxoChangeData transfer ada: ", transferAmount);
const minAda = this.commonUtil.getMinAdaOfUtxo(this.protocolParams, this.paymentAddress, { coins: transferAmount.amount, assets: {} }, datum);
let bnMinAda = CardanoWasm.BigNum.from_str(this.commonUtil.number2String(minAda));
console.log("\n..parseTreasuryUtxoChangeData bnMinAda: ", bnMinAda.to_str(), bnTransferValue.to_str(), bnInputCoinValue.to_str());
const bnTransferValue = CardanoWasm.BigNum.from_str(this.commonUtil.number2String(transferAmount.amount));
if (0 === bnInputCoinValue.compare(bnTransferValue)) {
console.log("\n..parseTreasuryUtxoChangeData bnInputCoinValue is equle with bnTransferValue: ", bnTransferValue.to_str());
bnOutputNum = CardanoWasm.BigNum.from_str('0');
adaAmount = bnTransferValue;
} else if (1 === bnInputCoinValue.compare(bnTransferValue)) {
console.log("\n..parseTreasuryUtxoChangeData bnInputCoinValue is large than bnTransferValue: ", bnTransferValue.to_str(), bnInputCoinValue.to_str());
let unitOutputAda = bnInputCoinValue.checked_sub(bnTransferValue).div_floor(bnOutputNum);
console.log("\n..parseTreasuryUtxoChangeData unitOutputAda: ", bnOutputNum.to_str(), unitOutputAda.to_str());
// if not enough for split, then not to balanced
if (-1 === unitOutputAda.compare(bnMinAda)) {
console.log("\n..parseTreasuryUtxoChangeData unitOutputAda is smaller than minAda: ", unitOutputAda.to_str(), bnMinAda.to_str());
marginAda = bnMinAda.checked_sub(unitOutputAda).checked_mul(bnOutputNum);
console.log("\n..parseTreasuryUtxoChangeData marginAda: ", marginAda.to_str());
}
adaAmount = bnTransferValue;
} else {
console.log("\n..parseTreasuryUtxoChangeData bnInputCoinValue is not enough for bnTransferValue: ", bnTransferValue.to_str(), bnInputCoinValue.to_str());
this.logger.debug("..parseTreasuryUtxoChangeData bnInputCoinValue is not enough for bnTransferValue: ", bnTransferValue.to_str(), bnInputCoinValue.to_str());
return undefined;
}
console.log("\n..parseTreasuryUtxoChangeData transfer ada: ", marginAda.to_str(), adaAmount.to_str(), bnOutputNum.to_str());
} else {
const tokenUnit = transferAmount.unit + "." + transferAmount.name;
const minBindAda = this.commonUtil.getMinAdaOfUtxo(this.protocolParams, this.paymentAddress, { coins: 0, assets: { [tokenUnit]: transferAmount.amount } }, datum);
const bnMinBindAda = CardanoWasm.BigNum.from_str(this.commonUtil.number2String(minBindAda));
const bnInputAssetValue = totalInputAmount.asset.get(tokenUnit.replace(".", ""));
const bnTransferValue = CardanoWasm.BigNum.from_str(this.commonUtil.number2String(tokenAmount));
if (0 === bnInputAssetValue.compare(bnTransferValue)) {
bnOutputNum = CardanoWasm.BigNum.from_str('0');
if (0 === bnInputCoinValue.compare(bnMinBindAda)) {
// bnOutputNum = CardanoWasm.BigNum.from_str('0');
adaAmount = bnMinBindAda;
} else {
const minAda = this.commonUtil.getMinAdaOfUtxo(this.protocolParams, this.paymentAddress, { coins: "10000000", assets: {} }, datum);
let bnMinAda = CardanoWasm.BigNum.from_str(this.commonUtil.number2String(minAda));
let changeAda = bnInputCoinValue.checked_sub(bnMinBindAda);
if (-1 === changeAda.compare(bnMinAda)) {
// in this case, changeAda should be filled in bindAda
adaAmount = bnInputCoinValue;
} else {
adaAmount = bnMinBindAda;
}