-
Notifications
You must be signed in to change notification settings - Fork 0
/
plutusNftTxBuilder.js
1483 lines (1272 loc) · 69.3 KB
/
plutusNftTxBuilder.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
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 Cbor = require('cbor-sync');
const UtxoSelectionService = require('./bizServices/utxoSelectionService');
const NftContractService = require('./bizServices/nftContractService');
class PlutusNftTxBuilder {
constructor(chainConnector, scriptRefOwnerAddr, utxosManager, logUtil, bMainnet) {
this.connector = chainConnector;
this.scriptRefOwnerAddr = scriptRefOwnerAddr;
this.bMainnet = bMainnet;
this.utxosManagerObj = utxosManager;
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.mapMultiAssetUTXO = new Map();
this.mapAccountLocker = new Map();
// supportted token
this.mapValidAssetType = new Map();
// to new common util instance
this.commonUtil = new Common(this.ADDR_PREFIX);
this.utxoSelectionService = new UtxoSelectionService(this.ADDR_PREFIX);
this.contractService = new NftContractService(bMainnet, this.ADDR_PREFIX, logUtil);
this.logger = logUtil;
}
async init() {
let stakeCred = await this.getGroupInfoStkVh();
this.lockerScAddress = this.contractService.getLockerScAddress(stakeCred);
// this.lockerScAddress = "addr_test1qq0rlnqmmmrl4wzy35nt0pzsuu88h78swk4wnjrpzy8yk62mqlt3z2733rdlarwrd0l9sgx5t99qgsejv52qrzwmm8hqfvmgam";
console.log("\n\n..init...this.lockerScAddress: ", this.lockerScAddress);
this.signMode = this.contractService.getSignMode();
this.validPolicyId = this.contractService.getValidPolicyId();
this.utxosManagerObj.setNftTreasuryScAddress(this.lockerScAddress);
console.log("\n\n\n\******* this.lockerScAddress: ", this.lockerScAddress);
}
//////////////////////////////////////////
//// PART 1: plutus contracts related api
//////////////////////////////////////////
async checkNFTRefAssets(refAssetHolder, refAssets) {
let mapAssetAvailable = new Map();
for (let j = 0; j < refAssets.length; j++) {
let assetUnit = refAssets[j];
mapAssetAvailable.set(assetUnit, false);
}
let utxos = await this.utxosManagerObj.getUtxo(refAssetHolder, false);
for (let i = 0; i < utxos.length; i++) {
/*
{
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 itemAssets = utxos[i].value.assets;
for (let assetUnit of itemAssets.keys()) {
let index = refAssets.indexOf(assetUnit);
if (-1 !== index) {
mapAssetAvailable.set(assetUnit, true);
}
}
}
return mapAssetAvailable;
}
genNFTAssetName(name, typeCode) {
let ret = this.commonUtil.genNFTAssetName(name, typeCode);
return ret;
}
getNFTRefHolderScript() {
// need to check whether this hold address is given by sc sdk?? or transfer by agent??
let nftRefHolderAddr = this.contractService.getRefHolderScript();
return nftRefHolderAddr;
}
async genRedeemProofHash(proofInfo) {
try {
if (undefined === this.groupInfoToken) {
this.groupInfoToken = await this.getGroupInfoToken();
// this.logger.debug("..PlutusNftTxBuilder......genRedeemProofHash()... init groupInfoToken: ", this.groupInfoToken);
if (false === this.groupInfoToken) {
throw "network exception";
}
this.groupPK = this.contractService.getGroupPublicKey(this.groupInfoToken.datum);
}
let redeemerProof = {
to: proofInfo.to,
crossValue: proofInfo.crossValue,
txHash: proofInfo.txHash,
index: proofInfo.index,
mode: this.signMode,
signature: '',
// pk: this.groupPK,
uniqueId: proofInfo.uniqueId,
policy_id: proofInfo.policyId,
txType: proofInfo.txType,
ttl: proofInfo.ttl
}
// this.logger.debug("..PlutusNftTxBuilder......genRedeemProofHash redeemerProof: ", JSON.stringify(redeemerProof, null, 0))
let redeemProofHash = this.contractService.caculateRedeemDataHash(redeemerProof, false);
this.logger.debug("..PlutusNftTxBuilder......genRedeemProofHash caculateRedeemDataHash: ", redeemProofHash);
return redeemProofHash;
} catch (e) {
this.logger.error("..PlutusNftTxBuilder...genRedeemProofHash...catch error : ", e);
throw e;
}
}
async genTokenRedeemProofHash(proofInfo) {
try {
if (undefined === this.groupInfoToken) {
this.groupInfoToken = await this.getGroupInfoToken();
// this.logger.debug("..PlutusNftTxBuilder......genRedeemProofHash()... init groupInfoToken: ", this.groupInfoToken);
if (false === this.groupInfoToken) {
throw "network exception";
}
this.groupPK = this.contractService.getGroupPublicKey(this.groupInfoToken.datum);
}
let redeemerProof = {
to: proofInfo.to,
// crossValue: proofInfo.crossValue,
txHash: proofInfo.txHash,
index: proofInfo.index,
mode: this.signMode,
signature: '',
// pk: this.groupPK,
uniqueId: proofInfo.uniqueId,
nftAssets: proofInfo.nftAssets,
nftRefAssets: proofInfo.nftRefAssets,
userData: proofInfo.userData,
ttl: proofInfo.ttl
}
// this.logger.debug("..PlutusNftTxBuilder......genRedeemProofHash redeemerProof: ", JSON.stringify(redeemerProof, null, 0))
let redeemProofHash = this.contractService.caculateRedeemDataHash(redeemerProof, true);
this.logger.debug("..PlutusNftTxBuilder......genTokenRedeemProofHash caculateRedeemDataHash: ", redeemProofHash);
return redeemProofHash;
} catch (e) {
this.logger.error("..PlutusNftTxBuilder...genTokenRedeemProofHash...catch error : ", e);
throw e;
}
}
async deCodeTxRedeemersCbor(txInfo, bMintCheck) {
// this.logger.debug("..PlutusNftTxBuilder...", txInfo.hash, "...deCodeTxRedeemersCbor txInfo: ", txInfo);
// add exception catch for connector
let txUtxos;
try {
txUtxos = await this.connector.txsUtxos(txInfo.hash);
// this.logger.debug("..PlutusNftTxBuilder...deCodeTxRedeemersCbor...tx utxos: ", txUtxos);
} catch (e) {
this.logger.debug("..PlutusNftTxBuilder...deCodeTxRedeemersCbor...get txsUtxos...error: ", e);
throw e;
}
let redeemer = this.contractService.deCodeTxRedeemersCbor(txUtxos, bMintCheck);
return redeemer;
}
checkIfContainTreasuryUtxo(txInputUtxos) {
let bContained = false;
// to get treasury sc address
if (undefined === this.lockerScAddress) {
throw "failed to initial sdk!";
}
// to check if contains treasury utxos
for (let i = 0; i < txInputUtxos.length; i++) {
let utxoOwner = txInputUtxos[i].address;
if (this.lockerScAddress === utxoOwner) {
bContained = true;
break;
}
}
return bContained;
}
async getTreasuryCheckRefAndAvailableUtxo(checkVH, bMintCheck) {
// Step 1: treasuryCheckRefUtxo
let treasuryCheckRef = await this.getScriptRefUtxoByVH(checkVH);
console.log("\n..getTreasuryCheckRefAndAvailableUtxo treasuryCheckRef: ", treasuryCheckRef);
if (undefined === treasuryCheckRef) {
this.logger.debug("..PlutusNftTxBuilder...getScriptRefUtxo...error:: no available check ref utxo");
return undefined;
}
// Step 2: treasuryCheckUxto : to monitor this script check utxos
let scriptCheckRefAddress = await this.getTreasuryCheckAddress(bMintCheck);
console.log("\n..getTreasuryCheckRefAndAvailableUtxo scriptCheckRefAddress: ", scriptCheckRefAddress);
let treasuryCheckUxto = await this.getScriptCheckRefAvailableUtxo(scriptCheckRefAddress);
console.log("\n..getTreasuryCheckRefAndAvailableUtxo treasuryCheckUxto: ", treasuryCheckUxto);
if (undefined === treasuryCheckUxto) {
this.logger.debug("..PlutusNftTxBuilder...getScriptCheckRefAvailableUtxo...warning:: no available check utxo");
return undefined;
}
let ret = {
"checkUtxo": treasuryCheckUxto,
"checkRef": treasuryCheckRef
}
return ret;
}
async getTreasuryCheckUtxosTotalNum(bMintCheck) {
let scriptCheckRefAddress = await this.getTreasuryCheckAddress(bMintCheck);
let availableCheckUtxoCount = 0;
let utxos = await this.utxosManagerObj.getUtxo(scriptCheckRefAddress, false);
for (let i = 0; i < utxos.length; i++) {
let utxoItem = {
"txId": utxos[i].txHash,
"index": utxos[i].index
}
// this.logger.debug(`..PlutusNftTxBuilder...release utxo: ${utxoItem.txId + '#' + utxoItem.index}`);
let transaction_id = CardanoWasm.TransactionHash.from_bytes(Buffer.from(utxoItem.txId, 'hex'));
let txInput = CardanoWasm.TransactionInput.new(transaction_id, utxoItem.index);
// to generate utxoId by txInput
let utxoId = txInput.to_hex();
// this.logger.debug(`..PlutusNftTxBuilder..getTreasuryCheckUtxosTotalNum...to match Key: ${utxoId}`);
let mapConsumedUtxos = this.utxosManagerObj.getPendingComsumedUtxoByAddress(scriptCheckRefAddress);
if (mapConsumedUtxos.get(utxoId)) {
// this.logger.debug(`..PlutusNftTxBuilder..release utxoId: #${utxoId} in pendingUtxo of address: ${address}`);
continue;
};
availableCheckUtxoCount++;
}
this.logger.debug("..PlutusNftTxBuilder...availalbe check utxos num: ", bMintCheck, scriptCheckRefAddress, availableCheckUtxoCount);
return availableCheckUtxoCount;
}
async getScriptCheckRefAvailableUtxo(scriptCheckRefAddress) {
let utxos = await this.utxosManagerObj.getUtxo(scriptCheckRefAddress, false);
this.logger.debug("..PlutusNftTxBuilder......get scriptCheckRef utxos: ", scriptCheckRefAddress, utxos.length);
if (0 === utxos.length) {
this.logger.debug("..PlutusNftTxBuilder.....warning: get no scriptCheckRef utxos.");
return undefined;
}
let availableUtxos = this.utxosManagerObj.checkAvailableUtxos(scriptCheckRefAddress, utxos, true);
// this.logger.debug("..PlutusNftTxBuilder......availableUtxos: ", availableUtxos);
if ((undefined === availableUtxos) || (availableUtxos.length < 1)) {
this.logger.debug("..PlutusNftTxBuilder...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("..PlutusNftTxBuilder......selected availableUtxos: ", utxo);
// to add new pending consumed utxos for scriptCheckRefAddress
this.utxosManagerObj.appendPendingComsumedUtxo(scriptCheckRefAddress, availableUtxos[0], this.curChainTip.slot);
break;
}
}
return treasuryCheckUxto;
}
async getScriptRefUtxoByVH(checkVH) {
let refUtxo = await this.utxosManagerObj.getUtxo(this.scriptRefOwnerAddr, false);
console.log(`..PlutusNftTxBuilder....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
});
console.log(`..PlutusNftTxBuilder....getScriptRefUtxoByVH result: ${ref} `);
if (undefined === ref) {
return undefined;
}
// this.logger.debug(`..PlutusNftTxBuilder.... getScriptRefUtxoByVH's ref-utxo: ${JSON.stringify(ref)} `);
return ref;
}
async getScriptRefUtxo(script) {
let refUtxo = await this.utxosManagerObj.getUtxo(this.scriptRefOwnerAddr, false);
// this.logger.debug(`..PlutusNftTxBuilder....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(`..PlutusNftTxBuilder.... scriptRefOwner's ref-utxo: ${JSON.stringify(ref)} `);
return ref;
}
getLockerScAddress() {
// this.lockerScAddress = this.contractService.getLockerScAddress(stakeCred);
return this.lockerScAddress;
}
getValidPolicyId() {
// this.validPolicyId = this.contractService.getValidPolicyId();
return this.validPolicyId
}
addressToPkhOrScriptHash(address) {
let phk = this.contractService.addressToPkhOrScriptHash(address);
return phk;
}
async getGroupInfoToken() {
const groupInfo = this.contractService.getGroupInfoHolder();
const groupInfoHolder = groupInfo.groupHolder;
const expectedTokenId = groupInfo.tokenId;
console.log("..getGroupInfoToken: ", groupInfo);
const groupInfoToken = (await this.utxosManagerObj.getUtxo(groupInfoHolder)).find(o => {
console.log("utxosManager get utxo ret: ", groupInfoHolder, o);
for (let tokenId in o.value.assets) {
tokenId = tokenId.replace(".", "");
console.log("utxosManager tokenId: ", tokenId);
if (tokenId == expectedTokenId) return true;
}
return false;
});
//this.logger.debug("..PlutusNftTxBuilder......groupInfoToken ", groupInfoToken);
if (undefined === groupInfoToken) {
return false;
}
console.log("..getGroupInfoToken groupInfoToken: ", groupInfoToken);
return groupInfoToken;
}
async getGroupInfoStkVh() {
this.groupInfoToken = await this.getGroupInfoToken();
//this.logger.debug("..PlutusNftTxBuilder......getGroupInfoToken...: ", this.groupInfoToken);
console.log("..groupInfoToken: ", this.groupInfoToken);
if (false === this.groupInfoToken) {
throw "getGroupInfoStkVh: exception network during get group info token";
}
let StkVh = this.contractService.getGroupInfoStkVh(this.groupInfoToken.datum);
//this.logger.debug("..PlutusNftTxBuilder......groupInfoFromDatum...StkVh: ", StkVh);
console.log("..getGroupInfoToken StkVh: ", StkVh);
return StkVh;
}
async getTreasuryCheckAddress(bMintCheck) {
this.groupInfoToken = await this.getGroupInfoToken();
// this.logger.debug("..PlutusNftTxBuilder......getGroupInfoToken...: ", this.groupInfoToken);
if (false === this.groupInfoToken) {
throw "getTreasuryCheckAddress: exception network during get group info token";
}
let checkAddress = this.contractService.getTreasuryCheckAddress(bMintCheck, this.groupInfoToken.datum);
return checkAddress;
}
//////////////////////////////////////////////////////
//// PART 2: to fetch online data from ogmios service
//////////////////////////////////////////////////////
async convertSlotToTimestamp(slot) {
try {
const eraSummaries = await this.connector.queryEraSummaries();
const genisis = await this.connector.queryGenesisConfig();
return this.commonUtil.slotToTimestamp(slot, eraSummaries, genisis);
} catch (err) {
throw `convertSlotToTimestamp failed: ${err}`;
}
}
async getCurChainParams() {
let latestChainTip = undefined;
try {
latestChainTip = await this.connector.chainTip();
// this.logger.debug("..PlutusNftTxBuilder......latestChainTip: ", latestChainTip);
} catch (e) {
this.logger.debug("..PlutusNftTxBuilder......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("..PlutusNftTxBuilder......this.curLatestBlock: ", this.curLatestBlock);
} catch (e) {
this.logger.debug("..PlutusNftTxBuilder......get blocksLatest failed: ", e);
this.mapAccountLocker.set("latestChainStatusLocker", false);
return false;
}
try {
let tmpProtocolParams = await this.connector.getCurrentProtocolParameters();
// this.logger.debug("..PlutusNftTxBuilder......protocolParams: ", this.protocolParams);
if ((undefined === tmpProtocolParams) || ("" === tmpProtocolParams)) {
this.logger.debug("..PlutusNftTxBuilder......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("..PlutusNftTxBuilder......getCurChainParams failed: ", e);
this.mapAccountLocker.set("latestChainStatusLocker", false);
return false;
}
try {
this.curChainTip = await this.connector.chainTip();
this.logger.debug("..PlutusNftTxBuilder......get this.curChainTip onchain: ", this.curChainTip);
} catch (e) {
this.logger.debug("..PlutusNftTxBuilder......get chainTip failed: ", e);
this.mapAccountLocker.set("latestChainStatusLocker", false);
return false;
}
}
this.mapAccountLocker.set("latestChainStatusLocker", false);
return true;
}
async confirmTx(txHash) {
if (undefined === this.lockerScAddress) {
throw "failed to initial sdk!";
}
// this.logger.debug("..PlutusNftTxBuilder...", txHash, "...confirmTx...lockerScAddress: ", this.lockerScAddress);
let mapConsumedUtxos = this.utxosManagerObj.getPendingComsumedUtxoByAddress(this.lockerScAddress);
if (undefined === mapConsumedUtxos) {
// this.logger.debug("..PlutusNftTxBuilder...", txHash, "...confirmTx...no pending utxos for: ", this.lockerScAddress);
return;
}
// add exception catch for connector
let txUtxos;
try {
txUtxos = await this.connector.txsUtxos(txHash);
// this.logger.debug("..PlutusNftTxBuilder...", txHash, "...confirmTx...tx utxos: ", txUtxos);
} catch (e) {
this.logger.debug("..PlutusNftTxBuilder...", txHash, "...confirmTx...get txsUtxos...error: ", e);
throw e;
}
for (let j = 0; j < txUtxos.inputs.length; j++) {
const tmp = txUtxos.inputs[j];
if (tmp.address === this.lockerScAddress) {
// to generate tx input based on txId&index
let transaction_id = CardanoWasm.TransactionHash.from_bytes(Buffer.from(tmp.tx_hash, 'hex'));
let txInput = CardanoWasm.TransactionInput.new(transaction_id, tmp.output_index);
// to generate utxoId by txInput
let utxoId = txInput.to_hex();
// this.logger.debug("..PlutusNftTxBuilder...", txHash, "...confirmTx...pending list remove utxoId : ", utxoId);
// mapConsumedUtxos.delete(utxoId);
this.utxosManagerObj.deletePendingComsumedUtxoById(this.lockerScAddress, utxoId);
}
}
}
revertUtxoPendingComsumedStatus(inputUtxos) {
this.utxosManagerObj.revertUtxoPendingComsumedStatus(inputUtxos);
}
////////////////////////////////////////////
//// PART 4: build cross-chain tx raw data
////////////////////////////////////////////
async buildSignedTx(basicArgs, internalSignFunc, partialRedeemerArgs) {
this.logger.debug("..PlutusNftTxBuilder...buildSignedTx......basicArgs:", basicArgs);
if (undefined === this.lockerScAddress) {
throw "failed to initial sdk!";
}
//this.logger.debug("..PlutusNftTxBuilder...buildSignedTx......partialRedeemerArgs:", partialRedeemerArgs);
this.logger.debug("..PlutusNftTxBuilder...", basicArgs.hashX, "...begin to build Signed Tx! ");
this.paymentAddress = basicArgs.paymentAddress;
this.paymentSkey = basicArgs.paymentSKey;
// to add leader address for utxo manager
this.utxosManagerObj.setSmgLeaderAddress(this.paymentAddress);
this.utxosManagerObj.setNftTreasuryScAddress(this.lockerScAddress);
//Step 1: to get groupInfoToken and fetch group pk
let encodedGpk = this.commonUtil.encodeGpk(basicArgs.gpk);
// this.logger.debug("..PlutusNftTxBuilder...", basicArgs.hashX, "...this.groupInfoToken: ", this.groupInfoToken);
if (this.groupPK !== encodedGpk) {
// {
this.groupInfoToken = await this.getGroupInfoToken();
// this.logger.debug("..PlutusNftTxBuilder...", basicArgs.hashX, "...getGroupInfoToken...: ", this.groupInfoToken);
console.log("...getGroupInfoToken...: ", this.groupInfoToken);
if (false === this.groupInfoToken) {
throw "getGroupInfoToken: exception network during get group info token";
}
this.groupPK = this.contractService.getGroupPublicKey(this.groupInfoToken.datum);
// this.logger.debug("..PlutusNftTxBuilder...", basicArgs.hashX, "...groupInfoFromDatum...groupPK: ", this.groupPK);
console.log("...groupInfoFromDatum...groupPK: ", this.groupPK);
if (this.groupPK !== encodedGpk) {
throw "inconsistent gpk";
}
}
console.log("\n\n... this.groupPK: ", this.groupPK);
// Step 2: to get cardano current netParams
let bRet = await this.getCurChainParams();
// this.logger.debug("..PlutusNftTxBuilder...", basicArgs.hashX, "...getCurChainParams......bRet:", bRet);
if (false === bRet) {
throw "exception network during update protocal params";
}
// Step 3: to build cardano cross-chain tx
let signedTx = await this.genSignedTxData(basicArgs, partialRedeemerArgs, internalSignFunc);
// this.logger.debug("..PlutusNftTxBuilder...", basicArgs.hashX, "...genSignedTxData......ret:", signedTx);
return signedTx;
}
async genSignedTxData(basicArgs, partialRedeemerArgs, internalSignFunc) {
// this.logger.debug("..PlutusNftTxBuilder...", basicArgs.hashX, "...basicArgs: ", basicArgs);
const owner = basicArgs.crossAddress;
// to confirm transfer asset value
const datum = CardanoWasm.PlutusData.new_empty_constr_plutus_data(CardanoWasm.BigNum.from_str('0'));
/* Modify By NFT Program:
need to extend tokenId&tokenAmount to support multi-nft-tokens
transferAmount:{
tokenId_1: strTokenAmount_1,
...
tokenId_n: strTokenAmount_n,
}
*/
// assets: { [tokenId]: tokenAmount }
const minAda = this.commonUtil.getMinAdaOfUtxo(this.protocolParams,
owner,
{ coins: 0, assets: basicArgs.transferAmount },
datum);
// this.logger.debug("..PlutusNftTxBuilder...", basicArgs.hashX, "...getMinAdaOfUtxo: ", minAda, typeof (minAda));
console.log("..PlutusNftTxBuilder......getMinAdaOfUtxo: ", minAda, typeof (minAda));
// to build & sign normal cc tx or token mint tx by basciArgs params
let buildRet = undefined;
if (!basicArgs.bMint) {
buildRet = await this.buildAndSignNftRawTx(internalSignFunc,
basicArgs,
minAda,
partialRedeemerArgs);
} else {
buildRet = await this.buildAndSignNftMintRawTx(internalSignFunc,
basicArgs,
minAda,
partialRedeemerArgs);
}
this.logger.debug("..PlutusNftTxBuilder...", basicArgs.hashX, "...buildAndSignRawTx...signedTxData: ", buildRet);
return buildRet;
}
async buildAndSignNftRawTx(internalSignFunc, basicArgs, minAda, partialRedeemerArgs) {
// this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...buildAndSignNftRawTx current slot: ", this.curChainTip.slot);
const to = basicArgs.crossAddress;
const metaData = basicArgs.metaData;
const uniqueId = basicArgs.hashX;
// Step 1: to get treasury utxos for ccTask
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...this.lockerScAddress: ", this.lockerScAddress);
// Step 1-1: to coin select treasury utxos for transfer
let transferAmount = new Array();
/* Modify By NFT Program:
need to extend tokenId&tokenAmount to support multi-nft-tokens,
format is just like:
transferAmount:{
tokenId_1: tokenAmount_1,
...
tokenId_n: tokenAmount_n,
}
*/
let nftPolicyId = "";
const objNftAmount = basicArgs.transferAmount;
for (let tokenId in objNftAmount) {
let tokenAmount = objNftAmount[tokenId];
let [policyId, name] = tokenId.split(".");
let strTokenAmount = this.commonUtil.number2String(tokenAmount);
let bnTokenAmount = CardanoWasm.BigNum.from_str(strTokenAmount);
nftPolicyId = policyId;
let amountItem = {
"unit": policyId,
"name": name,
"amount": bnTokenAmount.to_str()
};
transferAmount.push(amountItem);
}
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...transferAmount: ", transferAmount);
// step 1-2: to select nft utxo for ccTask
/* Modify By NFT Program:
need to check if coinselection can handle multi-types utxo selection -- done!!
*/
let contractUtxoRet = undefined;
do {
contractUtxoRet = await this.utxosManagerObj.getNftUtxoOfAmount(this.lockerScAddress,
to,
transferAmount,
Config.PlutusCfg.maxUtxoNum,
uniqueId,
true);
if (undefined === contractUtxoRet) {
throw "failed to get treasury utxos for uniqueId: " + uniqueId;
}
console.log("\n\n....getNftUtxoOfAmount...contractUtxoRet: ", contractUtxoRet.checkStatus, contractUtxoRet.marginAmount);
// in case the task takes reserved utxo with pending available status
if (("PendingAvailable" === contractUtxoRet.checkStatus)
|| ("NoAvailable" === contractUtxoRet.checkStatus)) {
this.commonUtil.sleep(10 * 1000);
continue;
}
// in case there are enough available utxos for this task
if ("Available" === contractUtxoRet.checkStatus) {
break;
}
// in case need to merge more utxos based on preReserved utxo,
if ("InSufficent" === contractUtxoRet.checkStatus) {
// step 1-3: in case of no suitable nft utxo
/* Modify By NFT Program:
in case of no any utxo for this kind nft, need to balance nft utxos for cctask
*/
let ret = this.selectBalanceNftUtxos(contractUtxoRet.selectedUtxos, contractUtxoRet.totalUtxos, contractUtxoRet.marginAmount);
if (undefined !== ret) {
// let ret = {
// "selectedUtxos": selectedNftUtxos,
// "marginAmount": marginNftAmount,
// "targetAmount": targetNftAmount,
// }
if ((0 === ret.marginAmount.length) && (Config.PlutusCfg.maxUtxoNum >= ret.selectedUtxos.length)) {
// in case coinselection is failed and there are enough available utxos for task
contractUtxoRet.selectedUtxos = ret.selectedUtxos;
break;
} else {
let mergedTxId = await this.handleNftUtxosBalance(internalSignFunc, ret.selectedUtxos, ret.targetAmount, uniqueId, nftPolicyId);
if (undefined === mergedTxId) {
console.log("\n\n...handleNftUtxosBalance mergedTxId is undefined! ");
// throw "handle nft utxos merging failed for uniqueId: " + uniqueId;
}
}
}
}
this.commonUtil.sleep(5 * 1000);
} while (true);
// Step 1-4: combine selectedUtxos with target balanced utxos
////// Step 2-5: to get utxos for fee && collateral
/* Modify By NFT Program:
need to expend the parseTreasuryUtxoChangeData params to support multi-nft transfer amount
this.protocolParams,
formatedUtxos,
transferNftAmount,
this.lockerScAddress);
*/
let treasuryUtxo = contractUtxoRet.selectedUtxos;
let treasuryUtxoChangeInfo = this.commonUtil.parseTreasuryNftUtxoChangeData(
this.protocolParams,
treasuryUtxo,
transferAmount,
this.lockerScAddress);
if (undefined === treasuryUtxoChangeInfo) {
this.utxosManagerObj.releaseUtxos(treasuryUtxo);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury Utxo.");
throw "coin select treasury utxo amount is not enough for transferAmount for uniqueId: " + uniqueId;
}
// let txOutputNum = treasuryUtxoChangeInfo.outputNum;
let marginAda = treasuryUtxoChangeInfo.marginAda;
// let adaAmount = treasuryUtxoChangeInfo.mergedBindAda;
// let mapMergedAmount = treasuryUtxoChangeInfo.mergedAmount;
console.log("\n\n...parseTreasuryNftUtxoChangeData treasuryUtxoChangeInfo: ", treasuryUtxoChangeInfo);
// Step 2: to get treasury data
// Step 2-1: treasuryCheckRef&&Uxto
const treasuryCheckVH = this.contractService.getTreasuryCheckVH(this.groupInfoToken.datum);
if (undefined == treasuryCheckVH) {
this.utxosManagerObj.releaseUtxos(treasuryUtxo);
throw "failed to get treasury check VH for uniqueId: " + uniqueId;
}
let checkRefData = await this.getTreasuryCheckRefAndAvailableUtxo(treasuryCheckVH, false);
if (undefined == checkRefData) {
this.utxosManagerObj.releaseUtxos(treasuryUtxo);
throw "empty treasury check ref utxo for uniqueId: " + uniqueId;
}
let treasuryCheckUxto = checkRefData.checkUtxo;
let treasuryCheckRef = checkRefData.checkRef;
// Step 2-2: treasury Ref utxo
// NFT program modify: getTreasuryScript --> getNftTreasuryScript
const treasuryScript = this.contractService.getTreasuryScript();
let treasuryRef = await this.getScriptRefUtxo(treasuryScript);
if (undefined === treasuryRef) {
this.utxosManagerObj.releaseUtxos(treasuryUtxo);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury Utxo.");
this.utxosManagerObj.releaseUtxos(treasuryCheckUxto);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury check Utxo");
throw "empty treasury ref utxo for uniqueId: " + uniqueId;
}
this.logger.debug("..PlutusNftTxBuilder...",
uniqueId,
`...transferValue Treasury ref utxo: ${treasuryRef.txHash + '#' + treasuryRef.index}`);
// Step 3: to get payment from leader
let feeValue = new Array();
let feeAmount = CardanoWasm.BigNum.from_str("5000000").checked_add(marginAda);
let valueItem = {
"unit": "lovelace",
"name": "",
"amount": feeAmount.to_str()
};
feeValue.push(valueItem);
// this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...begin feeValue: ", feeValue);
let paymentUtxosRet = await this.utxosManagerObj.getUtxoOfAmount(this.paymentAddress,
to,
feeValue,
undefined);
if (undefined === paymentUtxosRet) {
this.utxosManagerObj.releaseUtxos(treasuryUtxo);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury Utxo.");
this.utxosManagerObj.releaseUtxos(treasuryCheckUxto);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury check Utxo.");
throw "failed to get leader utxos for fee for uniqueId: " + uniqueId;
}
let utxosForFee = paymentUtxosRet.selectedUtxos;
if (0 === utxosForFee.length) {
this.utxosManagerObj.releaseUtxos(treasuryUtxo);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury Utxo.");
this.utxosManagerObj.releaseUtxos(treasuryCheckUxto);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury check Utxo.");
throw "insufficent leader utxos for fee for uniqueId: " + uniqueId;
}
// this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...utxosForFee: ", utxosForFee);
//TODO:utxosForFee
let validTTL = this.curChainTip.slot + Config.MaxTxTTL;
const nonce = {
"txHash": treasuryCheckUxto.txHash, // "9caaf865d51fc7ce403f624a260f397c0d1ac6512ebe50809d7cb09932b1d007", //
"index": treasuryCheckUxto.index // 0 //
};
let ttl2Ts = validTTL;
try {
ttl2Ts = await this.convertSlotToTimestamp(validTTL);
} catch (err) {
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...convertSlotToTimestamp failed: ", err);
this.utxosManagerObj.releaseUtxos(treasuryCheckUxto);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury check Utxo.");
this.utxosManagerObj.releaseUtxos(treasuryUtxo);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury Utxo.");
this.utxosManagerObj.releaseUtxos(utxosForFee);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release utxosForFee.");
throw err;
}
// Step 4: to get inner sign by mpc
let crossValue = {
"coins": minAda,
"assets": basicArgs.transferAmount
};
const redeemerProof = {
to, crossValue: crossValue, policy_id: nftPolicyId,
txHash: nonce.txHash, index: nonce.index, mode: this.signMode,
txType: Config.TaskType.crossTask, uniqueId: uniqueId,
signature: '', ttl: ttl2Ts
};
this.logger.debug(".....PlutusNftTxBuilder...", uniqueId, "...redeemerProof: ", JSON.stringify(redeemerProof));
const redeemProofHash = this.contractService.caculateRedeemDataHash(redeemerProof, false);
try {
this.logger.debug(".....PlutusNftTxBuilder...", uniqueId, "...caculateRedeemDataHash: ", redeemProofHash);
let signature = await internalSignFunc(partialRedeemerArgs, redeemerProof, redeemProofHash);
redeemerProof.signature = signature;
// this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...buildAndSignNftRawTx internalSignFunc: ", signature);
} catch (e) {
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...buildAndSignNftRawTx internalSignFunc exception: ", e);
this.utxosManagerObj.releaseUtxos(treasuryCheckUxto);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury check Utxo.");
this.utxosManagerObj.releaseUtxos(treasuryUtxo);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury Utxo.");
this.utxosManagerObj.releaseUtxos(utxosForFee);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release utxosForFee.");
throw e;
}
// Step 5: to build transfer value
// this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...buildAndSignNftRawTx transferValue: ", transferValue);
try {
const signedTxOutBound = await this.contractService.transferFromTreasury(this.protocolParams, utxosForFee,
treasuryUtxo, treasuryRef, this.groupInfoToken, crossValue, to, redeemerProof, utxosForFee,
treasuryCheckUxto, treasuryCheckRef, this.paymentAddress, this.evaluateFn.bind(this), this.signFn.bind(this),
metaData, validTTL);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...buildAndSignNftRawTx signedTxOutBound finished. ");
return signedTxOutBound;
} catch (e) {
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...buildAndSignNftRawTx error: ", e);
this.utxosManagerObj.releaseUtxos(treasuryCheckUxto);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury check Utxo.");
this.utxosManagerObj.releaseUtxos(treasuryUtxo);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release treasury Utxo.");
this.utxosManagerObj.releaseUtxos(utxosForFee);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release utxosForFee.");
throw e;
}
}
async buildAndSignNftMintRawTx(internalSignFunc, basicArgs, minAda, partialRedeemerArgs) {
const to = basicArgs.crossAddress;
const metaData = basicArgs.metaData;
const uniqueId = basicArgs.hashX;
const nftRefAssets = ""; //
// this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...buildAndSignNftMintRawTx current slot: ", this.curChainTip.slot);
// Step 1-1: to coin select treasury utxos for transfer
let transferAmount = new Array();
/* Modify By NFT Program:
need to extend tokenId&tokenAmount to support multi-nft-tokens,
format is just like:
transferAmount:{
tokenId_1: tokenAmount_1,
...
tokenId_n: tokenAmount_n,
}
*/
const objNftAmount = basicArgs.transferAmount;
let mappingPolicyId = "";
for (let tokenId in objNftAmount) {
let tokenAmount = objNftAmount[tokenId];
let [policyId, name] = tokenId.split(".");
let strTokenAmount = this.commonUtil.number2String(tokenAmount);
let bnTokenAmount = CardanoWasm.BigNum.from_str(strTokenAmount);
mappingPolicyId = policyId;
let amountItem = {
"name": name,
"amount": bnTokenAmount.to_str()
};
transferAmount.push(amountItem);
}
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...transferAmount: ", transferAmount);
// Step 1: to get treasury data
let mintCheckVH = this.contractService.getTreasuryMintCheckVH(this.groupInfoToken.datum);
// Step 1-1: treasuryCheckRef&&Uxto
let mintCheckRefData = await this.getTreasuryCheckRefAndAvailableUtxo(mintCheckVH, true);
if (undefined == mintCheckRefData) {
throw "empty mint check ref or utxo for uniqueId: " + uniqueId;
}
let mintCheckUxto = mintCheckRefData.checkUtxo;
let mintCheckRef = mintCheckRefData.checkRef;
const mintScript = this.contractService.getMappingTokenScript();
// this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...mint check Treasury ref utxo: ", mintCheckUxto, mintCheckRef);
// Step 1-2: treasury Ref utxo
let mappingTokenRef = await this.getScriptRefUtxo(mintScript);
if (undefined === mappingTokenRef) {
this.utxosManagerObj.releaseUtxos(mintCheckUxto);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release mint check Utxo: ", mintCheckUxto);
throw "empty mapping token script ref for uniqueId: " + uniqueId;
}
// this.logger.debug("..PlutusNftTxBuilder...", uniqueId, `...transferValue Treasury ref utxo: ${mappingTokenRef.txHash + '#' + mappingTokenRef.index}`);
// Step 2: to get leader utxos for mint fee
let feeValue = new Array();
let feeAmount = CardanoWasm.BigNum.from_str("5000000");
let valueItem = {
"unit": "lovelace",
"name": "",
"amount": feeAmount.to_str()
};
feeValue.push(valueItem);
// this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...begin feeValue: ", feeValue);
let paymentUtxosRet = await this.utxosManagerObj.getUtxoOfAmount(this.paymentAddress,
to,
feeValue,
undefined);
if (undefined === paymentUtxosRet) {
this.utxosManagerObj.releaseUtxos(mintCheckUxto);
this.logger.debug("..PlutusNftTxBuilder...", uniqueId, "...release mint check Utxo: ", mintCheckUxto);