-
Notifications
You must be signed in to change notification settings - Fork 212
/
Balance.hs
1684 lines (1568 loc) · 57.2 KB
/
Balance.hs
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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NoFieldSelectors #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE OverloadedRecordDot #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{- HLINT ignore "Use ||" -}
module Internal.Cardano.Write.Tx.Balance
(
-- * Balancing transactions
balanceTransaction
, ErrBalanceTx (..)
, ErrBalanceTxAssetsInsufficientError (..)
, ErrBalanceTxInsufficientCollateralError (..)
, ErrBalanceTxInternalError (..)
, ErrBalanceTxOutputError (..)
, ErrBalanceTxOutputErrorInfo (..)
, ErrBalanceTxUnableToCreateChangeError (..)
, ErrAssignRedeemers (..)
-- * Change addresses
, ChangeAddressGen (..)
, assignChangeAddresses
-- * Partial transactions
, PartialTx (..)
, Redeemer (..)
-- * UTxO assumptions
, UTxOAssumptions (..)
-- * UTxO indices
, UTxOIndex
, constructUTxOIndex
-- * Utilities
, fromWalletUTxO
, toWalletUTxO
, splitSignedValue
, mergeSignedValue
-- ** updateTx
, TxUpdate (..)
, noTxUpdate
, updateTx
, TxFeeUpdate (..)
, ErrUpdateTx (..)
-- ** distributeSurplus
, distributeSurplus
, distributeSurplusDelta
, sizeOfCoin
, maximumCostOfIncreasingCoin
, costOfIncreasingCoin
, TxFeeAndChange (..)
, ErrMoreSurplusNeeded (..)
)
where
import Prelude
import Cardano.CoinSelection.Size
( TokenBundleSizeAssessment (..)
)
import Cardano.CoinSelection.UTxOSelection
( UTxOSelection
)
import Cardano.Ledger.Alonzo.Core
( ppCollateralPercentageL
, ppMaxCollateralInputsL
)
import Cardano.Ledger.Alonzo.Scripts
( AlonzoScript (..)
)
import Cardano.Ledger.Api
( BabbageEraTxBody (totalCollateralTxBodyL)
, Script
, ScriptHash
, StandardCrypto
, addrTxWitsL
, bodyTxL
, bootAddrTxWitsL
, coinTxOutL
, collateralInputsTxBodyL
, collateralReturnTxBodyL
, feeTxBodyL
, hashScript
, inputsTxBodyL
, outputsTxBodyL
, ppMaxTxSizeL
, scriptTxWitsL
, witsTxL
)
import Cardano.Ledger.BaseTypes
( StrictMaybe (..)
)
import Cardano.Ledger.Mary.Value
( MaryValue (MaryValue)
, MultiAsset (MultiAsset)
)
import Cardano.Ledger.UTxO
( txinLookup
)
import Control.Arrow
( left
)
import Control.Monad
( forM
, unless
, when
)
import Control.Monad.Random
( MonadRandom
)
import Control.Monad.Trans.Except
( ExceptT (ExceptT)
, catchE
, except
, throwE
, withExceptT
)
import Control.Monad.Trans.State
( runState
, state
)
import Data.Bits
( Bits
)
import Data.Either
( partitionEithers
)
import Data.Function
( on
, (&)
)
import Data.Functor
( (<&>)
)
import Data.Generics.Internal.VL.Lens
( over
, set
, view
, (^.)
)
import Data.Generics.Labels
()
import Data.Group
( Group (invert)
)
import Data.IntCast
( intCast
, intCastMaybe
)
import Data.List.NonEmpty
( NonEmpty (..)
)
import Data.Map
( Map
)
import Data.Maybe
( fromMaybe
, mapMaybe
)
import Data.Monoid.Monus
( Monus ((<\>))
)
import Data.Semigroup.Cancellative
( Reductive ((</>))
)
import Fmt
( Buildable
, Builder
, blockListF'
, build
, nameF
, pretty
)
import GHC.Generics
( Generic
)
import GHC.Stack
( HasCallStack
)
import Internal.Cardano.Write.Tx
( Address
, AssetName
, Coin (..)
, FeePerByte (..)
, IsRecentEra (..)
, KeyWitnessCounts (..)
, PParams
, PolicyId
, RecentEra (..)
, Tx
, TxBody
, TxIn
, TxOut
, UTxO (..)
, Value
, computeMinimumCoinForTxOut
, evaluateMinimumFee
, evaluateTransactionBalance
, feeOfBytes
, getFeePerByte
, isBelowMinimumCoinForTxOut
, maxScriptExecutionCost
)
import Internal.Cardano.Write.Tx.Balance.CoinSelection
( Selection
, SelectionBalanceError (..)
, SelectionCollateralError (..)
, SelectionCollateralRequirement (..)
, SelectionConstraints (..)
, SelectionError (..)
, SelectionOf (..)
, SelectionParams (..)
, SelectionStrategy (..)
, UnableToConstructChangeError (..)
, WalletSelectionContext
, WalletUTxO (..)
, performSelection
, toExternalUTxOMap
, toInternalUTxOMap
)
import Internal.Cardano.Write.Tx.Balance.TokenBundleSize
( mkTokenBundleSizeAssessor
)
import Internal.Cardano.Write.Tx.Redeemers
( ErrAssignRedeemers (..)
, Redeemer (..)
, assignScriptRedeemers
)
import Internal.Cardano.Write.Tx.Sign
( TimelockKeyWitnessCounts (..)
, estimateKeyWitnessCounts
, estimateSignedTxSize
)
import Internal.Cardano.Write.Tx.SizeEstimation
( TxSkeleton (..)
, assumedTxWitnessTag
, estimateTxCost
)
import Internal.Cardano.Write.Tx.TimeTranslation
( TimeTranslation
)
import Internal.Cardano.Write.UTxOAssumptions
( UTxOAssumptions (..)
, assumedInputScriptTemplate
)
import Numeric.Natural
( Natural
)
import Text.Pretty.Simple
( pShow
)
import qualified Cardano.Address.Script as CA
import qualified Cardano.CoinSelection.UTxOIndex as UTxOIndex
import qualified Cardano.CoinSelection.UTxOSelection as UTxOSelection
import qualified Cardano.Ledger.Core as Core
import qualified Cardano.Ledger.Val as Val
( coin
)
import qualified Cardano.Wallet.Primitive.Ledger.Convert as Convert
import qualified Cardano.Wallet.Primitive.Types.Address as W
( Address
)
import qualified Cardano.Wallet.Primitive.Types.AssetId as W
( AssetId (..)
)
import qualified Cardano.Wallet.Primitive.Types.Coin as W
( Coin (..)
)
import qualified Cardano.Wallet.Primitive.Types.Coin as W.Coin
import qualified Cardano.Wallet.Primitive.Types.TokenBundle as W
( TokenBundle (..)
)
import qualified Cardano.Wallet.Primitive.Types.TokenBundle as W.TokenBundle
import qualified Cardano.Wallet.Primitive.Types.TokenMap as W.TokenMap
import qualified Cardano.Wallet.Primitive.Types.TokenQuantity as W
( TokenQuantity (..)
)
import qualified Cardano.Wallet.Primitive.Types.Tx.Constraints as W
( TxSize (..)
, txOutMaxCoin
, txOutMaxTokenQuantity
)
import qualified Cardano.Wallet.Primitive.Types.Tx.TxIn as W
( TxIn
)
import qualified Cardano.Wallet.Primitive.Types.Tx.TxOut as W
( TxOut (..)
)
import qualified Cardano.Wallet.Primitive.Types.Tx.TxOut as W.TxOut
import qualified Cardano.Wallet.Primitive.Types.UTxO as W
( UTxO (..)
)
import qualified Data.Foldable as F
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import qualified Data.Map.Strict.Extra as Map
import qualified Data.Sequence.Strict as StrictSeq
import qualified Data.Set as Set
-- | Indicates a failure to select a sufficient amount of collateral.
--
data ErrBalanceTxInsufficientCollateralError era =
ErrBalanceTxInsufficientCollateralError
{ largestCombinationAvailable :: UTxO era
-- ^ The largest available combination of pure ada UTxOs.
, minimumCollateralAmount :: Coin
-- ^ The minimum quantity of ada necessary for collateral.
}
deriving Generic
deriving instance IsRecentEra era =>
Eq (ErrBalanceTxInsufficientCollateralError era)
deriving instance IsRecentEra era =>
Show (ErrBalanceTxInsufficientCollateralError era)
-- | Indicates that there was not enough ada available to create change outputs.
--
-- When creating a change output, ada is required in order to pay for:
--
-- - the minimum ada quantity required for that change output; and
-- - the marginal fee for including that output in the transaction.
--
data ErrBalanceTxUnableToCreateChangeError =
ErrBalanceTxUnableToCreateChangeError
{ requiredCost :: !Coin
-- ^ An estimate of the minimal fee required for this transaction to
-- be considered valid.
--
-- TODO: ADP-2547
-- Investigate whether this field is really appropriate and necessary,
-- and if not, remove it.
, shortfall :: !Coin
-- ^ The total additional quantity of ada required to pay for the
-- minimum ada quantities of all change outputs as well as the
-- marginal fee for including these outputs in the transaction.
}
deriving (Eq, Generic, Show)
-- | Indicates the insufficient availability of one or more assets.
--
-- This error is returned when the available quantity of one or more assets
-- is insufficient to balance the transaction.
--
-- The 'shortfall' field indicates the minimum extra quantity of each asset
-- that would be necessary to balance the transaction.
--
data ErrBalanceTxAssetsInsufficientError = ErrBalanceTxAssetsInsufficientError
{ available :: Value
-- ^ The total sum of all assets available.
, required :: Value
-- ^ The total sum of all assets required.
, shortfall :: Value
-- ^ The total shortfall between available and required assets.
}
deriving (Eq, Generic, Show)
data ErrBalanceTxInternalError era
= ErrUnderestimatedFee Coin (Tx era) KeyWitnessCounts
| ErrFailedBalancing Value
deriving instance IsRecentEra era => Eq (ErrBalanceTxInternalError era)
deriving instance IsRecentEra era => Show (ErrBalanceTxInternalError era)
-- | Errors that can occur when balancing transactions.
data ErrBalanceTx era
= ErrBalanceTxAssetsInsufficient ErrBalanceTxAssetsInsufficientError
| ErrBalanceTxMaxSizeLimitExceeded
| ErrBalanceTxExistingKeyWitnesses Int
-- ^ Indicates that a transaction could not be balanced because a given
-- number of existing key witnesses would be rendered invalid.
| ErrBalanceTxExistingCollateral
| ErrBalanceTxExistingTotalCollateral
| ErrBalanceTxExistingReturnCollateral
| ErrBalanceTxInsufficientCollateral
(ErrBalanceTxInsufficientCollateralError era)
| ErrBalanceTxConflictingNetworks
| ErrBalanceTxAssignRedeemers (ErrAssignRedeemers era)
| ErrBalanceTxInternalError (ErrBalanceTxInternalError era)
| ErrBalanceTxInputResolutionConflicts
(NonEmpty (TxOut era, TxOut era))
| ErrBalanceTxUnresolvedInputs (NonEmpty TxIn)
| ErrBalanceTxOutputError ErrBalanceTxOutputError
| ErrBalanceTxUnableToCreateChange ErrBalanceTxUnableToCreateChangeError
| ErrBalanceTxUnableToCreateInput
-- ^ Returned when __both__ of the following conditions are true:
-- - the given partial transaction has no existing inputs; and
-- - the given UTxO index is empty.
-- A transaction must have at least one input in order to be valid.
deriving Generic
deriving instance IsRecentEra era => Eq (ErrBalanceTx era)
deriving instance IsRecentEra era => Show (ErrBalanceTx era)
-- | A 'PartialTx' is an an unbalanced transaction along with the necessary
-- information to balance it.
--
-- The 'TxIn's of the 'inputs' must exactly match the inputs contained in the
-- 'tx'. If not, the behaviour is undefined. This will be fixed by ADP-1662.
--
-- The provided 'redeemers' will overwrite any redeemers inside the 'tx'. This
-- is done as the internal redeemers in the 'tx' use an index referring to a
-- 'TxIn', rather than an actual 'TxIn'. When we are adding extra inputs as part
-- of balancing, these indexes become incorrect.
--
-- TODO: With some extra care, we could probably remove the 'redeemers' field
-- and instead adjust the existing redeemer indexes ourselves when balancing,
-- even though they are in an "unordered" set.
data PartialTx era = PartialTx
{ tx :: Tx era
, extraUTxO :: UTxO era
, redeemers :: [Redeemer]
, timelockKeyWitnessCounts :: TimelockKeyWitnessCounts
-- ^ Specifying the intended number of timelock script key witnesses may
-- save space and fees when constructing a transaction.
--
-- Timelock scripts without entries in this map will have their key
-- witness counts estimated according to
-- 'estimateMaxWitnessRequiredPerInput'.
}
deriving Generic
deriving instance IsRecentEra era => Eq (PartialTx era)
deriving instance IsRecentEra era => Show (PartialTx era)
instance IsRecentEra era => Buildable (PartialTx era)
where
build PartialTx {tx, extraUTxO, redeemers, timelockKeyWitnessCounts}
= nameF "PartialTx" $ mconcat
[ nameF "extraUTxO"
(blockListF' "-" inF (Map.toList (unUTxO extraUTxO)))
, nameF "redeemers" (pretty redeemers)
, nameF "tx" (txF tx)
, nameF "intended timelock key witness counts"
$ blockListF' "-" (build . show)
$ Map.toList
$ getTimelockKeyWitnessCounts timelockKeyWitnessCounts
]
where
inF = build . show
txF :: Tx era -> Builder
txF tx' = pretty $ pShow tx'
data UTxOIndex era = UTxOIndex
{ availableUTxO :: !(UTxO era)
-- ^ The set of UTxOs that are available to spend.
, availableUTxOIndex :: !(UTxOIndex.UTxOIndex WalletUTxO)
-- ^ The set of UTxOs that are available to spend, in indexed form.
}
constructUTxOIndex
:: IsRecentEra era
=> UTxO era
-> UTxOIndex era
constructUTxOIndex availableUTxO =
UTxOIndex {availableUTxO, availableUTxOIndex}
where
availableUTxOIndex =
UTxOIndex.fromMap $ toInternalUTxOMap $ toWalletUTxO availableUTxO
fromWalletUTxO
:: forall era. IsRecentEra era
=> W.UTxO
-> UTxO era
fromWalletUTxO (W.UTxO m) = UTxO
$ Map.mapKeys Convert.toLedger
$ Map.map (toLedgerTxOut (recentEra @era)) m
toWalletUTxO
:: forall era. IsRecentEra era
=> UTxO era
-> W.UTxO
toWalletUTxO (UTxO m) = W.UTxO
$ Map.mapKeys Convert.toWallet
$ Map.map (toWalletTxOut (recentEra @era)) m
balanceTransaction
:: forall era m changeState.
( MonadRandom m
, IsRecentEra era
)
=> PParams era
-- Protocol parameters. Can be retrieved via Local State Query to a
-- local node.
--
-- If passed an incorrect value, a phase 1 script integrity hash mismatch
-- will protect against collateral being forfeited.
-> TimeTranslation
-- ^ Needed to convert convert validity intervals from 'UTCTime' to 'SlotNo'
-- when executing Plutus scripts.
--
-- Can be hard-coded for a given network configuration. Just be
-- cautious of the fact that the value will occasionally
-- change as new eras are introduced to Cardano.
--
-- It is unclear whether an incorrect value could cause collateral to be
-- forfeited. We should ideally investigate and clarify as part of ADP-1544
-- or similar ticket. Relevant ledger code:
-- https://github.com/IntersectMBO/cardano-ledger/blob/fdec04e8c071060a003263cdcb37e7319fb4dbf3/eras/alonzo/impl/src/Cardano/Ledger/Alonzo/TxInfo.hs#L428-L440
-> UTxOAssumptions
-> UTxOIndex era
-> ChangeAddressGen changeState
-> changeState
-> PartialTx era
-> ExceptT (ErrBalanceTx era) m (Tx era, changeState)
balanceTransaction
pp
timeTranslation
utxoAssumptions
UTxOIndex {availableUTxO, availableUTxOIndex}
genChange
s
PartialTx {extraUTxO, tx, redeemers, timelockKeyWitnessCounts}
= do
guardExistingCollateral
guardExistingReturnCollateral
guardExistingTotalCollateral
guardUTxOConsistency
externallySelectedUtxo <- extractExternallySelectedUTxO
let utxoSelection =
UTxOSelection.fromIndexPair
(availableUTxOIndex, externallySelectedUtxo)
when (UTxOSelection.availableSize utxoSelection == 0) $
throwE ErrBalanceTxUnableToCreateInput
balanceWith utxoSelection SelectionStrategyOptimal
`catchE` \e ->
if minimalStrategyIsWorthTrying e
then balanceWith utxoSelection SelectionStrategyMinimal
else throwE e
where
adjustedPartialTx :: Tx era
adjustedPartialTx = assignMinimalAdaQuantitiesToOutputsWithoutAda pp tx
balanceWith
:: UTxOSelection WalletUTxO
-> SelectionStrategy
-> ExceptT (ErrBalanceTx era) m (Tx era, changeState)
balanceWith utxoSelection strategy =
balanceTransactionWithSelectionStrategyAndNoZeroAdaAdjustment
pp
timeTranslation
utxoAssumptions
utxoReference
utxoSelection
genChange
s
strategy
redeemers
timelockKeyWitnessCounts
adjustedPartialTx
-- | Extract the inputs from the raw 'tx' of the 'Partialtx', with the
-- corresponding 'TxOut' according to @utxoReference@.
--
-- === Examples using pseudo-code
--
-- >>> let extraUTxO = {inA -> outA, inB -> outB }
-- >>> let tx = addInputs [inA] emptyTx
-- >>> let ptx = PartialTx tx extraUTxO []
-- >>> extractExternallySelectedUTxO ptx
-- Right (UTxOIndex.fromMap {inA -> outA})
--
-- >>> let extraUTxO = {inB -> outB }
-- >>> let tx = addInputs [inA, inC] emptyTx
-- >>> let ptx = PartialTx tx extraUTxO []
-- >>> extractExternallySelectedUTxO ptx
-- Left (ErrBalanceTxUnresolvedInputs [inA, inC])
extractExternallySelectedUTxO
:: ExceptT (ErrBalanceTx era) m (UTxOIndex.UTxOIndex WalletUTxO)
extractExternallySelectedUTxO = do
let res = flip map txIns $ \i-> do
case txinLookup i utxoReference of
Nothing ->
Left i
Just o -> do
let i' = Convert.toWallet i
let W.TxOut addr bundle = toWalletTxOut era o
pure (WalletUTxO i' addr, bundle)
case partitionEithers res of
([], resolved) ->
pure $ UTxOIndex.fromSequence resolved
(unresolvedInsHead:unresolvedInsTail, _) ->
throwE
. ErrBalanceTxUnresolvedInputs
$ (unresolvedInsHead :| unresolvedInsTail)
where
era = recentEra @era
txIns :: [TxIn]
txIns = Set.toList $ tx ^. bodyTxL . inputsTxBodyL
-- The set of all UTxOs that may be referenced by a balanced transaction.
--
-- Note that when constructing this set, we give precedence to UTxOs
-- provided as part of the 'PartialTx' object. This relies on the
-- left-biased nature of the 'Semigroup' 'mappend' operation on UTxO sets.
--
utxoReference :: UTxO era
utxoReference = mconcat [extraUTxO, availableUTxO]
guardExistingCollateral :: ExceptT (ErrBalanceTx era) m ()
guardExistingCollateral = do
-- Coin selection does not support pre-defining collateral. In Sep 2021
-- consensus was that we /could/ allow for it with just a day's work or
-- so, but that the need for it was unclear enough that it was not in
-- any way a priority.
let collIns = tx ^. bodyTxL . collateralInputsTxBodyL
unless (null collIns) $
throwE ErrBalanceTxExistingCollateral
guardExistingReturnCollateral :: ExceptT (ErrBalanceTx era) m ()
guardExistingReturnCollateral = do
let collRet = tx ^. bodyTxL . collateralReturnTxBodyL
case collRet of
SNothing -> return ()
SJust _ -> throwE ErrBalanceTxExistingReturnCollateral
guardExistingTotalCollateral :: ExceptT (ErrBalanceTx era) m ()
guardExistingTotalCollateral = do
let totColl = tx ^. bodyTxL . totalCollateralTxBodyL
case totColl of
SNothing -> return ()
SJust _ -> throwE ErrBalanceTxExistingTotalCollateral
-- | Ensures that the given UTxO sets are consistent with one another.
--
-- They are not consistent iff an input can be looked up in both UTxO sets
-- with different @Address@, or @TokenBundle@ values.
--
guardUTxOConsistency :: ExceptT (ErrBalanceTx era) m ()
guardUTxOConsistency =
case NE.nonEmpty (F.toList (conflicts extraUTxO availableUTxO)) of
Just cs -> throwE $ ErrBalanceTxInputResolutionConflicts cs
Nothing -> return ()
where
conflicts :: UTxO era -> UTxO era -> Map TxIn (TxOut era, TxOut era)
conflicts = Map.conflictsWith ((/=) `on` toWalletTxOut era) `on` unUTxO
era = recentEra @era
-- Determines whether or not the minimal selection strategy is worth trying.
-- This depends upon the way in which the optimal selection strategy failed.
minimalStrategyIsWorthTrying :: ErrBalanceTx era -> Bool
minimalStrategyIsWorthTrying e = or
[ maxSizeLimitExceeded
, unableToConstructChange
, selectionCollateralError
]
where
-- The size of a transaction can be reduced by selecting fewer inputs,
-- or by generating less change. Since the minimal selection strategy
-- selects as few inputs and generates as little change as possible,
-- using this strategy might allow us to generate a transaction within
-- the size limit.
maxSizeLimitExceeded = case e of
ErrBalanceTxMaxSizeLimitExceeded ->
True
_someOtherError ->
False
-- In situations where the available supply of ada is constrained, or
-- where all available ada is bundled up with other tokens, this can
-- prevent us from generating change. In this case, trying again with
-- the minimal selection strategy might allow us to select fewer
-- inputs, generate less change, lower the amount of ada required to
-- pay for the change, and therefore increase the chance that we can
-- generate change successfully.
unableToConstructChange = case e of
ErrBalanceTxUnableToCreateChange {} ->
True
_someOtherError ->
False
-- The minimum required amount of collateral depends on the transaction
-- fee, which in turn depends on the space occupied by ordinary inputs
-- and generated change. If we select fewer inputs and generate less
-- change, we can lower the transaction fee, lower the minimum required
-- amount of collateral, and increase the chance of being able to
-- satisfy the minimum.
selectionCollateralError = case e of
ErrBalanceTxInsufficientCollateral {} ->
True
_someOtherError ->
False
-- | Assigns minimal ada quantities to outputs without ada.
--
-- This function only modifies outputs with ada quantities of zero. Outputs
-- that have non-zero ada quantities will not be modified.
--
-- Minimal ada quantities are computed with the 'computeMinimumCoinForTxOut'
-- function.
--
assignMinimalAdaQuantitiesToOutputsWithoutAda
:: forall era. IsRecentEra era
=> PParams era
-> Tx era
-> Tx era
assignMinimalAdaQuantitiesToOutputsWithoutAda pp =
over (bodyTxL . outputsTxBodyL) (fmap modifyTxOut)
where
modifyTxOut
:: TxOut era
-> TxOut era
modifyTxOut out = flip (over coinTxOutL) out $ \c ->
if c == mempty then computeMinimumCoinForTxOut pp out else c
-- | Internal helper to 'balanceTransaction'
balanceTransactionWithSelectionStrategyAndNoZeroAdaAdjustment
:: forall era m changeState.
( MonadRandom m
, IsRecentEra era
)
=> PParams era
-> TimeTranslation
-> UTxOAssumptions
-> UTxO era
-- ^ The reference set of all UTxOs.
-> UTxOSelection WalletUTxO
-- ^ The set of UTxOs that may be spent by the resultant transaction.
-- The subset of UTxOs that are already spent are pre-selected.
-> ChangeAddressGen changeState
-> changeState
-> SelectionStrategy
-> [Redeemer]
-> TimelockKeyWitnessCounts
-> Tx era
-> ExceptT (ErrBalanceTx era) m (Tx era, changeState)
balanceTransactionWithSelectionStrategyAndNoZeroAdaAdjustment
pp
timeTranslation
utxoAssumptions
utxoReference
utxoSelection
genChange
s
selectionStrategy
redeemers
timelockKeyWitnessCounts
partialTx
= do
(balance0, minfee0, _) <- balanceAfterSettingMinFee partialTx
(extraInputs, extraCollateral', extraOutputs, s') <- do
-- NOTE: It is not possible to know the script execution cost in
-- advance because it actually depends on the final transaction. Inputs
-- selected as part of the fee balancing might have an influence on the
-- execution cost.
-- However, they are bounded so it is possible to balance the
-- transaction considering only the maximum cost, and only after, try to
-- adjust the change and ExUnits of each redeemer to something more
-- sensible than the max execution cost.
let
transform
:: Selection
-> ( [(W.TxIn, W.TxOut)]
, [(W.TxIn, W.TxOut)]
, [W.TxOut]
, changeState
)
transform sel =
let (sel', s') = assignChangeAddresses genChange sel s
inputs = F.toList (sel' ^. #inputs)
in ( inputs
, sel' ^. #collateral
, sel' ^. #change
, s'
)
let mSel = selectAssets
pp
utxoAssumptions
(F.toList $ partialTx ^. bodyTxL . outputsTxBodyL)
redeemers
utxoSelection
balance0
(Convert.toWalletCoin minfee0)
genChange
selectionStrategy
transform <$> mSel
-- NOTE:
-- Once the coin selection is done, we need to
--
-- (a) Add selected inputs, collateral and change outputs to the transaction
-- (b) Assign correct execution units to every redeemer
-- (c) Correctly reference redeemed entities with redeemer pointers
-- (d) Adjust fees and change output(s) to the new fees.
-- (e) If added inputs are native script originated coresponding scripts
-- need to be added as witnesses
--
-- There's a strong assumption that modifying the fee value AND increasing
-- the coin values of change outputs does not modify transaction fees; or
-- more exactly, does not modify the execution units of scripts. This is in
-- principle a fair assumption because script validators ought to be
-- unaware of change outputs. If their execution costs increase when change
-- output values increase, then it becomes impossible to guarantee that fee
-- balancing will ever converge towards a fixed point. A script validator
-- doing such a thing is considered bonkers and this is not a behavior we
-- ought to support.
let extraInputScripts =
case utxoAssumptions of
AllKeyPaymentCredentials -> []
AllByronKeyPaymentCredentials -> []
AllScriptPaymentCredentialsFrom _template toInpScripts ->
( toInpScripts
. Convert.toLedgerAddress
. view #address
. snd
) <$> extraInputs <> extraCollateral'
extraCollateral = fst <$> extraCollateral'
candidateTx <- assembleTransaction $ TxUpdate
{ extraInputs
, extraCollateral
, extraOutputs
, extraInputScripts
, feeUpdate = UseNewTxFee $ Convert.toWalletCoin minfee0
}
(balance, candidateMinFee, witCount) <-
balanceAfterSettingMinFee candidateTx
surplus <- case Val.coin balance of
(Coin c)
| c >= 0 ->
pure $ W.Coin.unsafeFromIntegral c
| otherwise ->
throwE
$ ErrBalanceTxInternalError
$ ErrUnderestimatedFee
(Coin (-c))
candidateTx
witCount
let feeAndChange = TxFeeAndChange
(Convert.toWalletCoin candidateMinFee)
(extraOutputs)
feePerByte = getFeePerByte pp
-- @distributeSurplus@ should never fail becase we have provided enough
-- padding in @selectAssets@.
TxFeeAndChange updatedFee updatedChange <- withExceptT
(\(ErrMoreSurplusNeeded c) ->
ErrBalanceTxInternalError
$ ErrUnderestimatedFee
(Convert.toLedgerCoin c)
candidateTx
witCount
)
(ExceptT . pure $
distributeSurplus feePerByte surplus feeAndChange)
fmap ((, s')) . guardTxSize witCount
=<< guardTxBalanced
=<< assembleTransaction
TxUpdate
{ extraInputs
, extraCollateral
, extraOutputs = updatedChange
, extraInputScripts
, feeUpdate = UseNewTxFee updatedFee
}
where
guardTxSize
:: KeyWitnessCounts
-> Tx era
-> ExceptT (ErrBalanceTx era) m (Tx era)
guardTxSize witCount tx = do
let maxSize = W.TxSize $ intCast (pp ^. ppMaxTxSizeL)
when (estimateSignedTxSize pp witCount tx > maxSize) $
throwE ErrBalanceTxMaxSizeLimitExceeded
pure tx
guardTxBalanced
:: Tx era
-> ExceptT (ErrBalanceTx era) m (Tx era)
guardTxBalanced tx = do
let bal = txBalance tx
if bal == mempty
then pure tx
else throwE
$ ErrBalanceTxInternalError
$ ErrFailedBalancing bal
txBalance :: Tx era -> Value
txBalance
= evaluateTransactionBalance pp utxoReference
. view bodyTxL
balanceAfterSettingMinFee
:: Tx era
-> ExceptT (ErrBalanceTx era) m (Value, Coin, KeyWitnessCounts)
balanceAfterSettingMinFee tx = ExceptT . pure $ do
let witCount =
estimateKeyWitnessCounts
utxoReference
tx
timelockKeyWitnessCounts
minfee = Convert.toWalletCoin $ evaluateMinimumFee pp tx witCount
update = TxUpdate [] [] [] [] (UseNewTxFee minfee)
tx' <- left updateTxErrorToBalanceTxError $ updateTx tx update
let balance = txBalance tx'
minfee' = Convert.toLedgerCoin minfee
return (balance, minfee', witCount)
assembleTransaction
:: TxUpdate
-> ExceptT (ErrBalanceTx era) m (Tx era)
assembleTransaction update = ExceptT . pure $ do
tx' <- left updateTxErrorToBalanceTxError
$ updateTx partialTx update
left ErrBalanceTxAssignRedeemers $
assignScriptRedeemers pp timeTranslation utxoReference redeemers tx'
-- | Select assets to cover the specified balance and fee.
--
-- If the transaction contains redeemers, the function will also ensure the
-- selection covers the fees for the maximum allowed execution units of a
-- transaction. For this, and other reasons, the selection may include too
-- much ada.
selectAssets
:: forall era m changeState.
( MonadRandom m
, IsRecentEra era
)
=> PParams era
-> UTxOAssumptions
-> [TxOut era]
-> [Redeemer]
-> UTxOSelection WalletUTxO
-- ^ Specifies which UTxOs are pre-selected, and which UTxOs can be used as
-- inputs or collateral.
-> Value
-- ^ Balance to cover.
-> W.Coin
-- ^ Current minimum fee (before selecting assets).
-> ChangeAddressGen changeState
-> SelectionStrategy
-- ^ A function to assess the size of a token bundle.
-> ExceptT (ErrBalanceTx era) m Selection
selectAssets pp utxoAssumptions outs' redeemers
utxoSelection balance fee0 changeGen selectionStrategy = do
except validateTxOutputs'
performSelection'
where
era = recentEra @era
outs = map fromLedgerTxOut outs'
fromLedgerTxOut :: TxOut era -> W.TxOut
fromLedgerTxOut o = case era of
RecentEraBabbage -> Convert.fromBabbageTxOut o
RecentEraConway -> Convert.fromConwayTxOut o
validateTxOutputs'
:: Either (ErrBalanceTx era) ()
validateTxOutputs'
= left ErrBalanceTxOutputError
$ validateTxOutputs selectionConstraints
(outs <&> \out -> (view #address out, view #tokens out))
performSelection'
:: ExceptT (ErrBalanceTx era) m Selection
performSelection'
= withExceptT coinSelectionErrorToBalanceTxError
$ performSelection selectionConstraints selectionParams
selectionConstraints = SelectionConstraints
{ tokenBundleSizeAssessor =
mkTokenBundleSizeAssessor pp
, computeMinimumAdaQuantity = \addr tokens -> Convert.toWallet $
computeMinimumCoinForTxOut
pp
(mkLedgerTxOut era addr (W.TokenBundle W.txOutMaxCoin tokens))
, isBelowMinimumAdaQuantity = \addr bundle ->
isBelowMinimumCoinForTxOut pp (mkLedgerTxOut era addr bundle)
, computeMinimumCost = \skeleton -> mconcat