forked from Riley-Kilgore/WorldsWithin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
1183 lines (1113 loc) · 35.1 KB
/
index.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
import Loader from "./loader.js";
import {
assetsToValue,
fromAscii,
fromHex,
getTradeDetails,
lovelacePercentage,
toBytesNum,
toHex,
valueToAssets,
} from "./utils.js";
import { languageViews } from "./languageViews.js";
import { contract } from "./plutus.js";
import CoinSelection from "./coinSelection.js";
import {
Address,
PlutusData,
TransactionUnspentOutput,
} from "./custom_modules/@emurgo/cardano-serialization-lib-browser/cardano_serialization_lib.js";
const DATUM_LABEL = 405;
const ADDRESS_LABEL = 406;
// Validator
const CONTRACT = () => {
const scripts = Loader.Cardano.PlutusScripts.new();
scripts.add(Loader.Cardano.PlutusScript.new(fromHex(contract)));
return scripts;
};
const CONTRACT_ADDRESS = () =>
Loader.Cardano.Address.from_bech32(
//"addr1wyvvtqlx34nu8xkpe86dcznlj9kwgpy97x0zpgqnr782hvcyjjcdh"
"addr1zyvvtqlx34nu8xkpe86dcznlj9kwgpy97x0zpgqnr782hvlassd377xwhjrwyuqtxsces0ksaev6s7pllvd7hrpfn98q35a5tz"
);
// Datums
const START_BID = () => {
const datum = Loader.Cardano.PlutusData.new_constr_plutus_data(
Loader.Cardano.ConstrPlutusData.new(
Loader.Cardano.Int.new_i32(DATUM_TYPE.StartBid),
Loader.Cardano.PlutusList.new()
)
);
return datum;
};
const BID = ({ tradeOwner, budId }) => {
const fieldsInner = Loader.Cardano.PlutusList.new();
fieldsInner.add(Loader.Cardano.PlutusData.new_bytes(fromHex(tradeOwner)));
fieldsInner.add(
Loader.Cardano.PlutusData.new_bytes(fromHex(toBytesNum(budId)))
);
fieldsInner.add(
Loader.Cardano.PlutusData.new_integer(Loader.Cardano.BigInt.from_str("1"))
);
const tradeDetails = Loader.Cardano.PlutusList.new();
tradeDetails.add(
Loader.Cardano.PlutusData.new_constr_plutus_data(
Loader.Cardano.ConstrPlutusData.new(
Loader.Cardano.Int.new_i32(0),
fieldsInner
)
)
);
const datum = Loader.Cardano.PlutusData.new_constr_plutus_data(
Loader.Cardano.ConstrPlutusData.new(
Loader.Cardano.Int.new_i32(DATUM_TYPE.Bid),
tradeDetails
)
);
return datum;
};
const OFFER = ({ tradeOwner, budId, requestedAmount }) => {
const fieldsInner = Loader.Cardano.PlutusList.new();
fieldsInner.add(Loader.Cardano.PlutusData.new_bytes(fromHex(tradeOwner)));
fieldsInner.add(
Loader.Cardano.PlutusData.new_bytes(fromHex(toBytesNum(budId)))
);
fieldsInner.add(
Loader.Cardano.PlutusData.new_integer(
Loader.Cardano.BigInt.from_str(requestedAmount)
)
);
const tradeDetails = Loader.Cardano.PlutusList.new();
tradeDetails.add(
Loader.Cardano.PlutusData.new_constr_plutus_data(
Loader.Cardano.ConstrPlutusData.new(
Loader.Cardano.Int.new_i32(0),
fieldsInner
)
)
);
const datum = Loader.Cardano.PlutusData.new_constr_plutus_data(
Loader.Cardano.ConstrPlutusData.new(
Loader.Cardano.Int.new_i32(DATUM_TYPE.Offer),
tradeDetails
)
);
return datum;
};
const DATUM_TYPE = {
StartBid: 0,
Bid: 1,
Offer: 2,
};
// Redeemers
const BUY = (index) => {
const redeemerData = Loader.Cardano.PlutusData.new_constr_plutus_data(
Loader.Cardano.ConstrPlutusData.new(
Loader.Cardano.Int.new_i32(0),
Loader.Cardano.PlutusList.new()
)
);
const redeemer = Loader.Cardano.Redeemer.new(
Loader.Cardano.RedeemerTag.new_spend(),
Loader.Cardano.BigNum.from_str(index),
redeemerData,
Loader.Cardano.ExUnits.new(
Loader.Cardano.BigNum.from_str("7000000"),
Loader.Cardano.BigNum.from_str("3000000000")
)
);
return redeemer;
};
const SELL = (index) => {
const redeemerData = Loader.Cardano.PlutusData.new_constr_plutus_data(
Loader.Cardano.ConstrPlutusData.new(
Loader.Cardano.Int.new_i32(1),
Loader.Cardano.PlutusList.new()
)
);
const redeemer = Loader.Cardano.Redeemer.new(
Loader.Cardano.RedeemerTag.new_spend(),
Loader.Cardano.BigNum.from_str(index),
redeemerData,
Loader.Cardano.ExUnits.new(
Loader.Cardano.BigNum.from_str("7000000"),
Loader.Cardano.BigNum.from_str("3000000000")
)
);
return redeemer;
};
const BID_HIGHER = (index) => {
const redeemerData = Loader.Cardano.PlutusData.new_constr_plutus_data(
Loader.Cardano.ConstrPlutusData.new(
Loader.Cardano.Int.new_i32(2),
Loader.Cardano.PlutusList.new()
)
);
const redeemer = Loader.Cardano.Redeemer.new(
Loader.Cardano.RedeemerTag.new_spend(),
Loader.Cardano.BigNum.from_str(index),
redeemerData,
Loader.Cardano.ExUnits.new(
Loader.Cardano.BigNum.from_str("7000000"),
Loader.Cardano.BigNum.from_str("3000000000")
)
);
return redeemer;
};
const CANCEL = (index) => {
const redeemerData = Loader.Cardano.PlutusData.new_constr_plutus_data(
Loader.Cardano.ConstrPlutusData.new(
Loader.Cardano.Int.new_i32(3),
Loader.Cardano.PlutusList.new()
)
);
const redeemer = Loader.Cardano.Redeemer.new(
Loader.Cardano.RedeemerTag.new_spend(),
Loader.Cardano.BigNum.from_str(index),
redeemerData,
Loader.Cardano.ExUnits.new(
Loader.Cardano.BigNum.from_str("5000000"),
Loader.Cardano.BigNum.from_str("2000000000")
)
);
return redeemer;
};
const toFraction = (p) => Math.floor(1 / (p / 1000));
class SpaceBudzMarket {
constructor({ base, projectId }, extraFeeRecipient) {
this.provider = { base, projectId };
this.extraFeeRecipient = extraFeeRecipient;
}
/**
*
* @typedef {Object} TradeUtxo
* @property {PlutusData} datum
* @property {Address} tradeOwnerAddress
* @property {TransactionUnspentOutput} utxo
* @property {string} budId
* @property {string} lovelace bid amount or requested amount from offer
*/
/**
*@private
*/
async blockfrostRequest(endpoint, headers, body) {
return await fetch(this.provider.base + endpoint, {
headers: {
project_id: this.provider.projectId,
...headers,
"User-Agent": "spacebudz-marketplace",
},
method: body ? "POST" : "GET",
body,
}).then((res) => res.json());
}
/**
* @private
* @returns {TradeUtxo[]}
*/
async getUtxo(policy, prefix, budId) {
const asset = policy + fromAscii(prefix + budId);
const utxos = await this.blockfrostRequest( // TODO - We need to make sure that this is going to work for us. Do we just want to use blockfrost? No.
`/addresses/${CONTRACT_ADDRESS().to_bech32()}/utxos/${asset}`
);
console.log(JSON.stringify(utxos));
return await Promise.all(
utxos.map(async (utxo) => {
const metadata = await this.blockfrostRequest(
`/txs/${utxo.tx_hash}/metadata`
);
let datum;
let tradeOwnerAddress;
try {
console.log(`Expect: ${toHex(START_BID().to_bytes())}`)
datum = metadata
.find((m) => m.label == DATUM_LABEL)
.json_metadata[utxo.output_index].slice(2);
if (datum != toHex(START_BID().to_bytes()))
//STARTBID doesn't have a tradeOwner
tradeOwnerAddress = metadata
.find((m) => m.label == ADDRESS_LABEL)
.json_metadata.address.slice(2);
} catch (e) {
// throw new Error("Some required metadata entries were not found");
console.log("Some required metadata entries were not found.")
datum = toHex(START_BID().to_bytes());
}
datum = Loader.Cardano.PlutusData.from_bytes(fromHex(datum));
console.log(utxo.data_hash);
console.log(toHex(Loader.Cardano.hash_plutus_data(datum).to_bytes()));
if (
toHex(Loader.Cardano.hash_plutus_data(datum).to_bytes()) !==
utxo.data_hash
)
throw new Error("Datum hash doesn't match");
return {
datum,
tradeOwnerAddress:
tradeOwnerAddress &&
Loader.Cardano.Address.from_bytes(fromHex(tradeOwnerAddress)),
utxo: Loader.Cardano.TransactionUnspentOutput.new(
Loader.Cardano.TransactionInput.new(
Loader.Cardano.TransactionHash.from_bytes(fromHex(utxo.tx_hash)),
utxo.output_index
),
Loader.Cardano.TransactionOutput.new(
CONTRACT_ADDRESS(),
assetsToValue(utxo.amount)
)
),
budId,
};
})
);
}
/**
*@private
*/
async initTx() {
const txBuilder = Loader.Cardano.TransactionBuilder.new(
Loader.Cardano.LinearFee.new(
Loader.Cardano.BigNum.from_str(
this.protocolParameters.linearFee.minFeeA
),
Loader.Cardano.BigNum.from_str(
this.protocolParameters.linearFee.minFeeB
)
),
Loader.Cardano.BigNum.from_str(this.protocolParameters.minUtxo),
Loader.Cardano.BigNum.from_str(this.protocolParameters.poolDeposit),
Loader.Cardano.BigNum.from_str(this.protocolParameters.keyDeposit),
this.protocolParameters.maxValSize,
this.protocolParameters.maxTxSize,
this.protocolParameters.priceMem,
this.protocolParameters.priceStep,
Loader.Cardano.LanguageViews.new(Buffer.from(languageViews, "hex"))
);
const datums = Loader.Cardano.PlutusList.new();
const metadata = { [DATUM_LABEL]: {}, [ADDRESS_LABEL]: {} };
const outputs = Loader.Cardano.TransactionOutputs.new();
return { txBuilder, datums, metadata, outputs };
}
/**
* @private
*/
policyBidLength(value) {
if (!value.multiasset()) return 0;
const policy = Loader.Cardano.ScriptHash.from_bytes(
Loader.Cardano.Ed25519KeyHash.from_bytes(
fromHex(this.contractInfo.policyBid)
).to_bytes()
);
return value.multiasset().get(policy).len();
}
/**
* @private
*/
policyBidRemaining(value, budId) {
const assets = valueToAssets(value);
return assetsToValue(
assets.filter(
(asset) =>
asset.unit !=
this.contractInfo.policyBid +
fromAscii(this.contractInfo.prefixSpaceBudBid + budId) &&
asset.unit.startsWith(this.contractInfo.policyBid)
)
);
}
/**
* @private
*/
createOutput(
address,
value,
{ datum, index, tradeOwnerAddress, metadata } = {}
) {
const v = value;
const minAda = Loader.Cardano.min_ada_required(
v,
Loader.Cardano.BigNum.from_str(this.protocolParameters.minUtxo),
datum && Loader.Cardano.hash_plutus_data(datum)
);
if (minAda.compare(v.coin()) == 1) v.set_coin(minAda);
const output = Loader.Cardano.TransactionOutput.new(address, v);
if (datum) {
output.set_data_hash(Loader.Cardano.hash_plutus_data(datum));
metadata[DATUM_LABEL][index] = "0x" + toHex(datum.to_bytes());
}
if (tradeOwnerAddress) {
metadata[ADDRESS_LABEL].address =
"0x" + toHex(tradeOwnerAddress.to_address().to_bytes());
}
return output;
}
/**
* @private
*/
setCollateral(txBuilder, utxos) {
const inputs = Loader.Cardano.TransactionInputs.new();
utxos.forEach((utxo) => {
inputs.add(utxo.input());
txBuilder.add_address_witness(utxo.output().address());
});
txBuilder.set_collateral(inputs);
}
/**
* @private
*/
async finalizeTx({
txBuilder,
changeAddress,
utxos,
outputs,
datums,
metadata,
scriptUtxo,
action,
}) {
const transactionWitnessSet = Loader.Cardano.TransactionWitnessSet.new();
let { input, change } = CoinSelection.randomImprove(
utxos,
outputs,
8,
scriptUtxo ? [scriptUtxo] : []
);
input.forEach((utxo) => {
txBuilder.add_input(
utxo.output().address(),
utxo.input(),
utxo.output().amount()
);
});
for (let i = 0; i < outputs.len(); i++) {
txBuilder.add_output(outputs.get(i));
}
if (scriptUtxo) {
const redeemers = Loader.Cardano.Redeemers.new();
const redeemerIndex = txBuilder
.index_of_input(scriptUtxo.input())
.toString();
redeemers.add(action(redeemerIndex));
txBuilder.set_redeemers(
Loader.Cardano.Redeemers.from_bytes(redeemers.to_bytes())
);
txBuilder.set_plutus_data(
Loader.Cardano.PlutusList.from_bytes(datums.to_bytes())
);
txBuilder.set_plutus_scripts(CONTRACT());
const collateral = (
await window.cardano.selectedWallet.experimental.getCollateral()
).map((utxo) =>
Loader.Cardano.TransactionUnspentOutput.from_bytes(fromHex(utxo))
);
if (collateral.length <= 0) throw new Error("NO_COLLATERAL");
this.setCollateral(txBuilder, collateral);
transactionWitnessSet.set_plutus_scripts(CONTRACT());
transactionWitnessSet.set_plutus_data(datums);
transactionWitnessSet.set_redeemers(redeemers);
}
let aux_data;
if (metadata) {
aux_data = Loader.Cardano.AuxiliaryData.new();
const generalMetadata = Loader.Cardano.GeneralTransactionMetadata.new();
Object.keys(metadata).forEach((label) => {
Object.keys(metadata[label]).length > 0 &&
generalMetadata.insert(
Loader.Cardano.BigNum.from_str(label),
Loader.Cardano.encode_json_str_to_metadatum(
JSON.stringify(metadata[label]),
1
)
);
});
aux_data.set_metadata(generalMetadata);
txBuilder.set_auxiliary_data(aux_data);
}
const changeMultiAssets = change.multiasset();
// check if change value is too big for single output
if (
changeMultiAssets &&
change.to_bytes().length * 2 > this.protocolParameters.maxValSize
) {
const partialChange = Loader.Cardano.Value.new(
Loader.Cardano.BigNum.from_str("0")
);
const partialMultiAssets = Loader.Cardano.MultiAsset.new();
const policies = changeMultiAssets.keys();
const makeSplit = () => {
for (let j = 0; j < changeMultiAssets.len(); j++) {
const policy = policies.get(j);
const policyAssets = changeMultiAssets.get(policy);
const assetNames = policyAssets.keys();
const assets = Loader.Cardano.Assets.new();
for (let k = 0; k < assetNames.len(); k++) {
const policyAsset = assetNames.get(k);
const quantity = policyAssets.get(policyAsset);
assets.insert(policyAsset, quantity);
//check size
const checkMultiAssets = Loader.Cardano.MultiAsset.from_bytes(
partialMultiAssets.to_bytes()
);
checkMultiAssets.insert(policy, assets);
const checkValue = Loader.Cardano.Value.new(
Loader.Cardano.BigNum.from_str("0")
);
checkValue.set_multiasset(checkMultiAssets);
if (
checkValue.to_bytes().length * 2 >=
this.protocolParameters.maxValSize
) {
partialMultiAssets.insert(policy, assets);
return;
}
}
partialMultiAssets.insert(policy, assets);
}
};
makeSplit();
partialChange.set_multiasset(partialMultiAssets);
const minAda = Loader.Cardano.min_ada_required(
partialChange,
Loader.Cardano.BigNum.from_str(this.protocolParameters.minUtxo)
);
partialChange.set_coin(minAda);
txBuilder.add_output(
Loader.Cardano.TransactionOutput.new(
changeAddress.to_address(),
partialChange
)
);
}
txBuilder.add_change_if_needed(changeAddress.to_address());
const txBody = txBuilder.build();
const tx = Loader.Cardano.Transaction.new(
txBody,
Loader.Cardano.TransactionWitnessSet.from_bytes(
transactionWitnessSet.to_bytes()
),
aux_data
);
const size = tx.to_bytes().length * 2;
console.log(size);
if (size > this.protocolParameters.maxTxSize)
throw new Error("MAX_SIZE_REACHED");
let txVkeyWitnesses = await window.cardano.selectedWallet.signTx(
toHex(tx.to_bytes()),
true
);
txVkeyWitnesses = Loader.Cardano.TransactionWitnessSet.from_bytes(
fromHex(txVkeyWitnesses)
);
transactionWitnessSet.set_vkeys(txVkeyWitnesses.vkeys());
const signedTx = Loader.Cardano.Transaction.new(
tx.body(),
transactionWitnessSet,
tx.auxiliary_data()
);
console.log("Full Tx Size", signedTx.to_bytes().length);
const txHash = await window.cardano.selectedWallet.submitTx(
toHex(signedTx.to_bytes())
);
return txHash;
}
/**
* @private
*/
splitAmount(lovelaceAmount, address, outputs) {
if (
lovelaceAmount.compare(Loader.Cardano.BigNum.from_str("400000000")) ==
1 ||
lovelaceAmount.compare(Loader.Cardano.BigNum.from_str("400000000")) == 0
) {
const [amount1, amount2, amount3] = [
lovelacePercentage(lovelaceAmount, this.contractInfo.owner1.fee2),
lovelacePercentage(lovelaceAmount, this.contractInfo.owner2.fee),
lovelacePercentage(lovelaceAmount, this.contractInfo.extraFee),
];
if (
this.extraFeeRecipient.to_bech32() ==
this.contractInfo.owner1.address.to_bech32() // if owner is same as fee recipient, no reason to split up utxo extra
) {
outputs.add(
this.createOutput(
this.contractInfo.owner1.address,
Loader.Cardano.Value.new(amount1.checked_add(amount3))
)
);
} else {
outputs.add(
this.createOutput(
this.contractInfo.owner1.address,
Loader.Cardano.Value.new(amount1)
)
);
outputs.add(
this.createOutput(
this.extraFeeRecipient,
Loader.Cardano.Value.new(amount3)
)
);
}
outputs.add(
this.createOutput(
this.contractInfo.owner2.address,
Loader.Cardano.Value.new(amount2)
)
);
outputs.add(
this.createOutput(
address,
Loader.Cardano.Value.new(
lovelaceAmount
.checked_sub(amount1)
.checked_sub(amount2)
.checked_sub(amount3)
)
)
);
} else {
const amount1 = lovelacePercentage(
lovelaceAmount,
this.contractInfo.owner1.fee1
);
outputs.add(
this.createOutput(
this.contractInfo.owner1.address,
Loader.Cardano.Value.new(amount1)
)
);
outputs.add(
this.createOutput(
address,
Loader.Cardano.Value.new(lovelaceAmount.checked_sub(amount1))
)
);
}
}
async load() {
await Loader.load();
const p = await this.blockfrostRequest(`/epochs/latest/parameters`); // TODO - We have this on the other one.
console.log(JSON.stringify(p));
this.protocolParameters = {
linearFee: {
minFeeA: p.min_fee_a.toString(),
minFeeB: p.min_fee_b.toString(),
},
minUtxo: "1000000",
poolDeposit: p.pool_deposit,
keyDeposit: p.key_deposit,
maxValSize: parseInt(p.max_val_size),
maxTxSize: parseInt(p.max_tx_size),
priceMem: parseFloat(p.price_mem),
priceStep: parseFloat(p.price_step),
};
//TODO: wait for blockfrost fix
// this.protocolParameters = {
// linearFee: {
// minFeeA: p.min_fee_a.toString(),
// minFeeB: p.min_fee_b.toString(),
// },
// minUtxo: "1000000",
// poolDeposit: "500000000",
// keyDeposit: "2000000",
// maxValSize: "5000",
// maxTxSize: 16384,
// priceMem: 5.77e-2,
// priceStep: 7.21e-5,
// };
this.contractInfo = {
policySpaceBudz: // TODO - Replace the policy ids below.
"3c2cfd4f1ad33678039cfd0347cca8df363c710067d739624218abc0",
policyBid: "314f6e0535275e1ba9335c722364865fe5503a8aa6a0f9ad640c6c94",
prefixSpaceBud: "WorldsWithin",
prefixSpaceBudBid: "WorldsWithinBid",
owner1: {
address: Loader.Cardano.Address.from_bech32(
"addr1q9pgdsg5ds5r7dldfny020wu5ck2e9xch7z97ufcakayfmctzv5tnwx36p2kl0dlkk5kft9z55e9k5dmpqvk9xluupdsz3s9xl"
),
fee1: Loader.Cardano.BigNum.from_str("416"), // 2.4%
fee2: Loader.Cardano.BigNum.from_str("625"), // 1.6%
},
owner2: {
address: Loader.Cardano.Address.from_bech32(
"addr1q9pgdsg5ds5r7dldfny020wu5ck2e9xch7z97ufcakayfmctzv5tnwx36p2kl0dlkk5kft9z55e9k5dmpqvk9xluupdsz3s9xl"
),
fee: Loader.Cardano.BigNum.from_str("2500"), // 0.4%
},
extraFee: Loader.Cardano.BigNum.from_str("2500"), // 0.4%
minPrice: Loader.Cardano.BigNum.from_str("20000000"),
bidStep: Loader.Cardano.BigNum.from_str("10000"),
};
this.extraFeeRecipient = Loader.Cardano.Address.from_bech32(
"addr1q9pgdsg5ds5r7dldfny020wu5ck2e9xch7z97ufcakayfmctzv5tnwx36p2kl0dlkk5kft9z55e9k5dmpqvk9xluupdsz3s9xl"
);
CoinSelection.setProtocolParameters(
this.protocolParameters.minUtxo,
this.protocolParameters.linearFee.minFeeA,
this.protocolParameters.linearFee.minFeeB,
this.protocolParameters.maxTxSize.toString()
);
}
/**
*
* @param {number} budId
* @returns {TradeUtxo | TradeUtxo[] | undefined} Array if both twins are offered
*/
async getOffer(budId) {
const offerUtxo = await this.getUtxo(
this.contractInfo.policySpaceBudz,
this.contractInfo.prefixSpaceBud,
budId.toString().padStart(5, "0")
);
if (offerUtxo.length === 1) {
const lovelace = getTradeDetails(offerUtxo[0].datum).requestedAmount;
if (lovelace.compare(this.contractInfo.minPrice) == -1) return null;
return { ...offerUtxo[0], lovelace: lovelace.to_str() };
}
if (offerUtxo.length === 2 && (budId == 1903 || budId == 6413)) {
const utxos = offerUtxo
.map((utxo) => {
const lovelace = getTradeDetails(utxo.datum).requestedAmount;
if (lovelace.compare(this.contractInfo.minPrice) == -1) return null;
return { ...utxo, lovelace: lovelace.to_str() };
})
.filter((utxo) => utxo != null);
// if both twins are offered, but one < minPrice filter it out and do not return an array
// if both are < minPrice return null
if (utxos.length <= 0) return null;
if (utxos.length < 2) return utxos[0];
return utxos;
}
return null;
}
async getAddress() {
try {
return Loader.Cardano.BaseAddress.from_address(
Loader.Cardano.Address.from_bytes(
fromHex((await window.cardano.selectedWallet.getUsedAddresses())[0])
)
);
} catch (e) {}
try {
return Loader.Cardano.EnterpriseAddress.from_address(
Loader.Cardano.Address.from_bytes(
fromHex((await window.cardano.selectedWallet.getUsedAddresses())[0])
)
);
} catch (e) {}
try {
return Loader.Cardano.PointerAddress.from_address(
Loader.Cardano.Address.from_bytes(
fromHex((await window.cardano.selectedWallet.getUsedAddresses())[0])
)
);
} catch (e) {}
throw Error("Not supported address type");
}
/**
*
* @param {number} budId
* @returns {TradeUtxo}
*/
async getBid(budId) {
console.log(`getUtxo w policy: ${this.contractInfo.policyBid} , prefix: ${this.contractInfo.prefixSpaceBudBid}, id: ${budId.toString()}`)
let budString = budId.toString().padStart(5, "0")
console.log(budString)
// let numZeros = 5 - budString.length
const bidUtxo = await this.getUtxo(
this.contractInfo.policyBid,
this.contractInfo.prefixSpaceBudBid,
budString
);
if (bidUtxo.length !== 1) return null;
const lovelace = bidUtxo[0].utxo.output().amount().coin().to_str();
return { ...bidUtxo[0], lovelace };
}
/**
* @param {TradeUtxo} bidUtxo
* @param {string} bidAmount lovelace amount
* @returns {string} Transaction Id
*/
async bid(bidUtxo, bidAmount) {
const { txBuilder, datums, metadata, outputs } = await this.initTx();
const budId = bidUtxo.budId;
const walletAddress = await this.getAddress();
const utxos = (await window.cardano.selectedWallet.getUtxos()).map((utxo) =>
Loader.Cardano.TransactionUnspentOutput.from_bytes(fromHex(utxo))
);
datums.add(bidUtxo.datum);
const bidDatum = BID({
tradeOwner: toHex(walletAddress.payment_cred().to_keyhash().to_bytes()),
budId,
});
const datumType = bidUtxo.datum.as_constr_plutus_data().tag().as_i32();
const value = bidUtxo.utxo.output().amount();
if (datumType === DATUM_TYPE.StartBid) {
if (
Loader.Cardano.BigNum.from_str(bidAmount).compare(
this.contractInfo.minPrice
) == -1
)
throw new Error("Amount too small");
if (this.policyBidLength(value) > 1) {
outputs.add(
this.createOutput(
CONTRACT_ADDRESS(),
assetsToValue([
{ unit: "lovelace", quantity: bidAmount },
{
unit:
this.contractInfo.policyBid +
fromAscii(this.contractInfo.prefixSpaceBudBid + budId),
quantity: "1",
},
]),
{
datum: bidDatum,
index: 0,
tradeOwnerAddress: walletAddress,
metadata,
}
)
);
datums.add(bidDatum);
outputs.add(
this.createOutput(
CONTRACT_ADDRESS(),
this.policyBidRemaining(bidUtxo.utxo.output().amount(), budId),
{
datum: START_BID(),
index: 1,
metadata,
}
)
);
datums.add(START_BID());
} else {
outputs.add(
this.createOutput(
CONTRACT_ADDRESS(),
assetsToValue([
{ unit: "lovelace", quantity: bidAmount },
{
unit:
this.contractInfo.policyBid +
fromAscii(this.contractInfo.prefixSpaceBudBid + budId),
quantity: "1",
},
]),
{
datum: bidDatum,
index: 0,
tradeOwnerAddress: walletAddress,
metadata,
}
)
);
datums.add(bidDatum);
}
} else if (datumType == DATUM_TYPE.Bid) {
if (
Loader.Cardano.BigNum.from_str(bidAmount).compare(
this.contractInfo.bidStep.checked_add(value.coin())
) == -1
)
throw new Error("Amount too small");
outputs.add(
this.createOutput(
CONTRACT_ADDRESS(),
assetsToValue([
{ unit: "lovelace", quantity: bidAmount },
{
unit:
this.contractInfo.policyBid +
fromAscii(this.contractInfo.prefixSpaceBudBid + budId),
quantity: "1",
},
]),
{
datum: bidDatum,
index: 0,
tradeOwnerAddress: walletAddress,
metadata,
}
)
);
datums.add(bidDatum);
if (
bidUtxo.tradeOwnerAddress.to_bech32() !=
walletAddress.to_address().to_bech32()
)
// check if bidder is owner of utxo. if so, not necessary to pay back to you own address
outputs.add(
this.createOutput(
bidUtxo.tradeOwnerAddress,
Loader.Cardano.Value.new(value.coin())
)
);
else {
const requiredSigners = Loader.Cardano.Ed25519KeyHashes.new();
requiredSigners.add(walletAddress.payment_cred().to_keyhash());
txBuilder.set_required_signers(requiredSigners);
}
}
const txHash = await this.finalizeTx({
txBuilder,
changeAddress: walletAddress,
utxos,
outputs,
datums,
metadata,
scriptUtxo: bidUtxo.utxo,
action: BID_HIGHER,
});
return txHash;
}
/**
*
* @param {TradeUtxo} bidUtxo
* @returns {string} Transaction Id
*/
async sell(bidUtxo) {
const { txBuilder, datums, metadata, outputs } = await this.initTx();
const budId = bidUtxo.budId;
const walletAddress = await this.getAddress();
const utxos = (await window.cardano.selectedWallet.getUtxos()).map((utxo) =>
Loader.Cardano.TransactionUnspentOutput.from_bytes(fromHex(utxo))
);
datums.add(bidUtxo.datum);
const datumType = bidUtxo.datum.as_constr_plutus_data().tag().as_i32();
const value = bidUtxo.utxo.output().amount();
if (datumType !== DATUM_TYPE.Bid) throw new Error("Datum needs to be Bid");
outputs.add(
this.createOutput(
CONTRACT_ADDRESS(),
assetsToValue([
{
unit:
this.contractInfo.policyBid +
fromAscii(this.contractInfo.prefixSpaceBudBid + budId),
quantity: "1",
},
]),
{
datum: START_BID(),
index: 0,
metadata,
}
)
);
datums.add(START_BID());
this.splitAmount(value.coin(), walletAddress.to_address(), outputs);
outputs.add(
this.createOutput(
bidUtxo.tradeOwnerAddress,
assetsToValue([
{
unit:
this.contractInfo.policySpaceBudz +
fromAscii(this.contractInfo.prefixSpaceBud + budId),
quantity: "1",
},
])
)
); // bidder receiving SpaceBud
const requiredSigners = Loader.Cardano.Ed25519KeyHashes.new();
requiredSigners.add(walletAddress.payment_cred().to_keyhash());
txBuilder.set_required_signers(requiredSigners);
const txHash = await this.finalizeTx({
txBuilder,
changeAddress: walletAddress,
utxos,
outputs,
datums,
metadata,
scriptUtxo: bidUtxo.utxo,
action: SELL,
});
return txHash;
}
/**
*
* @param {number} budId
* @param {string} requestedAmount lovelace
* @returns {string} Transaction Id
*/
async offer(budId, requestedAmount) {
const { txBuilder, datums, metadata, outputs } = await this.initTx();
budId = budId.toString().padStart(5, "0");
if (
Loader.Cardano.BigNum.from_str(requestedAmount).compare(
this.contractInfo.minPrice
) == -1
)
throw new Error("Amount too small");
const walletAddress = await this.getAddress();
const utxos = (await window.cardano.selectedWallet.getUtxos()).map((utxo) =>
Loader.Cardano.TransactionUnspentOutput.from_bytes(fromHex(utxo))
);