-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathapollo.go
More file actions
3135 lines (2903 loc) · 102 KB
/
Copy pathapollo.go
File metadata and controls
3135 lines (2903 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package apollo
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"maps"
"math"
"math/big"
"slices"
"sort"
"strconv"
"strings"
"github.com/blinklabs-io/gouroboros/cbor"
"github.com/blinklabs-io/gouroboros/ledger/babbage"
"github.com/blinklabs-io/gouroboros/ledger/common"
"github.com/blinklabs-io/gouroboros/ledger/conway"
"github.com/blinklabs-io/gouroboros/ledger/shelley"
"github.com/Salvionied/apollo/v2/backend"
)
const (
ExMemoryBuffer = 0.2
ExStepBuffer = 0.2
StakeDeposit = 2_000_000
)
// Apollo is the main transaction builder.
type Apollo struct {
Context backend.ChainContext
payments []PaymentI
isEstimateRequired bool
utxos []common.Utxo
preselectedUtxos []common.Utxo
inputAddresses []common.Address
tx *conway.ConwayTransaction
datums []common.Datum
requiredSigners []common.Blake2b224
v1scripts []common.PlutusV1Script
v2scripts []common.PlutusV2Script
v3scripts []common.PlutusV3Script
redeemers map[string]redeemerEntry // keyed by UTxO ref string
stakeRedeemers map[string]redeemerEntry
mintRedeemers map[string]redeemerEntry
mint []Unit
collaterals []common.Utxo
Fee int64
FeePadding int64
Ttl int64
ValidityStart int64
totalCollateral int64
referenceInputs []shelley.ShelleyTransactionInput
collateralReturn *babbage.BabbageTransactionOutput
// collateralOverlapRef holds the ref of an auto-selected collateral UTxO
// that is also allowed to serve as a regular spending input. It is set only
// when no dedicated (separate) collateral UTxO was available, so wallets
// with a single UTxO can still build script transactions. The Cardano ledger
// permits this overlap because collateral is consumed only on phase-2 script
// failure and regular inputs only on success - the two paths are mutually
// exclusive. When empty, collateral is reserved out of the coin-selection
// pool as usual.
collateralOverlapRef string
// collateralAutoSelected is true when setCollateral() chose the collateral
// inputs itself (rather than the caller pinning them via AddCollateral).
// Only auto-selected collateral is resized by finalizeCollateral(), so
// caller-pinned collateral is never silently rewritten.
collateralAutoSelected bool
nativescripts []common.NativeScript
usedUtxos map[string]bool
wallet Wallet
certificates []common.CertificateWrapper
withdrawals map[string]withdrawalEntry
auxiliaryData *auxData
votingProcedures common.VotingProcedures
proposalProcedures []conway.ConwayProposalProcedure
currentTreasury int64
treasuryDonation int64
collateralAmount int64
scriptHashes []string
changeAddress *common.Address
estimateExUnits bool
forceFee bool
coinSelector CoinSelector
err error
}
type redeemerEntry struct {
Tag common.RedeemerTag
Data common.Datum
ExUnits common.ExUnits
}
type withdrawalEntry struct {
Address common.Address
Amount uint64
}
type auxData struct {
metadata map[uint64]any
}
// New creates a new Apollo transaction builder with the given chain context.
func New(cc backend.ChainContext) *Apollo {
return &Apollo{
Context: cc,
redeemers: make(map[string]redeemerEntry),
stakeRedeemers: make(map[string]redeemerEntry),
mintRedeemers: make(map[string]redeemerEntry),
withdrawals: make(map[string]withdrawalEntry),
estimateExUnits: true,
}
}
// SetWallet sets the wallet for the transaction builder.
func (a *Apollo) SetWallet(w Wallet) *Apollo {
a.wallet = w
return a
}
// SetWalletFromMnemonic creates a BursaWallet from a mnemonic and sets it.
func (a *Apollo) SetWalletFromMnemonic(mnemonic string) (*Apollo, error) {
w, err := NewBursaWallet(mnemonic)
if err != nil {
return a, err
}
a.wallet = w
return a, nil
}
// SetWalletFromMnemonicWithPassphrase creates a BursaWallet from a mnemonic and passphrase and sets it.
func (a *Apollo) SetWalletFromMnemonicWithPassphrase(mnemonic string, passphrase string) (*Apollo, error) {
w, err := NewBursaWalletWithPassphrase(mnemonic, passphrase)
if err != nil {
return a, err
}
a.wallet = w
return a, nil
}
// AddPayment adds a payment to the transaction.
func (a *Apollo) AddPayment(payment PaymentI) *Apollo {
a.payments = append(a.payments, payment)
return a
}
// AddLoadedUTxOs adds UTxOs to the available pool for coin selection.
func (a *Apollo) AddLoadedUTxOs(utxos ...common.Utxo) *Apollo {
a.utxos = append(a.utxos, utxos...)
return a
}
// AddInput adds a specific UTxO as a transaction input.
func (a *Apollo) AddInput(utxo common.Utxo) *Apollo {
a.preselectedUtxos = append(a.preselectedUtxos, utxo)
return a
}
// AddInputAddress adds an address whose UTxOs should be used for coin selection.
func (a *Apollo) AddInputAddress(addr common.Address) *Apollo {
a.inputAddresses = append(a.inputAddresses, addr)
return a
}
// AddRequiredSigner adds a required signer by key hash.
func (a *Apollo) AddRequiredSigner(pkh common.Blake2b224) *Apollo {
a.requiredSigners = append(a.requiredSigners, pkh)
return a
}
// AddRequiredSignerPaymentKey adds the payment key hash from an address as a required signer.
func (a *Apollo) AddRequiredSignerPaymentKey(addr common.Address) *Apollo {
a.requiredSigners = append(a.requiredSigners, addr.PaymentKeyHash())
return a
}
// AddRequiredSignerStakeKey adds the staking key hash from an address as a required signer.
func (a *Apollo) AddRequiredSignerStakeKey(addr common.Address) *Apollo {
skh := addr.StakeKeyHash()
if skh != (common.Blake2b224{}) {
a.requiredSigners = append(a.requiredSigners, skh)
}
return a
}
// SetTtl sets the transaction time-to-live.
func (a *Apollo) SetTtl(ttl int64) *Apollo {
a.Ttl = ttl
return a
}
// SetValidityStart sets the validity start slot.
func (a *Apollo) SetValidityStart(start int64) *Apollo {
a.ValidityStart = start
return a
}
// SetFee sets a specific fee (disables fee estimation).
func (a *Apollo) SetFee(fee int64) *Apollo {
a.Fee = fee
return a
}
// SetFeePadding adds additional fee padding.
func (a *Apollo) SetFeePadding(padding int64) *Apollo {
a.FeePadding = padding
return a
}
// SetCoinSelector sets the coin selection algorithm used by Complete to
// choose inputs. When unset, the package default selector is used.
func (a *Apollo) SetCoinSelector(selector CoinSelector) *Apollo {
a.coinSelector = selector
return a
}
// ForceFee sets a fixed fee for the transaction, bypassing automatic fee estimation.
func (a *Apollo) ForceFee(fee int64) *Apollo {
a.Fee = fee
a.forceFee = true
return a
}
// SetChangeAddress sets the address to receive change outputs.
func (a *Apollo) SetChangeAddress(addr common.Address) *Apollo {
a.changeAddress = &addr
return a
}
// AddCollateral adds a UTxO as collateral for script transactions.
func (a *Apollo) AddCollateral(utxo common.Utxo) *Apollo {
a.collaterals = append(a.collaterals, utxo)
return a
}
// AddDatum adds a datum to the witness set.
func (a *Apollo) AddDatum(datum *common.Datum) *Apollo {
if datum != nil {
a.datums = append(a.datums, *datum)
}
return a
}
// AddReferenceInput adds a reference input to the transaction.
func (a *Apollo) AddReferenceInput(txHash string, index int) (*Apollo, error) {
hashBytes, err := hex.DecodeString(txHash)
if err != nil {
return a, fmt.Errorf("invalid tx hash hex: %w", err)
}
if len(hashBytes) != common.Blake2b256Size {
return a, fmt.Errorf("invalid tx hash length: expected %d bytes, got %d", common.Blake2b256Size, len(hashBytes))
}
if index < 0 || index > math.MaxUint32 {
return a, fmt.Errorf("index must be 0-%d, got %d", math.MaxUint32, index)
}
var hash common.Blake2b256
copy(hash[:], hashBytes)
input := shelley.ShelleyTransactionInput{
TxId: hash,
OutputIndex: uint32(index),
}
a.referenceInputs = append(a.referenceInputs, input)
return a, nil
}
// Mint adds tokens to mint. If redeemer is provided, sets up script minting.
// When exUnits is nil, execution units will be estimated automatically.
func (a *Apollo) Mint(unit Unit, redeemer *common.Datum, exUnits *common.ExUnits) *Apollo {
// Redeemer indexes bind to mint policies in byte-wise sorted order; mixed-case
// hex would sort differently as a string than as bytes, misbinding redeemers.
unit.PolicyId = strings.ToLower(unit.PolicyId)
a.mint = append(a.mint, unit)
if redeemer != nil {
eu := common.ExUnits{}
if exUnits != nil {
eu = *exUnits
}
a.mintRedeemers[unit.PolicyId] = redeemerEntry{
Tag: common.RedeemerTagMint,
Data: *redeemer,
ExUnits: eu,
}
a.isEstimateRequired = true
}
return a
}
// AttachScript attaches a script to the witness set, deduplicating by hash.
// Accepts PlutusV1Script, PlutusV2Script, PlutusV3Script, or NativeScript.
func (a *Apollo) AttachScript(script common.Script) *Apollo {
hash := script.Hash().String()
if a.hasScriptHash(hash) {
return a
}
a.scriptHashes = append(a.scriptHashes, hash)
switch s := script.(type) {
case common.PlutusV1Script:
a.v1scripts = append(a.v1scripts, s)
case common.PlutusV2Script:
a.v2scripts = append(a.v2scripts, s)
case common.PlutusV3Script:
a.v3scripts = append(a.v3scripts, s)
case common.NativeScript:
a.nativescripts = append(a.nativescripts, s)
}
return a
}
// DisableExecutionUnitsEstimation disables automatic ExUnit estimation.
func (a *Apollo) DisableExecutionUnitsEstimation() *Apollo {
a.estimateExUnits = false
return a
}
// --- Smart Contract Methods ---
// CollectFrom adds a script UTxO as input with a spending redeemer.
func (a *Apollo) CollectFrom(utxo common.Utxo, redeemer common.Datum, exUnits common.ExUnits) *Apollo {
a.isEstimateRequired = true
a.preselectedUtxos = append(a.preselectedUtxos, utxo)
ref := utxoRef(utxo)
a.redeemers[ref] = redeemerEntry{
Tag: common.RedeemerTagSpend,
Data: redeemer,
ExUnits: exUnits,
}
return a
}
// PayToContract creates a payment to a script address with an inline datum.
func (a *Apollo) PayToContract(addr common.Address, datum *common.Datum, lovelace int64, units ...Unit) *Apollo {
p := &Payment{
Receiver: addr,
Lovelace: lovelace,
Units: units,
Datum: datum,
IsInline: true,
}
a.payments = append(a.payments, p)
return a
}
// PayToContractWithDatumHash creates a payment to a script address with a datum hash.
// The datum is added to the witness set and its hash is placed in the output.
func (a *Apollo) PayToContractWithDatumHash(addr common.Address, datum *common.Datum, lovelace int64, units ...Unit) (*Apollo, error) {
p := &Payment{
Receiver: addr,
Lovelace: lovelace,
Units: units,
}
if datum != nil {
datumCbor, err := cbor.Encode(datum)
if err != nil {
return a, fmt.Errorf("failed to encode datum: %w", err)
}
hash := common.Blake2b256Hash(datumCbor)
p.DatumHash = hash.Bytes()
a.datums = append(a.datums, *datum)
}
a.payments = append(a.payments, p)
return a, nil
}
// resolveCredential resolves a credential from various input types.
// Accepts: *common.Credential, common.Credential, common.Address, string (bech32), or nil (wallet fallback).
func (a *Apollo) resolveCredential(v any) (common.Credential, error) {
switch val := v.(type) {
case *common.Credential:
if val != nil {
return *val, nil
}
return a.GetStakeCredentialFromWallet()
case common.Credential:
return val, nil
case common.Address:
return GetStakeCredentialFromAddress(val)
case string:
addr, err := common.NewAddress(val)
if err != nil {
return common.Credential{}, fmt.Errorf("invalid bech32 address: %w", err)
}
return GetStakeCredentialFromAddress(addr)
case nil:
return a.GetStakeCredentialFromWallet()
default:
return common.Credential{}, fmt.Errorf("unsupported credential type: %T", v)
}
}
func (a *Apollo) hasScriptHash(hash string) bool {
return slices.Contains(a.scriptHashes, hash)
}
// --- Convenience Payment Methods ---
// PayToAddress creates a simple payment to an address.
func (a *Apollo) PayToAddress(addr common.Address, lovelace int64, units ...Unit) *Apollo {
p := &Payment{
Receiver: addr,
Lovelace: lovelace,
Units: units,
}
a.payments = append(a.payments, p)
return a
}
// PayToAddressWithReferenceScript pays to address with a reference script attached.
// The script type (V1/V2/V3/Native) is detected automatically.
func (a *Apollo) PayToAddressWithReferenceScript(addr common.Address, lovelace int64, script common.Script, units ...Unit) (*Apollo, error) {
ref, err := NewScriptRef(script)
if err != nil {
return a, fmt.Errorf("failed to create script ref: %w", err)
}
p := &Payment{Receiver: addr, Lovelace: lovelace, Units: units, ScriptRef: ref}
a.payments = append(a.payments, p)
return a, nil
}
// --- UTxO Consumption Methods ---
// ConsumeUTxO adds a utxo as input, deducts payments, and returns remainder as change.
func (a *Apollo) ConsumeUTxO(utxo common.Utxo, payments ...PaymentI) (*Apollo, error) {
utxoVal, err := a.utxoValue(utxo)
if err != nil {
return a, fmt.Errorf("failed to read UTxO value: %w", err)
}
totalPayments := Value{}
for _, p := range payments {
pv, err := p.ToValue()
if err != nil {
return a, fmt.Errorf("failed to compute payment value: %w", err)
}
totalPayments, err = totalPayments.Add(pv)
if err != nil {
return a, fmt.Errorf("payment value overflow: %w", err)
}
}
remainder, err := utxoVal.Sub(totalPayments)
if err != nil {
return a, fmt.Errorf("UTxO value insufficient for payments: %w", err)
}
if remainder.Coin > 0 || remainder.HasAssets() {
if a.wallet == nil {
return a, errors.New("wallet required to receive UTxO remainder")
}
}
// Mutate state only after all validation succeeds.
a.preselectedUtxos = append(a.preselectedUtxos, utxo)
a.payments = append(a.payments, payments...)
if remainder.Coin > 0 || remainder.HasAssets() {
remainderPayment, err := NewPaymentFromValue(a.wallet.Address(), remainder)
if err != nil {
return a, fmt.Errorf("failed to build remainder payment: %w", err)
}
a.payments = append(a.payments, remainderPayment)
}
return a, nil
}
func (a *Apollo) utxoValue(utxo common.Utxo) (Value, error) {
v := Value{}
amt := utxo.Output.Amount()
if amt != nil {
if !amt.IsUint64() {
return Value{}, errors.New("UTxO amount exceeds uint64 range")
}
v.Coin = amt.Uint64()
}
if utxo.Output.Assets() != nil {
v.Assets = CloneMultiAsset(utxo.Output.Assets())
}
return v, nil
}
// --- Staking Infrastructure ---
// GetStakeCredentialFromWallet extracts a staking credential from the wallet address.
func (a *Apollo) GetStakeCredentialFromWallet() (common.Credential, error) {
if a.wallet == nil {
return common.Credential{}, errors.New("no wallet set")
}
return GetStakeCredentialFromAddress(a.wallet.Address())
}
// SetCertificates sets the certificates for the transaction.
func (a *Apollo) SetCertificates(certs []common.CertificateWrapper) *Apollo {
a.certificates = certs
return a
}
// --- Stake Registration & Deregistration ---
// RegisterStake creates a stake registration certificate.
// credOrAddr can be: *common.Credential, common.Credential, common.Address, string (bech32), or nil (uses wallet).
func (a *Apollo) RegisterStake(credOrAddr any) (*Apollo, error) {
cred, err := a.resolveCredential(credOrAddr)
if err != nil {
return a, err
}
cert := common.StakeRegistrationCertificate{
CertType: uint(common.CertificateTypeStakeRegistration),
StakeCredential: cred,
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeStakeRegistration),
Certificate: &cert,
})
return a, nil
}
// DeregisterStake creates a stake deregistration certificate.
// credOrAddr can be: *common.Credential, common.Credential, common.Address, string (bech32), or nil (uses wallet).
func (a *Apollo) DeregisterStake(credOrAddr any) (*Apollo, error) {
cred, err := a.resolveCredential(credOrAddr)
if err != nil {
return a, err
}
cert := common.StakeDeregistrationCertificate{
CertType: uint(common.CertificateTypeStakeDeregistration),
StakeCredential: cred,
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeStakeDeregistration),
Certificate: &cert,
})
return a, nil
}
// --- Stake Delegation ---
// DelegateStake creates a stake delegation certificate.
// credOrAddr can be: *common.Credential, common.Credential, common.Address, string (bech32), or nil (uses wallet).
func (a *Apollo) DelegateStake(credOrAddr any, poolHash common.Blake2b224) (*Apollo, error) {
cred, err := a.resolveCredential(credOrAddr)
if err != nil {
return a, err
}
cert := common.StakeDelegationCertificate{
CertType: uint(common.CertificateTypeStakeDelegation),
StakeCredential: &cred,
PoolKeyHash: poolHash,
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeStakeDelegation),
Certificate: &cert,
})
return a, nil
}
// RegisterAndDelegateStake creates a combined stake registration and delegation certificate.
// credOrAddr can be: *common.Credential, common.Credential, common.Address, string (bech32), or nil (uses wallet).
func (a *Apollo) RegisterAndDelegateStake(credOrAddr any, poolHash common.Blake2b224, coin int64) (*Apollo, error) {
cred, err := a.resolveCredential(credOrAddr)
if err != nil {
return a, err
}
cert := common.StakeRegistrationDelegationCertificate{
CertType: uint(common.CertificateTypeStakeRegistrationDelegation),
StakeCredential: cred,
PoolKeyHash: poolHash,
Amount: coin,
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeStakeRegistrationDelegation),
Certificate: &cert,
})
return a, nil
}
// --- Vote Delegation ---
// DelegateVote creates a vote delegation certificate.
// credOrAddr can be: *common.Credential, common.Credential, common.Address, string (bech32), or nil (uses wallet).
func (a *Apollo) DelegateVote(credOrAddr any, drep common.Drep) (*Apollo, error) {
cred, err := a.resolveCredential(credOrAddr)
if err != nil {
return a, err
}
cert := common.VoteDelegationCertificate{
CertType: uint(common.CertificateTypeVoteDelegation),
StakeCredential: cred,
Drep: drep,
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeVoteDelegation),
Certificate: &cert,
})
return a, nil
}
// DelegateStakeAndVote creates a combined stake+vote delegation certificate.
// credOrAddr can be: *common.Credential, common.Credential, common.Address, string (bech32), or nil (uses wallet).
func (a *Apollo) DelegateStakeAndVote(credOrAddr any, poolHash common.Blake2b224, drep common.Drep) (*Apollo, error) {
cred, err := a.resolveCredential(credOrAddr)
if err != nil {
return a, err
}
cert := common.StakeVoteDelegationCertificate{
CertType: uint(common.CertificateTypeStakeVoteDelegation),
StakeCredential: cred,
PoolKeyHash: poolHash,
Drep: drep,
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeStakeVoteDelegation),
Certificate: &cert,
})
return a, nil
}
// RegisterAndDelegateVote creates a combined registration+vote delegation certificate.
// credOrAddr can be: *common.Credential, common.Credential, common.Address, string (bech32), or nil (uses wallet).
func (a *Apollo) RegisterAndDelegateVote(credOrAddr any, drep common.Drep, coin int64) (*Apollo, error) {
cred, err := a.resolveCredential(credOrAddr)
if err != nil {
return a, err
}
cert := common.VoteRegistrationDelegationCertificate{
CertType: uint(common.CertificateTypeVoteRegistrationDelegation),
StakeCredential: cred,
Drep: drep,
Amount: coin,
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeVoteRegistrationDelegation),
Certificate: &cert,
})
return a, nil
}
// RegisterAndDelegateStakeAndVote creates a combined registration+stake+vote delegation certificate.
// credOrAddr can be: *common.Credential, common.Credential, common.Address, string (bech32), or nil (uses wallet).
func (a *Apollo) RegisterAndDelegateStakeAndVote(credOrAddr any, poolHash common.Blake2b224, drep common.Drep, coin int64) (*Apollo, error) {
cred, err := a.resolveCredential(credOrAddr)
if err != nil {
return a, err
}
cert := common.StakeVoteRegistrationDelegationCertificate{
CertType: uint(common.CertificateTypeStakeVoteRegistrationDelegation),
StakeCredential: cred,
PoolKeyHash: poolHash,
Drep: drep,
Amount: coin,
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeStakeVoteRegistrationDelegation),
Certificate: &cert,
})
return a, nil
}
// --- Pool Operations ---
// RegisterPool adds a pool registration certificate.
func (a *Apollo) RegisterPool(params common.PoolRegistrationCertificate) *Apollo {
params.CertType = uint(common.CertificateTypePoolRegistration)
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypePoolRegistration),
Certificate: ¶ms,
})
return a
}
// RegisterDRep adds a DRep registration certificate.
func (a *Apollo) RegisterDRep(cred common.Credential, coin int64, anchor *common.GovAnchor) *Apollo {
if coin < 0 {
a.setErrOnce(errors.New("RegisterDRep: coin must be non-negative"))
return a
}
cert := common.RegistrationDrepCertificate{
CertType: uint(common.CertificateTypeRegistrationDrep),
DrepCredential: cred,
Amount: coin,
Anchor: cloneGovAnchor(anchor),
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeRegistrationDrep),
Certificate: &cert,
})
return a
}
// RetireDRep adds a DRep deregistration certificate.
func (a *Apollo) RetireDRep(cred common.Credential, coin int64) *Apollo {
if coin < 0 {
a.setErrOnce(errors.New("RetireDRep: coin must be non-negative"))
return a
}
cert := common.DeregistrationDrepCertificate{
CertType: uint(common.CertificateTypeDeregistrationDrep),
DrepCredential: cred,
Amount: coin,
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeDeregistrationDrep),
Certificate: &cert,
})
return a
}
// UpdateDRep adds a DRep update certificate.
func (a *Apollo) UpdateDRep(cred common.Credential, anchor *common.GovAnchor) *Apollo {
cert := common.UpdateDrepCertificate{
CertType: uint(common.CertificateTypeUpdateDrep),
DrepCredential: cred,
Anchor: cloneGovAnchor(anchor),
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeUpdateDrep),
Certificate: &cert,
})
return a
}
// AuthorizeCommitteeHotKey adds a committee hot key authorization certificate.
func (a *Apollo) AuthorizeCommitteeHotKey(cold common.Credential, hot common.Credential) *Apollo {
cert := common.AuthCommitteeHotCertificate{
CertType: uint(common.CertificateTypeAuthCommitteeHot),
ColdCredential: cold,
HotCredential: hot,
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeAuthCommitteeHot),
Certificate: &cert,
})
return a
}
// ResignCommitteeColdKey adds a committee cold key resignation certificate.
func (a *Apollo) ResignCommitteeColdKey(cold common.Credential, anchor *common.GovAnchor) *Apollo {
cert := common.ResignCommitteeColdCertificate{
CertType: uint(common.CertificateTypeResignCommitteeCold),
ColdCredential: cold,
Anchor: cloneGovAnchor(anchor),
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypeResignCommitteeCold),
Certificate: &cert,
})
return a
}
// DeregisterPool adds a pool retirement certificate.
func (a *Apollo) DeregisterPool(poolHash common.Blake2b224, epoch uint64) *Apollo {
cert := common.PoolRetirementCertificate{
CertType: uint(common.CertificateTypePoolRetirement),
PoolKeyHash: poolHash,
Epoch: epoch,
}
a.certificates = append(a.certificates, common.CertificateWrapper{
Type: uint(common.CertificateTypePoolRetirement),
Certificate: &cert,
})
return a
}
// --- Withdrawals ---
// AddWithdrawal adds a staking reward withdrawal to the transaction.
// For script-based withdrawals, provide a redeemer and execution units.
func (a *Apollo) AddWithdrawal(address common.Address, amount uint64, redeemerData *common.Datum, exUnits *common.ExUnits) *Apollo {
wdKey := address.String()
if existing, ok := a.withdrawals[wdKey]; ok {
if math.MaxUint64-existing.Amount < amount {
a.setErrOnce(fmt.Errorf("withdrawal amount overflow for %s", wdKey))
return a
}
amount += existing.Amount
}
a.withdrawals[wdKey] = withdrawalEntry{Address: address, Amount: amount}
if redeemerData != nil {
skh := address.StakeKeyHash()
if skh == (common.Blake2b224{}) {
a.setErrOnce(fmt.Errorf("withdrawal redeemer requires stake credential for %s", wdKey))
return a
}
key := hex.EncodeToString(skh.Bytes())
entry := redeemerEntry{
Tag: common.RedeemerTagReward,
Data: *redeemerData,
}
if exUnits != nil {
entry.ExUnits = *exUnits
}
if existing, ok := a.stakeRedeemers[key]; ok && !redeemerEntriesEqual(existing, entry) {
a.setErrOnce(fmt.Errorf("conflicting withdrawal redeemer for %s", wdKey))
return a
}
a.stakeRedeemers[key] = entry
a.isEstimateRequired = true
}
return a
}
// --- Metadata ---
// SetShelleyMetadata sets transaction metadata from a key-value map.
func (a *Apollo) SetShelleyMetadata(metadata map[uint64]any) *Apollo {
a.auxiliaryData = &auxData{metadata: metadata}
return a
}
// SetShelleyMetadataFromJSON parses cardano-cli no-schema metadata JSON and sets it.
func (a *Apollo) SetShelleyMetadataFromJSON(jsonData []byte) (*Apollo, error) {
return a.SetShelleyMetadataFromJSONWithSchema(jsonData, MetadataJSONNoSchema)
}
// SetShelleyMetadataFromJSONWithSchema parses metadata JSON with the selected schema and sets it.
func (a *Apollo) SetShelleyMetadataFromJSONWithSchema(jsonData []byte, schema MetadataJSONSchema) (*Apollo, error) {
metadata, err := ShelleyMetadataFromJSONWithSchema(jsonData, schema)
if err != nil {
return a, err
}
a.SetShelleyMetadata(metadata)
return a, nil
}
// SetCurrentTreasuryValue sets the Conway current treasury value field.
func (a *Apollo) SetCurrentTreasuryValue(value int64) *Apollo {
if value < 0 {
a.setErrOnce(errors.New("SetCurrentTreasuryValue: value must be non-negative"))
return a
}
a.currentTreasury = value
return a
}
// AddTreasuryDonation adds to the Conway treasury donation amount.
func (a *Apollo) AddTreasuryDonation(amount int64) *Apollo {
if amount < 0 {
a.setErrOnce(errors.New("AddTreasuryDonation: amount must be non-negative"))
return a
}
if math.MaxInt64-a.treasuryDonation < amount {
a.setErrOnce(errors.New("AddTreasuryDonation: donation amount overflow"))
return a
}
a.treasuryDonation += amount
return a
}
// AddVote adds or replaces a Conway governance vote for a voter/action pair.
func (a *Apollo) AddVote(voter common.Voter, actionId common.GovActionId, procedure common.VotingProcedure) *Apollo {
if a.votingProcedures == nil {
a.votingProcedures = make(common.VotingProcedures)
}
procedure.Anchor = cloneGovAnchor(procedure.Anchor)
voterKey := findVotingProcedureVoter(a.votingProcedures, voter)
if voterKey == nil {
voterCopy := voter
voterKey = &voterCopy
a.votingProcedures[voterKey] = make(map[*common.GovActionId]common.VotingProcedure)
}
actionVotes := a.votingProcedures[voterKey]
if actionVotes == nil {
actionVotes = make(map[*common.GovActionId]common.VotingProcedure)
a.votingProcedures[voterKey] = actionVotes
}
actionKey := findVotingProcedureAction(actionVotes, actionId)
if actionKey == nil {
actionCopy := actionId
actionKey = &actionCopy
}
actionVotes[actionKey] = procedure
return a
}
// AddProposal adds a Conway governance proposal procedure.
func (a *Apollo) AddProposal(proposal conway.ConwayProposalProcedure) *Apollo {
proposal.PPAnchor = *cloneGovAnchor(&proposal.PPAnchor)
a.proposalProcedures = append(a.proposalProcedures, proposal)
return a
}
// --- Signing & Witness Methods ---
// AddVerificationKeyWitness adds a VKey witness to the transaction.
func (a *Apollo) AddVerificationKeyWitness(witness common.VkeyWitness) (*Apollo, error) {
if a.tx == nil {
return a, errors.New("transaction not built - call Complete() first")
}
var witnesses []common.VkeyWitness
if existing := a.tx.WitnessSet.VkeyWitnesses.Items(); existing != nil {
witnesses = existing
}
witnesses = append(witnesses, witness)
a.tx.WitnessSet.VkeyWitnesses = cbor.NewSetType(witnesses, true)
return a, nil
}
// SignWithSkey signs the transaction with a raw secret key.
func (a *Apollo) SignWithSkey(skey []byte) (*Apollo, error) {
if a.tx == nil {
return a, errors.New("transaction not built - call Complete() first")
}
bodyCbor, err := cbor.Encode(&a.tx.Body)
if err != nil {
return a, fmt.Errorf("failed to encode tx body: %w", err)
}
a.tx.Body.SetCbor(bodyCbor)
// Hash the freshly encoded body directly; Body.Id() caches its hash and
// SetCbor does not invalidate the cache, so it could return a stale digest
// if the body was mutated after a previous Id() call.
txHash := common.Blake2b256Hash(bodyCbor)
witness, err := NewVkeyWitnessFromSkey(txHash, skey)
if err != nil {
return a, err
}
return a.AddVerificationKeyWitness(witness)
}
// --- Collateral ---
// SetCollateralAmount sets the target collateral amount.
func (a *Apollo) SetCollateralAmount(amount int64) *Apollo {
a.collateralAmount = amount
return a
}
// --- Transaction Loading & Utility Methods ---
// LoadTxCbor loads a transaction from hex-encoded CBOR.
func (a *Apollo) LoadTxCbor(txCbor string) (*Apollo, error) {
txBytes, err := hex.DecodeString(txCbor)
if err != nil {
return a, fmt.Errorf("invalid hex: %w", err)
}
var tx conway.ConwayTransaction
if _, err := cbor.Decode(txBytes, &tx); err != nil {
return a, fmt.Errorf("failed to decode transaction: %w", err)
}
a.tx = &tx
return a, nil
}
// Clone returns a deep copy of this Apollo builder.
func (a *Apollo) Clone() *Apollo {
clone := &Apollo{
Context: a.Context,
isEstimateRequired: a.isEstimateRequired,
Fee: a.Fee,
FeePadding: a.FeePadding,
forceFee: a.forceFee,
Ttl: a.Ttl,
ValidityStart: a.ValidityStart,
totalCollateral: a.totalCollateral,
collateralAmount: a.collateralAmount,
collateralOverlapRef: a.collateralOverlapRef,
collateralAutoSelected: a.collateralAutoSelected,
currentTreasury: a.currentTreasury,
treasuryDonation: a.treasuryDonation,
estimateExUnits: a.estimateExUnits,
wallet: a.wallet,
err: a.err,
redeemers: make(map[string]redeemerEntry),
stakeRedeemers: make(map[string]redeemerEntry),
mintRedeemers: make(map[string]redeemerEntry),
withdrawals: make(map[string]withdrawalEntry),
}
for _, p := range a.payments {
if pp, ok := p.(*Payment); ok {
cp := *pp
if len(pp.Units) > 0 {
cp.Units = make([]Unit, len(pp.Units))
copy(cp.Units, pp.Units)
}
if len(pp.DatumHash) > 0 {
cp.DatumHash = make([]byte, len(pp.DatumHash))
copy(cp.DatumHash, pp.DatumHash)
}
clone.payments = append(clone.payments, &cp)
} else {
clone.payments = append(clone.payments, p)
}
}
clone.utxos = append(clone.utxos, a.utxos...)
clone.preselectedUtxos = append(clone.preselectedUtxos, a.preselectedUtxos...)
clone.inputAddresses = append(clone.inputAddresses, a.inputAddresses...)
clone.datums = append(clone.datums, a.datums...)
clone.requiredSigners = append(clone.requiredSigners, a.requiredSigners...)
clone.v1scripts = append(clone.v1scripts, a.v1scripts...)
clone.v2scripts = append(clone.v2scripts, a.v2scripts...)
clone.v3scripts = append(clone.v3scripts, a.v3scripts...)
clone.mint = append(clone.mint, a.mint...)
clone.collaterals = append(clone.collaterals, a.collaterals...)
clone.referenceInputs = append(clone.referenceInputs, a.referenceInputs...)
clone.nativescripts = append(clone.nativescripts, a.nativescripts...)
clone.usedUtxos = make(map[string]bool, len(a.usedUtxos))
maps.Copy(clone.usedUtxos, a.usedUtxos)
clone.certificates = append(clone.certificates, a.certificates...)
clone.scriptHashes = append(clone.scriptHashes, a.scriptHashes...)
clone.proposalProcedures = append(clone.proposalProcedures, a.proposalProcedures...)
clone.votingProcedures = cloneVotingProcedures(a.votingProcedures)
maps.Copy(clone.redeemers, a.redeemers)
maps.Copy(clone.stakeRedeemers, a.stakeRedeemers)