-
Notifications
You must be signed in to change notification settings - Fork 9
/
ApolloBuilder.go
1863 lines (1603 loc) · 53.1 KB
/
ApolloBuilder.go
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
package apollo
import (
"crypto/ed25519"
"encoding/hex"
"errors"
"fmt"
"strconv"
"github.com/Salvionied/apollo/apollotypes"
"github.com/Salvionied/apollo/constants"
"github.com/Salvionied/apollo/serialization"
"github.com/Salvionied/apollo/serialization/Address"
"github.com/Salvionied/apollo/serialization/Amount"
"github.com/Salvionied/apollo/serialization/Certificate"
"github.com/Salvionied/apollo/serialization/HDWallet"
"github.com/Salvionied/apollo/serialization/Key"
"github.com/Salvionied/apollo/serialization/Metadata"
"github.com/Salvionied/apollo/serialization/MultiAsset"
"github.com/Salvionied/apollo/serialization/NativeScript"
"github.com/Salvionied/apollo/serialization/PlutusData"
"github.com/Salvionied/apollo/serialization/Redeemer"
"github.com/Salvionied/apollo/serialization/Transaction"
"github.com/Salvionied/apollo/serialization/TransactionBody"
"github.com/Salvionied/apollo/serialization/TransactionInput"
"github.com/Salvionied/apollo/serialization/TransactionOutput"
"github.com/Salvionied/apollo/serialization/TransactionWitnessSet"
"github.com/Salvionied/apollo/serialization/UTxO"
"github.com/Salvionied/apollo/serialization/Value"
"github.com/Salvionied/apollo/serialization/VerificationKeyWitness"
"github.com/Salvionied/apollo/serialization/Withdrawal"
"github.com/Salvionied/apollo/txBuilding/Backend/Base"
"github.com/Salvionied/apollo/txBuilding/Backend/BlockFrostChainContext"
"github.com/Salvionied/apollo/txBuilding/Utils"
"github.com/Salvionied/cbor/v2"
"golang.org/x/exp/slices"
)
const (
EX_MEMORY_BUFFER = 0.2
EX_STEP_BUFFER = 0.2
)
type Apollo struct {
Context Base.ChainContext
payments []PaymentI
isEstimateRequired bool
auxiliaryData *Metadata.AuxiliaryData
utxos []UTxO.UTxO
preselectedUtxos []UTxO.UTxO
inputAddresses []Address.Address
tx *Transaction.Transaction
datums []PlutusData.PlutusData
requiredSigners []serialization.PubKeyHash
v1scripts []PlutusData.PlutusV1Script
v2scripts []PlutusData.PlutusV2Script
redeemers []Redeemer.Redeemer
redeemersToUTxO map[string]Redeemer.Redeemer
stakeRedeemers map[string]Redeemer.Redeemer
mintRedeemers map[string]Redeemer.Redeemer
mint []Unit
collaterals []UTxO.UTxO
Fee int64
FeePadding int64
Ttl int64
ValidityStart int64
totalCollateral int
referenceInputs []TransactionInput.TransactionInput
collateralReturn *TransactionOutput.TransactionOutput
withdrawals *Withdrawal.Withdrawal
certificates *Certificate.Certificates
nativescripts []NativeScript.NativeScript
usedUtxos []string
referenceScripts []PlutusData.ScriptHashable
wallet apollotypes.Wallet
scriptHashes []string
}
/*
*
New creates and initializes a new Apollo instance with the specified chain context,
in which sets up various internal data structures for building and handling transactions.
Params:
cc (Base.ChainContext): The chain context to use for transaction building.
Returns:
*Apollo: A pointer to the initialized Apollo instance.
*/
func New(cc Base.ChainContext) *Apollo {
return &Apollo{
Context: cc,
payments: []PaymentI{},
isEstimateRequired: false,
auxiliaryData: &Metadata.AuxiliaryData{},
utxos: []UTxO.UTxO{},
preselectedUtxos: []UTxO.UTxO{},
inputAddresses: []Address.Address{},
tx: nil,
datums: make([]PlutusData.PlutusData, 0),
requiredSigners: make([]serialization.PubKeyHash, 0),
v1scripts: make([]PlutusData.PlutusV1Script, 0),
v2scripts: make([]PlutusData.PlutusV2Script, 0),
redeemers: make([]Redeemer.Redeemer, 0),
redeemersToUTxO: make(map[string]Redeemer.Redeemer),
stakeRedeemers: make(map[string]Redeemer.Redeemer),
mint: make([]Unit, 0),
collaterals: make([]UTxO.UTxO, 0),
Fee: 0,
FeePadding: 0,
usedUtxos: make([]string, 0),
referenceInputs: make([]TransactionInput.TransactionInput, 0),
referenceScripts: make([]PlutusData.ScriptHashable, 0),
mintRedeemers: make(map[string]Redeemer.Redeemer)}
}
/*
*
GetWallet returns the wallet associated with the Apollo instance.
Returns:
apollotypes.Wallet: The wallet associated with the Apollo instance.
*/
func (b *Apollo) GetWallet() apollotypes.Wallet {
return b.wallet
}
/*
*
AddInput appends one or more UTxOs to the list of preselected
UTxOs for transaction inputs.
Params:
utxos (...UTxO.UTxO): A set of UTxOs to be added as inputs.
Returns:
*Apollo: A pointer to the modified Apollo instance.
*/
func (b *Apollo) AddInput(utxos ...UTxO.UTxO) *Apollo {
b.preselectedUtxos = append(b.preselectedUtxos, utxos...)
return b
}
/*
*
ConsumeUTxO adds a UTxO as an input to the transaction and deducts the specified payments from it.
Params:
utxo (UTxO.UTxO): The UTxO to be consumed as an input.
payments (...PaymentI): A sett of payments to be deducted from the UTxO.
Returns:
*Apollo: A pointer to the modified Apollo instance.
*/
func (b *Apollo) ConsumeUTxO(utxo UTxO.UTxO, payments ...PaymentI) *Apollo {
b.preselectedUtxos = append(b.preselectedUtxos, utxo)
selectedValue := utxo.Output.GetAmount()
for _, payment := range payments {
selectedValue = selectedValue.Sub(payment.ToValue())
}
if selectedValue.Less(Value.Value{}) {
panic("selected value is negative")
}
b.payments = append(b.payments, payments...)
selectedValue = selectedValue.RemoveZeroAssets()
p := NewPaymentFromValue(utxo.Output.GetAddress(), selectedValue)
b.payments = append(b.payments, p)
return b
}
/*
*
ConsumeAssetsFromUtxo adds a UTxO as an input to the transaction and deducts the specified asset payments from it.
Params:
utxo (UTxO.UTxO): The UTxO to be consumed as an input.
payments (...PaymentI): Asset payments to be deducted from the UTxO.
Returns:
*Apollo: A pointer to the modified Apollo instance.
*/
func (b *Apollo) ConsumeAssetsFromUtxo(utxo UTxO.UTxO, payments ...PaymentI) *Apollo {
b.preselectedUtxos = append(b.preselectedUtxos, utxo)
selectedValue := utxo.Output.GetAmount()
for _, payment := range payments {
selectedValue = selectedValue.Sub(Value.SimpleValue(0, payment.ToValue().GetAssets()))
}
if selectedValue.Less(Value.Value{}) {
panic("selected value is negative")
return b
}
b.payments = append(b.payments, payments...)
selectedValue = selectedValue.RemoveZeroAssets()
p := NewPaymentFromValue(utxo.Output.GetAddress(), selectedValue)
b.payments = append(b.payments, p)
return b
}
/*
*
AddLoadedUTxOs appends one or more UTxOs to the list of loaded UTxOs.
Params:
utxos (...UTxO.UTxO): A set of UTxOs to be added to the loaded UTxOs.
Returns:
*Apollo: A pointer to the modified Apollo instance.
*/
func (b *Apollo) AddLoadedUTxOs(utxos ...UTxO.UTxO) *Apollo {
b.utxos = append(b.utxos, utxos...)
return b
}
/*
*
AddInputAddress appends an input address to the list of input addresses for the transaction.
Params:
address (Address.Address): The input address to be added.
Returns:
*Apollo: A pointer to the modified Apollo instance.
*/
func (b *Apollo) AddInputAddress(address Address.Address) *Apollo {
b.inputAddresses = append(b.inputAddresses, address)
return b
}
/*
*
AddInputAddressFromBech32 decodes a Bech32 address and
appends it to the list of input addresses for the transaction.
Params:
address (string): The Bech32 address to be decoded and added
Returns:
*Apollo: A pointer to the modified Apollo instance.
*/
func (b *Apollo) AddInputAddressFromBech32(address string) *Apollo {
decoded_addr, _ := Address.DecodeAddress(address)
b.inputAddresses = append(b.inputAddresses, decoded_addr)
return b
}
/*
*
AddPayment appends a payment to the list of payments for the transaction.
Params:
payment (PaymentI): The payment to be added.
Returns:
*Apollo: A pointer to the modified Apollo instance with the payment added.
*/
func (b *Apollo) AddPayment(payment PaymentI) *Apollo {
b.payments = append(b.payments, payment)
return b
}
/*
*
PayToAddressBech32 creates a payment to the specified Bech32 address
with the given lovelace and units.
Params:
address (string): The Bech32 address to which the payment will be made.
lovelace (int): The amount in lovelace to be paid.
units (...Unit): The units (assets) to be paid along with the lovelace.
Returns:
*Apollo: A pointer to the modified Apollo instance with the payment added.
*/
func (b *Apollo) PayToAddressBech32(address string, lovelace int, units ...Unit) *Apollo {
decoded_addr, _ := Address.DecodeAddress(address)
return b.AddPayment(&Payment{lovelace, decoded_addr, units, nil, nil, false})
}
/*
*
PayToAddress creates a payment to the specified address with the given lovelace and units,
then adds it to the list of payment.
Params:
address (Address.Address): The recipient's address for the payment.
lovelace (int): The amount in lovelace to send in the payment.
units (...Unit): A set of units to include in the payment.
Returns:
*Apollo: A pointer to the modified Apollo instance with the payment added.
*/
func (b *Apollo) PayToAddress(address Address.Address, lovelace int, units ...Unit) *Apollo {
return b.AddPayment(&Payment{lovelace, address, units, nil, nil, false})
}
/*
*
AddDatum appends a Plutus datum to the list of data associated with the Apollo instance.
Params:
pd (*PlutusData.PlutusData): The Plutus datum to be added.
Returns:
*Apollo: A pointer to the modified Apollo instance with the datum added.
*/
func (b *Apollo) AddDatum(pd *PlutusData.PlutusData) *Apollo {
b.datums = append(b.datums, *pd)
return b
}
/*
*
PayToContract creates a payment to a smart contract address and includes a Plutus datum, which
is added to the list of payments, and if a datum is provided, it is added to the data list.
Params:
contractAddress (Address.Address): The smart contract address to send the payment to.
pd (*PlutusData.PlutusData): Plutus datum to include in the payment.
lovelace (int): The amount in lovelace to send in the payment.
isInline (bool): Indicates if the payment is inline with the datum.
units (...Unit): A set of units to include in the payment.
Returns:
*Apollo: A pointer to the modified Apollo instance with the payment and datum added.
*/
func (b *Apollo) PayToContract(contractAddress Address.Address, pd *PlutusData.PlutusData, lovelace int, isInline bool, units ...Unit) *Apollo {
if isInline {
b = b.AddPayment(&Payment{lovelace, contractAddress, units, pd, nil, isInline})
} else if pd != nil {
dataHash, _ := PlutusData.PlutusDataHash(pd)
b = b.AddPayment(&Payment{lovelace, contractAddress, units, pd, dataHash.Payload, isInline})
} else {
b = b.AddPayment(&Payment{lovelace, contractAddress, units, nil, nil, isInline})
}
if pd != nil && !isInline {
b = b.AddDatum(pd)
}
return b
}
/*
*
AddRequiredSignerFromBech32 decodes an address in Bech32 format and adds
its payment and staking parts as required signers.
Params:
address (string): The Bech32-encoded address to decode and add its parts as required signers.
addPaymentPart (bool): Indicates whether to add the payment part as a required signer.
addStakingPart (bool): Indicates whether to add the staking part as a required signer.
Returns:
*Apollo: A pointer to the modified Apollo instance with the required signers added.
*/
func (b *Apollo) AddRequiredSignerFromBech32(address string, addPaymentPart, addStakingPart bool) *Apollo {
decoded_addr, _ := Address.DecodeAddress(address)
if addPaymentPart {
b.requiredSigners = append(b.requiredSigners, serialization.PubKeyHash(decoded_addr.PaymentPart[0:28]))
}
if addStakingPart {
b.requiredSigners = append(b.requiredSigners, serialization.PubKeyHash(decoded_addr.StakingPart[0:28]))
}
return b
}
/*
*
AddRequiredSigner appends a public key hash to the list of required signers.
Params:
pkh (serialization.PubKeyHash): The public key hash to add as a required signer.
Returns:
*Apollo: A pointer to the modified Apollo instance with the required signer added.
*/
func (b *Apollo) AddRequiredSigner(pkh serialization.PubKeyHash) *Apollo {
b.requiredSigners = append(b.requiredSigners, pkh)
return b
}
/*
*
AddRequiredSignerFromAddress extracts the payment and staking parts from an address and adds them as required signers.
Params:
address (Address.Address): The address from which to extract the parts and add them as required signers.
addPaymentPart (bool): Indicates whether to add the payment part as a required signer.
addStakingPart (bool): Indicates whether to add the staking part as a required signer.
Returns:
*Apollo: A pointer to the modified Apollo instance with the required signers added.
*/
func (b *Apollo) AddRequiredSignerFromAddress(address Address.Address, addPaymentPart, addStakingPart bool) *Apollo {
if addPaymentPart {
pkh := serialization.PubKeyHash(address.PaymentPart)
b.requiredSigners = append(b.requiredSigners, pkh)
}
if addStakingPart {
pkh := serialization.PubKeyHash(address.StakingPart)
b.requiredSigners = append(b.requiredSigners, pkh)
}
return b
}
func (b *Apollo) SetFeePadding(padding int64) *Apollo {
b.FeePadding = padding
return b
}
/**
buildOutputs constructs and returns the transaction outputs based on the payments.
Returns:
[]TransactionOutput.TransactionOutput: A slice of transaction outputs.
*/
func (b *Apollo) buildOutputs() []TransactionOutput.TransactionOutput {
outputs := make([]TransactionOutput.TransactionOutput, 0)
for _, payment := range b.payments {
outputs = append(outputs, *payment.ToTxOut())
}
return outputs
}
/*
*
buildWitnessSet constructs and returns the witness set for the transaction.
Returns:
TransactionWitnessSet.TransactionWitnessSet: The transaction's witness set.
*/
func (b *Apollo) buildWitnessSet() TransactionWitnessSet.TransactionWitnessSet {
plutusdata := make([]PlutusData.PlutusData, 0)
plutusdata = append(plutusdata, b.datums...)
return TransactionWitnessSet.TransactionWitnessSet{
NativeScripts: b.nativescripts,
PlutusV1Script: b.v1scripts,
PlutusV2Script: b.v2scripts,
PlutusData: PlutusData.PlutusIndefArray(plutusdata),
Redeemer: b.redeemers,
}
}
/*
*
buildFakeWitnessSet constructs and returns a fake witness set used for testing.
Returns:
TransactionWitnessSet.TransactionWitnessSet: A fake witness set for testing.
*/
func (b *Apollo) buildFakeWitnessSet() TransactionWitnessSet.TransactionWitnessSet {
plutusdata := make([]PlutusData.PlutusData, 0)
plutusdata = append(plutusdata, b.datums...)
fakeVkWitnesses := make([]VerificationKeyWitness.VerificationKeyWitness, 0)
fakeVkWitnesses = append(fakeVkWitnesses, VerificationKeyWitness.VerificationKeyWitness{
Vkey: constants.FAKE_VKEY,
Signature: constants.FAKE_SIGNATURE})
for range b.requiredSigners {
fakeVkWitnesses = append(fakeVkWitnesses, VerificationKeyWitness.VerificationKeyWitness{
Vkey: constants.FAKE_VKEY,
Signature: constants.FAKE_SIGNATURE})
}
return TransactionWitnessSet.TransactionWitnessSet{
NativeScripts: b.nativescripts,
PlutusV1Script: b.v1scripts,
PlutusV2Script: b.v2scripts,
PlutusData: PlutusData.PlutusIndefArray(plutusdata),
Redeemer: b.redeemers,
VkeyWitnesses: fakeVkWitnesses,
}
}
/**
scriptDataHash computes the hash of script data based on redeemers and datums.
Returns:
*serialization.ScriptDataHash: The computed script data hash.
error: An error if the scriptDataHash fails.
*/
func (b *Apollo) scriptDataHash() (*serialization.ScriptDataHash, error) {
if len(b.datums) == 0 && len(b.redeemers) == 0 {
return nil, nil
}
witnessSet := b.buildWitnessSet()
cost_models := map[int]cbor.Marshaler{}
redeemers := witnessSet.Redeemer
PV1Scripts := witnessSet.PlutusV1Script
PV2Scripts := witnessSet.PlutusV2Script
datums := witnessSet.PlutusData
isV1 := len(PV1Scripts) > 0
if len(redeemers) > 0 {
if len(PV2Scripts) > 0 {
cost_models = PlutusData.COST_MODELSV2
} else if !isV1 {
cost_models = PlutusData.COST_MODELSV2
}
}
if redeemers == nil {
redeemers = []Redeemer.Redeemer{}
}
redeemer_bytes, err := cbor.Marshal(redeemers)
if err != nil {
return nil, err
}
var datum_bytes []byte
if datums.Len() > 0 {
datum_bytes, err = cbor.Marshal(datums)
if err != nil {
return nil, err
}
} else {
datum_bytes = []byte{}
}
var cost_model_bytes []byte
if isV1 {
cost_model_bytes, err = cbor.Marshal(PlutusData.COST_MODELSV1)
if err != nil {
return nil, err
}
} else {
cost_model_bytes, err = cbor.Marshal(cost_models)
if err != nil {
return nil, err
}
}
total_bytes := append(redeemer_bytes, datum_bytes...)
total_bytes = append(total_bytes, cost_model_bytes...)
hashBytes, err := serialization.Blake2bHash(total_bytes)
if err != nil {
return nil, err
}
return &serialization.ScriptDataHash{Payload: hashBytes}, nil
}
/*
*
getMints returns the multi-assets generated from minting.
Returns:
MultiAsset.MultiAsset[int64]: The generated multi-assets.
*/
func (b *Apollo) getMints() MultiAsset.MultiAsset[int64] {
ma := make(MultiAsset.MultiAsset[int64])
for _, mintUnit := range b.mint {
ma = ma.Add(mintUnit.ToValue().GetAssets())
}
return ma
}
/*
*
MintAssets adds a minting unit to the transaction's minting set.
Params:
mintUnit Unit: The minting unit to add.
Returns:
*Apollo: A pointer to the Apollo object to support method chaining.
*/
func (b *Apollo) MintAssets(mintUnit Unit) *Apollo {
b.mint = append(b.mint, mintUnit)
return b
}
/*
*
MintAssetsWithRedeemer adds a minting unit with an associated redeemer to the transaction's minting set.
Params:
mintUnit Unit: The minting unit to add.
redeemer Redeemer.Redeemer: The redeemer associated with the minting unit.
Returns:
*Apollo: A pointer to the Apollo object with the minting unit added.
*/
func (b *Apollo) MintAssetsWithRedeemer(mintUnit Unit, redeemer Redeemer.Redeemer) *Apollo {
b.mint = append(b.mint, mintUnit)
b.mintRedeemers[mintUnit.PolicyId] = redeemer
b.isEstimateRequired = true
return b
}
/**
buildTxBody constructs and returns the transaction body for the transaction.
Returns:
TransactionBody.TransactionBody: The transaction body.
error: An error if the build fails.
*/
func (b *Apollo) buildTxBody() (TransactionBody.TransactionBody, error) {
inputs := make([]TransactionInput.TransactionInput, 0)
for _, utxo := range b.preselectedUtxos {
inputs = append(inputs, utxo.Input)
}
collaterals := make([]TransactionInput.TransactionInput, 0)
for _, utxo := range b.collaterals {
collaterals = append(collaterals, utxo.Input)
}
dataHash, err := b.scriptDataHash()
if err != nil {
return TransactionBody.TransactionBody{}, err
}
scriptDataHash := make([]byte, 0)
if dataHash != nil {
scriptDataHash = dataHash.Payload
}
aux_data_hash := b.auxiliaryData.Hash()
mints := b.getMints()
txb := TransactionBody.TransactionBody{
Inputs: inputs,
Outputs: b.buildOutputs(),
Fee: b.Fee,
Ttl: b.Ttl,
Mint: mints,
AuxiliaryDataHash: aux_data_hash,
ScriptDataHash: scriptDataHash,
RequiredSigners: b.requiredSigners,
ValidityStart: b.ValidityStart,
Collateral: collaterals,
Certificates: b.certificates,
Withdrawals: b.withdrawals,
ReferenceInputs: b.referenceInputs}
if b.totalCollateral != 0 {
txb.TotalCollateral = b.totalCollateral
txb.CollateralReturn = b.collateralReturn
}
return txb, nil
}
/*
*
buildFullFakeTx constructs and returns a full fake transaction for testing.
Returns:
*Transaction.Transaction: A pointer to the fake transaction.
error: An error if the transaction construction fails.
*/
func (b *Apollo) buildFullFakeTx() (*Transaction.Transaction, error) {
txBody, err := b.buildTxBody()
if err != nil {
return nil, err
}
if txBody.Fee == 0 {
txBody.Fee = int64(b.Context.MaxTxFee())
}
witness := b.buildFakeWitnessSet()
tx := Transaction.Transaction{
TransactionBody: txBody,
TransactionWitnessSet: witness,
Valid: true,
AuxiliaryData: b.auxiliaryData}
bytes, _ := tx.Bytes()
if len(bytes) > b.Context.GetProtocolParams().MaxTxSize {
return nil, errors.New("transaction too large")
}
return &tx, nil
}
/*
*
estimateFee estimates the transaction fee based on execution units and transaction size.
Returns:
int64: The estimated transaction fee.
*/
func (b *Apollo) estimateFee() int64 {
pExU := Redeemer.ExecutionUnits{Mem: 0, Steps: 0}
for _, redeemer := range b.redeemers {
pExU.Sum(redeemer.ExUnits)
}
fftx, err := b.buildFullFakeTx()
if err != nil {
return 0
}
fakeTxBytes, _ := fftx.Bytes()
estimatedFee := Utils.Fee(b.Context, len(fakeTxBytes), pExU.Steps, pExU.Mem)
estimatedFee += b.FeePadding
return estimatedFee
}
/*
*
getAvailableUtxos returns the available unspent transaction outputs (UTXOs) for the transaction.
Returns:
[]UTxO.UTxO: A slice of available UTXOs.
*/
func (b *Apollo) getAvailableUtxos() []UTxO.UTxO {
availableUtxos := make([]UTxO.UTxO, 0)
for _, utxo := range b.utxos {
if !slices.Contains(b.usedUtxos, utxo.GetKey()) {
availableUtxos = append(availableUtxos, utxo)
}
}
return availableUtxos
}
/*
*
setRedeemerIndexes function sets indexes for redeemers in
the transaction based on UTxO inputs.
Returns:
*Apollo: A pointer to the Apollo object with indexes and redeemers set.
*/
func (b *Apollo) setRedeemerIndexes() *Apollo {
sorted_inputs := SortInputs(b.preselectedUtxos)
done := make([]string, 0)
for i, utxo := range sorted_inputs {
key := hex.EncodeToString(utxo.Input.TransactionId) + fmt.Sprint(utxo.Input.Index)
val, ok := b.redeemersToUTxO[key]
if ok && val.Tag == Redeemer.SPEND {
done = append(done, key)
redeem := b.redeemersToUTxO[key]
redeem.Index = i
b.redeemersToUTxO[key] = redeem
} else if ok && val.Tag == Redeemer.MINT {
//TODO: IMPLEMENT FOR MINTS
}
}
return b
}
/*
*
AttachDatum attaches a datum to the transaction.
Params:
datum *PlutusData.PlutusData: The datum to attach.
Returns:
*Apollo: A pointer to the Apollo object with the datum added.
*/
func (b *Apollo) AttachDatum(datum *PlutusData.PlutusData) *Apollo {
b.datums = append(b.datums, *datum)
return b
}
/**
setCollateral function sets collateral for the transaction.
Returns:
*Apollo: A pointer to the Apollo object to support method chaining.
error: An error if the setCollateral fails.
*/
func (b *Apollo) setCollateral() (*Apollo, error) {
if len(b.collaterals) > 0 {
collateral_amount := 5_000_000
for _, utxo := range b.collaterals {
if int(utxo.Output.GetValue().GetCoin()) >= collateral_amount+1_000_000 && len(utxo.Output.GetValue().GetAssets()) <= 5 {
b.totalCollateral = collateral_amount
return_amount := utxo.Output.GetValue().GetCoin() - int64(collateral_amount)
returnOutput := TransactionOutput.SimpleTransactionOutput(b.inputAddresses[0], Value.SimpleValue(return_amount, utxo.Output.GetValue().GetAssets()))
b.collateralReturn = &returnOutput
}
}
return b, nil
}
witnesses := b.buildWitnessSet()
if len(witnesses.PlutusV1Script) == 0 &&
len(witnesses.PlutusV2Script) == 0 &&
len(b.referenceInputs) == 0 {
return b, nil
}
availableUtxos := b.getAvailableUtxos()
collateral_amount := 5_000_000
for _, utxo := range availableUtxos {
if int(utxo.Output.GetValue().GetCoin()) >= collateral_amount && len(utxo.Output.GetValue().GetAssets()) <= 5 {
return_amount := utxo.Output.GetValue().GetCoin() - int64(collateral_amount)
min_lovelace := Utils.MinLovelacePostAlonzo(TransactionOutput.SimpleTransactionOutput(b.inputAddresses[0], Value.SimpleValue(return_amount, utxo.Output.GetAmount().GetAssets())), b.Context)
if min_lovelace > return_amount && return_amount != 0 {
continue
} else if return_amount == 0 && len(utxo.Output.GetAmount().GetAssets()) == 0 {
b.collaterals = append(b.collaterals, utxo)
b.totalCollateral = collateral_amount
return b, nil
} else {
returnOutput := TransactionOutput.SimpleTransactionOutput(b.inputAddresses[0], Value.SimpleValue(return_amount, utxo.Output.GetValue().GetAssets()))
b.collaterals = append(b.collaterals, utxo)
b.collateralReturn = &returnOutput
b.totalCollateral = collateral_amount
return b, nil
}
}
}
for _, utxo := range availableUtxos {
if int(utxo.Output.GetValue().GetCoin()) >= collateral_amount {
return_amount := utxo.Output.GetValue().GetCoin() - int64(collateral_amount)
min_lovelace := Utils.MinLovelacePostAlonzo(TransactionOutput.SimpleTransactionOutput(b.inputAddresses[0], Value.SimpleValue(return_amount, utxo.Output.GetAmount().GetAssets())), b.Context)
if min_lovelace > return_amount && return_amount != 0 {
continue
} else if return_amount == 0 && len(utxo.Output.GetAmount().GetAssets()) == 0 {
b.collaterals = append(b.collaterals, utxo)
b.totalCollateral = collateral_amount
return b, nil
} else {
returnOutput := TransactionOutput.SimpleTransactionOutput(b.inputAddresses[0], Value.SimpleValue(return_amount, utxo.Output.GetValue().GetAssets()))
b.collaterals = append(b.collaterals, utxo)
b.collateralReturn = &returnOutput
b.totalCollateral = collateral_amount
return b, nil
}
}
}
return b, errors.New("NoCollateral")
}
/*
*
Clone creates a deep copy of the Apollo object.
Returns:
*Apollo: A pointer to the cloned Apollo object.
*/
func (b *Apollo) Clone() *Apollo {
clone := *b
return &clone
}
/*
*
estimateExUnits estimates the execution units for redeemers and updates them.
Returns:
map[string]Redeemer.ExecutionUnits: A map of estimated execution units.
*/
func (b *Apollo) estimateExunits() map[string]Redeemer.ExecutionUnits {
cloned_b := b.Clone()
cloned_b.isEstimateRequired = false
updated_b, _ := cloned_b.Complete()
//updated_b = updated_b.fakeWitness()
tx_cbor, _ := cbor.Marshal(updated_b.tx)
return b.Context.EvaluateTx(tx_cbor)
}
/*
*
updateExUnits updates the execution units in the transaction based on estimates.
Returns:
*Apollo: A pointer to the Apollo object to support method chaining.
*/
func (b *Apollo) updateExUnits() *Apollo {
if b.isEstimateRequired {
estimated_execution_units := b.estimateExunits()
for k, redeemer := range b.redeemersToUTxO {
key := fmt.Sprintf("%s:%d", Redeemer.RdeemerTagNames[redeemer.Tag], redeemer.Index)
if _, ok := estimated_execution_units[key]; ok {
redeemer.ExUnits = estimated_execution_units[key]
b.redeemersToUTxO[k] = redeemer
}
}
for k, redeemer := range b.stakeRedeemers {
key := fmt.Sprintf("%s:%d", Redeemer.RdeemerTagNames[redeemer.Tag], redeemer.Index)
if _, ok := estimated_execution_units[key]; ok {
redeemer.ExUnits = estimated_execution_units[key]
b.stakeRedeemers[k] = redeemer
}
}
for k, redeemer := range b.mintRedeemers {
key := fmt.Sprintf("%s:%d", Redeemer.RdeemerTagNames[redeemer.Tag], redeemer.Index)
if _, ok := estimated_execution_units[key]; ok {
redeemer.ExUnits = estimated_execution_units[key]
b.mintRedeemers[k] = redeemer
}
}
for _, redeemer := range b.redeemersToUTxO {
b.redeemers = append(b.redeemers, redeemer)
}
for _, redeemer := range b.stakeRedeemers {
b.redeemers = append(b.redeemers, redeemer)
}
for _, redeemer := range b.mintRedeemers {
b.redeemers = append(b.redeemers, redeemer)
}
} else {
for _, redeemer := range b.redeemersToUTxO {
b.redeemers = append(b.redeemers, redeemer)
}
for _, redeemer := range b.stakeRedeemers {
b.redeemers = append(b.redeemers, redeemer)
}
for _, redeemer := range b.mintRedeemers {
b.redeemers = append(b.redeemers, redeemer)
}
}
return b
}
/*
*
GetTx returns the transaction associated with the Apollo object.
Returns:
*Transacction.Transaction: A pointer to the transaction.
*/
func (b *Apollo) GetTx() *Transaction.Transaction {
return b.tx
}
func CountRequiredAssets(assets MultiAsset.MultiAsset[int64]) int {
count := 0
for _, asset := range assets {
for _, amt := range asset {
if amt > 0 {
count++
}
}
}
return count
}
/*
*
Complete assembles and finalizes the Apollo transaction, handling
inputs, change, fees, collateral and witness data.
Returns:
*Apollo: A pointer to the Apollo object representing the completed transaction.
error: An error if any issues are encountered during the process.
*/
func (b *Apollo) Complete() (*Apollo, error) {
selectedUtxos := make([]UTxO.UTxO, 0)
selectedAmount := Value.Value{}
for _, utxo := range b.preselectedUtxos {
selectedAmount = selectedAmount.Add(utxo.Output.GetValue())
}
burnedValue := b.GetBurns()
mintedValue := b.getPositiveMints()
selectedAmount = selectedAmount.Add(mintedValue)
requestedAmount := Value.Value{}
requestedAmount.Add(burnedValue)
for _, payment := range b.payments {
payment.EnsureMinUTXO(b.Context)
requestedAmount = requestedAmount.Add(payment.ToValue())
}
requestedAmount.AddLovelace(b.estimateFee() + constants.MIN_LOVELACE)
unfulfilledAmount := requestedAmount.Sub(selectedAmount)
unfulfilledAmount = unfulfilledAmount.RemoveZeroAssets()
available_utxos := SortUtxos(b.getAvailableUtxos())
//BALANCE TX
requiredAssetsCount := CountRequiredAssets(unfulfilledAmount.GetAssets())
if unfulfilledAmount.GetCoin() > 0 || requiredAssetsCount > 0 {
//BALANCE
if len(unfulfilledAmount.GetAssets()) > 0 {
//BALANCE WITH ASSETS
for pol, assets := range unfulfilledAmount.GetAssets() {
for asset, amt := range assets {
found := false
selectedSoFar := int64(0)
usedIdxs := make([]int, 0)
for idx, utxo := range available_utxos {
ma := utxo.Output.GetValue().GetAssets()