-
Notifications
You must be signed in to change notification settings - Fork 211
/
Balance.hs
2178 lines (2014 loc) · 79.5 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 BangPatterns #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedLabels #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
-- |
-- Copyright: © 2021 IOHK
-- License: Apache-2.0
--
-- Provides an algorithm for producing a balanced coin selection with change,
-- where the fee is paid for.
--
-- This module uses the Random-Round-Robin coin selection algorithm for
-- multi-asset UTxO sets.
--
-- See documentation for the 'performSelection' function for more details on
-- how to perform a selection.
--
module Cardano.Wallet.Primitive.CoinSelection.Balance
(
-- * Performing a selection
PerformSelection
, performSelection
, performSelectionEmpty
, emptySkeleton
, SelectionConstraints (..)
, SelectionParams
, SelectionParamsOf (..)
, SelectionSkeleton (..)
, SelectionResult
, SelectionResultOf (..)
, SelectionError (..)
, BalanceInsufficientError (..)
, InsufficientMinCoinValueError (..)
, UnableToConstructChangeError (..)
-- * Selection limits
, SelectionLimit
, SelectionLimitOf (..)
, selectionLimitExceeded
, SelectionLimitReachedError (..)
, reduceSelectionLimitBy
-- * Querying selections
, SelectionDelta (..)
, selectionDeltaAllAssets
, selectionDeltaCoin
, selectionHasValidSurplus
, selectionSurplusCoin
, selectionMinimumCost
, selectionMaximumCost
, selectionSkeleton
-- * Querying parameters
, UTxOBalanceSufficiency (..)
, UTxOBalanceSufficiencyInfo (..)
, computeBalanceInOut
, computeDeficitInOut
, computeUTxOBalanceAvailable
, computeUTxOBalanceRequired
, computeUTxOBalanceSufficiency
, computeUTxOBalanceSufficiencyInfo
, isUTxOBalanceSufficient
-- * Running a selection (without making change)
, runSelection
, runSelectionNonEmpty
, runSelectionNonEmptyWith
, RunSelectionParams (..)
-- * Running a selection step
, runSelectionStep
, SelectionLens (..)
, assetSelectionLens
, coinSelectionLens
-- * Making change
, MakeChangeCriteria (..)
, makeChange
, makeChangeForCoin
, makeChangeForUserSpecifiedAsset
, makeChangeForNonUserSpecifiedAsset
, makeChangeForNonUserSpecifiedAssets
, assignCoinsToChangeMaps
, collateNonUserSpecifiedAssetQuantities
, addMintValueToChangeMaps
, addMintValuesToChangeMaps
, removeBurnValueFromChangeMaps
, removeBurnValuesFromChangeMaps
, reduceTokenQuantities
-- * Splitting bundles
, splitBundleIfAssetCountExcessive
, splitBundlesWithExcessiveAssetCounts
, splitBundlesWithExcessiveTokenQuantities
-- * Grouping and ungrouping
, groupByKey
, ungroupByKey
-- * Round-robin processing
, runRoundRobin
, runRoundRobinM
-- * Utility classes
, AssetCount (..)
-- * Utility functions
, distance
, mapMaybe
, balanceMissing
) where
import Prelude
import Algebra.PartialOrd
( PartialOrd (..) )
import Cardano.Numeric.Util
( padCoalesce )
import Cardano.Wallet.Primitive.Types.Address
( Address (..) )
import Cardano.Wallet.Primitive.Types.Coin
( Coin (..) )
import Cardano.Wallet.Primitive.Types.TokenBundle
( TokenBundle (..) )
import Cardano.Wallet.Primitive.Types.TokenMap
( AssetId, TokenMap )
import Cardano.Wallet.Primitive.Types.TokenQuantity
( TokenQuantity (..) )
import Cardano.Wallet.Primitive.Types.Tx
( TokenBundleSizeAssessment (..)
, TokenBundleSizeAssessor (..)
, TxIn
, TxOut (..)
, txOutMaxTokenQuantity
)
import Cardano.Wallet.Primitive.Types.UTxOIndex
( SelectionFilter (..), UTxOIndex (..) )
import Cardano.Wallet.Primitive.Types.UTxOSelection
( IsUTxOSelection, UTxOSelection, UTxOSelectionNonEmpty )
import Control.Monad.Extra
( andM )
import Control.Monad.Random.Class
( MonadRandom (..) )
import Data.Bifunctor
( first )
import Data.Either.Extra
( maybeToEither )
import Data.Function
( (&) )
import Data.Functor.Identity
( Identity (..) )
import Data.Generics.Internal.VL.Lens
( over, view )
import Data.Generics.Labels
()
import Data.IntCast
( intCast )
import Data.List.NonEmpty
( NonEmpty (..) )
import Data.Map.Strict
( Map )
import Data.Maybe
( fromMaybe )
import Data.Ord
( comparing )
import Data.Semigroup
( mtimesDefault )
import Data.Set
( Set )
import Fmt
( Buildable (..), Builder, blockMapF, nameF, unlinesF )
import GHC.Generics
( Generic )
import GHC.Stack
( HasCallStack )
import Numeric.Natural
( Natural )
import qualified Cardano.Wallet.Primitive.Types.Coin as Coin
import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle
import qualified Cardano.Wallet.Primitive.Types.TokenMap as TokenMap
import qualified Cardano.Wallet.Primitive.Types.TokenQuantity as TokenQuantity
import qualified Cardano.Wallet.Primitive.Types.UTxOIndex as UTxOIndex
import qualified Cardano.Wallet.Primitive.Types.UTxOSelection as UTxOSelection
import qualified Data.Foldable as F
import qualified Data.List as L
import qualified Data.List.NonEmpty as NE
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
--------------------------------------------------------------------------------
-- Performing a selection
--------------------------------------------------------------------------------
-- | Specifies all constraints required for coin selection.
--
-- Selection constraints:
--
-- - place limits on the coin selection algorithm, enabling it to produce
-- selections that are acceptable to the ledger.
--
-- - are dependent on the current set of protocol parameters.
--
-- - are not specific to a given selection.
--
data SelectionConstraints = SelectionConstraints
{ assessTokenBundleSize
:: TokenBundle -> TokenBundleSizeAssessment
-- ^ Assesses the size of a token bundle relative to the upper limit of
-- what can be included in a transaction output. See documentation for
-- the 'TokenBundleSizeAssessor' type to learn about the expected
-- properties of this field.
, computeMinimumAdaQuantity
:: TokenMap -> Coin
-- ^ Computes the minimum ada quantity required for a given output.
, computeMinimumCost
:: SelectionSkeleton -> Coin
-- ^ Computes the minimum cost of a given selection skeleton.
, computeSelectionLimit
:: [TxOut] -> SelectionLimit
-- ^ Computes an upper bound for the number of ordinary inputs to
-- select, given a current set of outputs.
}
deriving Generic
type SelectionParams = SelectionParamsOf [TxOut]
-- | Specifies all parameters that are specific to a given selection.
--
data SelectionParamsOf outputs = SelectionParams
{ outputsToCover
:: !outputs
-- ^ The complete set of outputs to be covered.
, utxoAvailable
:: !UTxOSelection
-- ^ Specifies a set of UTxOs that are available for selection as
-- inputs and optionally, a subset that has already been selected.
--
-- Further entries from this set will be selected to cover any deficit.
, extraCoinSource
:: !Coin
-- ^ An extra source of ada.
, extraCoinSink
:: !Coin
-- ^ An extra sink for ada.
, assetsToMint
:: !TokenMap
-- ^ Assets to mint: these provide input value to a transaction.
--
-- By minting tokens, we generally decrease the burden of the selection
-- algorithm, allowing it to select fewer UTxO entries in order to
-- cover the required outputs.
, assetsToBurn
:: !TokenMap
-- ^ Assets to burn: these consume output value from a transaction.
--
-- By burning tokens, we generally increase the burden of the selection
-- algorithm, requiring it to select more UTxO entries in order to
-- cover the burn.
}
deriving (Eq, Generic, Show)
-- | Indicates whether the balance of available UTxO entries is sufficient.
--
-- See 'computeUTxOBalanceSufficiency'.
--
data UTxOBalanceSufficiency
= UTxOBalanceSufficient
-- ^ Indicates that the UTxO balance is sufficient.
| UTxOBalanceInsufficient
-- ^ Indicates that the UTxO balance is insufficient.
deriving (Eq, Show)
-- | Gives more information about UTxO balance sufficiency.
--
-- See 'computeUTxOBalanceSufficiencyInfo'.
--
data UTxOBalanceSufficiencyInfo = UTxOBalanceSufficiencyInfo
{ available :: TokenBundle
-- ^ See 'computeUTxOBalanceAvailable'.
, required :: TokenBundle
-- ^ See 'computeUTxOBalanceRequired'.
, difference :: TokenBundle
-- ^ The difference between 'available' and 'required'.
, sufficiency :: UTxOBalanceSufficiency
-- ^ Whether or not the balance is sufficient.
}
deriving (Eq, Generic, Show)
-- | Computes the balance of UTxO entries available for selection.
--
computeUTxOBalanceAvailable
:: SelectionParamsOf (f TxOut)
-> TokenBundle
computeUTxOBalanceAvailable =
UTxOSelection.availableBalance . view #utxoAvailable
-- | Computes the balance of UTxO entries required to be selected.
--
computeUTxOBalanceRequired
:: Foldable f
=> SelectionParamsOf (f TxOut)
-> TokenBundle
computeUTxOBalanceRequired = fst . computeDeficitInOut
computeBalanceInOut
:: Foldable f
=> SelectionParamsOf (f TxOut)
-> (TokenBundle, TokenBundle)
computeBalanceInOut params =
(balanceIn, balanceOut)
where
balanceIn =
TokenBundle.fromTokenMap (view #assetsToMint params)
`TokenBundle.add`
TokenBundle.fromCoin (view #extraCoinSource params)
balanceOut =
TokenBundle.fromTokenMap (view #assetsToBurn params)
`TokenBundle.add`
TokenBundle.fromCoin (view #extraCoinSink params)
`TokenBundle.add`
F.foldMap (view #tokens) (view #outputsToCover params)
computeDeficitInOut
:: Foldable f
=> SelectionParamsOf (f TxOut)
-> (TokenBundle, TokenBundle)
computeDeficitInOut params =
(deficitIn, deficitOut)
where
deficitIn =
TokenBundle.difference balanceOut balanceIn
deficitOut =
TokenBundle.difference balanceIn balanceOut
(balanceIn, balanceOut) =
computeBalanceInOut params
-- | Computes the UTxO balance sufficiency.
--
-- See 'UTxOBalanceSufficiency'.
--
computeUTxOBalanceSufficiency
:: Foldable f
=> SelectionParamsOf (f TxOut)
-> UTxOBalanceSufficiency
computeUTxOBalanceSufficiency = sufficiency . computeUTxOBalanceSufficiencyInfo
-- | Computes information about the UTxO balance sufficiency.
--
-- See 'UTxOBalanceSufficiencyInfo'.
--
computeUTxOBalanceSufficiencyInfo
:: Foldable f
=> SelectionParamsOf (f TxOut)
-> UTxOBalanceSufficiencyInfo
computeUTxOBalanceSufficiencyInfo params =
UTxOBalanceSufficiencyInfo {available, required, difference, sufficiency}
where
available = computeUTxOBalanceAvailable params
required = computeUTxOBalanceRequired params
sufficiency =
if required `leq` available
then UTxOBalanceSufficient
else UTxOBalanceInsufficient
difference =
if sufficiency == UTxOBalanceSufficient
then TokenBundle.difference available required
else TokenBundle.difference required available
-- | Indicates whether or not the UTxO balance is sufficient.
--
-- The balance of available UTxO entries is sufficient if (and only if) it
-- is greater than or equal to the required balance.
--
isUTxOBalanceSufficient
:: Foldable f
=> SelectionParamsOf (f TxOut)
-> Bool
isUTxOBalanceSufficient params =
case computeUTxOBalanceSufficiency params of
UTxOBalanceSufficient -> True
UTxOBalanceInsufficient -> False
-- | A skeleton selection that can be used to estimate the cost of a final
-- selection.
--
-- Change outputs are deliberately stripped of their asset quantities, as the
-- fee estimation function must be agnostic to the magnitudes of these
-- quantities.
--
-- Increasing or decreasing the quantity of a particular asset in a change
-- output must not change the estimated cost of a selection.
--
data SelectionSkeleton = SelectionSkeleton
{ skeletonInputCount
:: !Int
, skeletonOutputs
:: ![TxOut]
, skeletonChange
:: ![Set AssetId]
}
deriving (Eq, Generic, Show)
-- | Creates an empty 'SelectionSkeleton'.
--
emptySkeleton :: SelectionSkeleton
emptySkeleton = SelectionSkeleton
{ skeletonInputCount = 0
, skeletonOutputs = mempty
, skeletonChange = mempty
}
-- | Specifies a limit to adhere to when performing a selection.
--
type SelectionLimit = SelectionLimitOf Int
data SelectionLimitOf a
= NoLimit
-- ^ Indicates that there is no limit.
| MaximumInputLimit a
-- ^ Indicates a maximum limit on the number of inputs to select.
deriving (Eq, Functor, Show)
instance Ord a => Ord (SelectionLimitOf a) where
compare a b = case (a, b) of
(NoLimit , NoLimit ) -> EQ
(MaximumInputLimit _, NoLimit ) -> LT
(NoLimit , MaximumInputLimit _) -> GT
(MaximumInputLimit x, MaximumInputLimit y) -> compare x y
-- | Indicates whether or not the given selection limit has been exceeded.
--
selectionLimitExceeded :: IsUTxOSelection s => s -> SelectionLimit -> Bool
selectionLimitExceeded s = \case
NoLimit -> False
MaximumInputLimit n -> UTxOSelection.selectedSize s > n
-- | Reduces a selection limit by a given reduction amount.
--
-- If the given reduction amount is positive, then this function will reduce
-- the selection limit by that amount.
--
-- If the given reduction amount is zero or negative, then this function will
-- return the original limit unchanged.
--
reduceSelectionLimitBy :: SelectionLimit -> Int -> SelectionLimit
reduceSelectionLimitBy limit reduction
| reduction <= 0 =
limit
| otherwise =
subtract reduction <$> limit
type SelectionResult = SelectionResultOf [TxOut]
-- | The result of performing a successful selection.
--
data SelectionResultOf outputs = SelectionResult
{ inputsSelected
:: !(NonEmpty (TxIn, TxOut))
-- ^ A (non-empty) list of inputs selected from 'utxoAvailable'.
, extraCoinSource
:: !Coin
-- ^ An extra source of ada.
, extraCoinSink
:: !Coin
-- ^ An extra sink for ada.
, outputsCovered
:: !outputs
-- ^ A list of outputs covered.
, changeGenerated
:: ![TokenBundle]
-- ^ A list of generated change outputs.
, assetsToMint
:: !TokenMap
-- ^ The assets to mint.
, assetsToBurn
:: !TokenMap
-- ^ The assets to burn.
}
deriving (Generic, Eq, Show)
-- | Indicates the difference between total input value and total output value
-- of a 'SelectionResult'.
--
-- There are two possibilities:
--
-- - 'SelectionSurplus'
--
-- Indicates a surplus, when the total input value is greater than or equal
-- to the total output value.
--
-- - 'SelectionDeficit'
--
-- Indicates a deficit, when the total input value is NOT greater than or
-- equal to the total output value.
--
data SelectionDelta a
= SelectionSurplus a
| SelectionDeficit a
deriving (Eq, Functor, Show)
instance Buildable a => Buildable (SelectionDelta a) where
build d = case d of
SelectionSurplus surplus -> buildMap [("surplus", build surplus)]
SelectionDeficit deficit -> buildMap [("deficit", build deficit)]
where
buildMap :: [(String, Builder)] -> Builder
buildMap = blockMapF . fmap (first $ id @String)
-- | Calculates the selection delta for all assets.
--
-- See 'SelectionDelta'.
--
selectionDeltaAllAssets
:: Foldable f => SelectionResultOf (f TxOut) -> SelectionDelta TokenBundle
selectionDeltaAllAssets result
| balanceOut `leq` balanceIn =
SelectionSurplus $ TokenBundle.difference balanceIn balanceOut
| otherwise =
SelectionDeficit $ TokenBundle.difference balanceOut balanceIn
where
balanceIn =
TokenBundle.fromTokenMap assetsToMint
`TokenBundle.add`
TokenBundle.fromCoin extraCoinSource
`TokenBundle.add`
F.foldMap (view #tokens . snd) inputsSelected
balanceOut =
TokenBundle.fromTokenMap assetsToBurn
`TokenBundle.add`
TokenBundle.fromCoin extraCoinSink
`TokenBundle.add`
F.foldMap (view #tokens) outputsCovered
`TokenBundle.add`
F.fold changeGenerated
SelectionResult
{ assetsToMint
, assetsToBurn
, extraCoinSource
, extraCoinSink
, inputsSelected
, outputsCovered
, changeGenerated
} = result
-- | Calculates the ada selection delta.
--
-- See 'SelectionDelta'.
--
selectionDeltaCoin
:: Foldable f => SelectionResultOf (f TxOut) -> SelectionDelta Coin
selectionDeltaCoin = fmap TokenBundle.getCoin . selectionDeltaAllAssets
-- | Indicates whether or not a selection result has a valid surplus.
--
selectionHasValidSurplus
:: Foldable f
=> SelectionConstraints
-> SelectionResultOf (f TxOut)
-> Bool
selectionHasValidSurplus constraints selection =
case selectionDeltaAllAssets selection of
SelectionSurplus s -> surplusIsValid s
SelectionDeficit _ -> False
where
surplusIsValid :: TokenBundle -> Bool
surplusIsValid = andM
[ surplusHasNoNonAdaAssets
, surplusNotBelowMinimumCost
, surplusNotAboveMaximumCost
]
-- None of the non-ada assets can have a surplus.
surplusHasNoNonAdaAssets :: TokenBundle -> Bool
surplusHasNoNonAdaAssets surplus =
view #tokens surplus == TokenMap.empty
-- The surplus must not be less than the minimum cost.
surplusNotBelowMinimumCost :: TokenBundle -> Bool
surplusNotBelowMinimumCost surplus =
view #coin surplus >= selectionMinimumCost constraints selection
-- The surplus must not be greater than the maximum cost.
surplusNotAboveMaximumCost :: TokenBundle -> Bool
surplusNotAboveMaximumCost surplus =
view #coin surplus <= selectionMaximumCost constraints selection
-- | Calculates the ada selection surplus, assuming there is a surplus.
--
-- If there is a surplus, then this function returns that surplus.
-- If there is a deficit, then this function returns zero.
--
-- Use 'selectionDeltaCoin' if you wish to handle the case where there is
-- a deficit.
--
selectionSurplusCoin :: Foldable f => SelectionResultOf (f TxOut) -> Coin
selectionSurplusCoin result =
case selectionDeltaCoin result of
SelectionSurplus surplus -> surplus
SelectionDeficit _ -> Coin 0
-- | Converts a selection into a skeleton.
--
selectionSkeleton
:: Foldable f => SelectionResultOf (f TxOut) -> SelectionSkeleton
selectionSkeleton s = SelectionSkeleton
{ skeletonInputCount = F.length (view #inputsSelected s)
, skeletonOutputs = F.toList (view #outputsCovered s)
, skeletonChange = TokenBundle.getAssets <$> view #changeGenerated s
}
-- | Computes the minimum required cost of a selection.
--
selectionMinimumCost
:: Foldable f
=> SelectionConstraints
-> SelectionResultOf (f TxOut)
-> Coin
selectionMinimumCost c = view #computeMinimumCost c . selectionSkeleton
-- | Computes the maximum acceptable cost of a selection.
--
-- This function acts as a safety limit to ensure that fees of selections
-- produced by 'performSelection' are not excessively high.
--
-- Ideally, we'd always be able to generate selections with fees that are
-- precisely equal to 'selectionMinimumCost'. However, in some situations
-- it may be necessary to exceed this cost very slightly.
--
-- This function provides a conservative upper bound to a selection cost
-- that we can reference from within property tests.
--
-- See 'selectionHasValidSurplus'.
--
selectionMaximumCost
:: Foldable f
=> SelectionConstraints
-> SelectionResultOf (f TxOut)
-> Coin
selectionMaximumCost c = mtimesDefault (2 :: Int) . selectionMinimumCost c
-- | Represents the set of errors that may occur while performing a selection.
--
data SelectionError
= BalanceInsufficient
BalanceInsufficientError
| SelectionLimitReached
SelectionLimitReachedError
| InsufficientMinCoinValues
(NonEmpty InsufficientMinCoinValueError)
| UnableToConstructChange
UnableToConstructChangeError
| EmptyUTxO
deriving (Generic, Eq, Show)
-- | Indicates that the balance of selected UTxO entries was insufficient to
-- cover the balance required while remaining within the selection limit.
--
data SelectionLimitReachedError = SelectionLimitReachedError
{ utxoBalanceRequired
:: !TokenBundle
-- ^ The UTXO balance required.
, inputsSelected
:: ![(TxIn, TxOut)]
-- ^ The inputs that could be selected while satisfying the
-- 'selectionLimit'.
, outputsToCover
:: !(NonEmpty TxOut)
} deriving (Generic, Eq, Show)
-- | Indicates that the balance of available UTxO entries is insufficient to
-- cover the balance required.
--
-- See 'computeUTxOBalanceSufficiency'.
--
data BalanceInsufficientError = BalanceInsufficientError
{ utxoBalanceAvailable
:: !TokenBundle
-- ^ The balance of 'utxoAvailable'.
, utxoBalanceRequired
:: !TokenBundle
-- ^ The balance of 'outputsToCover'.
} deriving (Generic, Eq, Show)
-- | Calculate the missing balance from a @BalanceInsufficientError@.
balanceMissing :: BalanceInsufficientError -> TokenBundle
balanceMissing (BalanceInsufficientError available required) =
TokenBundle.difference required available
-- | Indicates that a particular output does not have the minimum coin quantity
-- expected by the protocol.
--
-- See also: 'prepareOutputs'.
--
data InsufficientMinCoinValueError = InsufficientMinCoinValueError
{ outputWithInsufficientAda
:: !TxOut
-- ^ The particular output that does not have the minimum coin quantity
-- expected by the protocol.
, expectedMinCoinValue
:: !Coin
-- ^ The minimum coin quantity expected for this output.
} deriving (Generic, Eq, Show)
instance Buildable InsufficientMinCoinValueError where
build (InsufficientMinCoinValueError o c) = unlinesF
[ nameF "Expected min coin value" (build c)
, nameF "TxOut" (build o)
]
data UnableToConstructChangeError = UnableToConstructChangeError
{ requiredCost
:: !Coin
-- ^ The minimal required cost needed for the transaction to be
-- considered valid. This does not include min Ada values.
, shortfall
:: !Coin
-- ^ The additional coin quantity that would be required to cover the
-- selection cost and minimum coin quantity of each change output.
} deriving (Generic, Eq, Show)
type PerformSelection m outputs =
SelectionConstraints ->
SelectionParamsOf outputs ->
m (Either SelectionError (SelectionResultOf outputs))
-- | Performs a coin selection and generates change bundles in one step.
--
-- Provided that 'isUTxOBalanceSufficient' returns 'True' for the given
-- selection criteria, this function guarantees to return a 'SelectionResult'
-- for which 'selectionHasValidSurplus' returns 'True'.
--
performSelection
:: forall m. (HasCallStack, MonadRandom m)
=> PerformSelection m [TxOut]
performSelection = performSelectionEmpty performSelectionNonEmpty
-- | Transforms a coin selection function that requires a non-empty list of
-- outputs into a function that accepts an empty list of outputs.
--
-- If the original list is already non-empty, this function does not alter the
-- parameters or the result in any way, such that:
--
-- params == transformParams params
-- result == transformResult result
--
-- If the original list is empty, this function:
--
-- 1. applies a balance-preserving transformation to the parameters, adding
-- a single minimal ada-only output to act as a change generation target,
-- such that:
--
-- computeUTxOBalanceSufficiencyInfo params ==
-- computeUTxOBalanceSufficiencyInfo (transformParams params)
--
-- 2. applies an inverse transformation to the result, removing the output,
-- such that:
--
-- selectionSurplus result ==
-- selectionSurplus (transformResult result)
--
-- selectionHasValidSurplus constraints result ==>
-- selectionHasValidSurplus constraints (transformResult result)
--
performSelectionEmpty
:: Functor m
=> PerformSelection m (NonEmpty TxOut)
-> PerformSelection m [ TxOut]
performSelectionEmpty performSelectionFn constraints params =
fmap transformResult <$>
performSelectionFn constraints (transformParams params)
where
transformParams
:: SelectionParamsOf [ TxOut]
-> SelectionParamsOf (NonEmpty TxOut)
transformParams
= over #extraCoinSource
(transform (`Coin.addCoin` minCoin) (const id))
. over #outputsToCover
(transform (const (dummyOutput :| [])) (const . id))
transformResult
:: SelectionResultOf (NonEmpty TxOut)
-> SelectionResultOf [ TxOut]
transformResult
= over #extraCoinSource
(transform (`Coin.difference` minCoin) (const id))
. over #outputsCovered
(transform (const []) (const . F.toList))
transform :: a -> (NonEmpty TxOut -> a) -> a
transform x y = maybe x y $ NE.nonEmpty $ view #outputsToCover params
dummyOutput :: TxOut
dummyOutput = TxOut (Address "") $ TokenBundle.fromCoin minCoin
-- The 'performSelectionNonEmpty' function imposes a precondition that all
-- outputs must have at least the minimum ada quantity. Therefore, the
-- dummy output must also satisfy this condition.
--
-- However, we must also ensure that the value is non-zero, since:
--
-- 1. Under some cost models, the 'computeMinimumAdaQuantity' function
-- has a constant value of zero.
--
-- 2. The change generation algorithm requires that the total ada balance
-- of all outputs is non-zero.
--
minCoin :: Coin
minCoin = max
(Coin 1)
(view #computeMinimumAdaQuantity constraints TokenMap.empty)
performSelectionNonEmpty
:: forall m. (HasCallStack, MonadRandom m)
=> PerformSelection m (NonEmpty TxOut)
performSelectionNonEmpty constraints params
-- Is the total available UTXO balance sufficient?
| not utxoBalanceSufficient =
pure $ Left $ BalanceInsufficient $ BalanceInsufficientError
{utxoBalanceAvailable, utxoBalanceRequired}
-- Are the minimum ada quantities of the outputs too small?
| not (null insufficientMinCoinValues) =
pure $ Left $ InsufficientMinCoinValues $
NE.fromList insufficientMinCoinValues
| otherwise = do
maybeSelection <- runSelectionNonEmpty RunSelectionParams
{ selectionLimit
, utxoAvailable
, minimumBalance = utxoBalanceRequired
}
case maybeSelection of
Nothing | utxoAvailable == UTxOSelection.empty ->
pure $ Left EmptyUTxO
Nothing ->
selectionLimitReachedError []
Just selection | selectionLimitExceeded selection selectionLimit ->
selectionLimitReachedError $ F.toList $
UTxOSelection.selectedList selection
Just selection -> do
let utxoSelected = UTxOSelection.selectedIndex selection
let utxoBalanceSelected = UTxOIndex.balance utxoSelected
if utxoBalanceRequired `leq` utxoBalanceSelected
then makeChangeRepeatedly selection
else selectionLimitReachedError (UTxOIndex.toList utxoSelected)
where
SelectionConstraints
{ assessTokenBundleSize
, computeMinimumAdaQuantity
, computeMinimumCost
, computeSelectionLimit
} = constraints
SelectionParams
{ outputsToCover
, utxoAvailable
, extraCoinSource
, extraCoinSink
, assetsToMint
, assetsToBurn
} = params
selectionLimitReachedError :: [(TxIn, TxOut)] -> m (Either SelectionError a)
selectionLimitReachedError inputsSelected =
pure $ Left $ SelectionLimitReached $ SelectionLimitReachedError
{ inputsSelected
, utxoBalanceRequired
, outputsToCover
}
selectionLimit :: SelectionLimit
selectionLimit = computeSelectionLimit (F.toList outputsToCover)
utxoBalanceAvailable :: TokenBundle
utxoBalanceAvailable = computeUTxOBalanceAvailable params
utxoBalanceRequired :: TokenBundle
utxoBalanceRequired = computeUTxOBalanceRequired params
utxoBalanceSufficient :: Bool
utxoBalanceSufficient = isUTxOBalanceSufficient params
insufficientMinCoinValues :: [InsufficientMinCoinValueError]
insufficientMinCoinValues =
mapMaybe mkInsufficientMinCoinValueError outputsToCover
where
mkInsufficientMinCoinValueError
:: TxOut
-> Maybe InsufficientMinCoinValueError
mkInsufficientMinCoinValueError o
| view (#tokens . #coin) o >= expectedMinCoinValue =
Nothing
| otherwise =
Just $ InsufficientMinCoinValueError
{ expectedMinCoinValue, outputWithInsufficientAda = o }
where
expectedMinCoinValue = computeMinimumAdaQuantity
(view (#tokens . #tokens) o)
-- Given a UTxO index that corresponds to a valid selection covering
-- 'outputsToCover', 'predictChange' yields a non-empty list of assets
-- expected for change outputs.
--
-- There's a chicken-and-egg situation when it comes to calculating
-- transaction fees. On the one hand, we need to know the shape of the
-- final transaction to calculate its cost. But in order to construct the
-- transaction, we need to know what its cost is.
--
-- So, in order to not duplicate the logic from 'makeChange', we first
-- calculate a pre-selection considering the case where we have no fees to
-- pay, and no minimum value. This is *guaranteed to succeed* and will
-- yield a selection with change outputs in the final shape (modulo
-- amounts).
--
-- The result of calling 'predictChange' with a valid input selection
-- should satisfy:
--
-- length predictedChange === length outputsToCover
--
-- flat predictChange `isSubsetOf` assets selectedInputs
--
-- ∃ params. / isRight (performSelection params) =>
-- Right predictedChange === assets <$> performSelection params
--
-- (That is, the predicted change is necessarily equal to the change
-- assets of the final resulting selection).
--
predictChange
:: UTxOSelectionNonEmpty
-> [Set AssetId]
predictChange s = either
(const $ invariantResultWithNoCost $ UTxOSelection.selectedIndex s)
(fmap (TokenMap.getAssets . view #tokens))
(makeChange MakeChangeCriteria
{ minCoinFor = noMinimumCoin
, bundleSizeAssessor = TokenBundleSizeAssessor assessTokenBundleSize
, requiredCost = noCost
, extraCoinSource
, extraCoinSink
, inputBundles
, outputBundles
, assetsToMint
, assetsToBurn
}
)
where
inputBundles = view #tokens . snd <$> UTxOSelection.selectedList s
outputBundles = view #tokens <$> outputsToCover
noMinimumCoin :: TokenMap -> Coin
noMinimumCoin = const (Coin 0)
noCost :: Coin
noCost = Coin 0
-- This function takes the given selection skeleton as a way to evaluate
-- the cost of a final selection, and then calls 'makeChange' repeatedly
-- until it succeeds.
--
-- Between each call, it selects an extra ada-only input to inject
-- additional ada to construct change outputs.
--
-- Eventually it returns just a final selection, or 'Nothing' if no more
-- ada-only inputs are available.
--
-- This function also takes a set of tokens that are to be burned, and
-- hence although one or more inputs will be consumed for them, this
-- function won't make associated outputs for them.
--
makeChangeRepeatedly
:: UTxOSelectionNonEmpty
-> m (Either SelectionError (SelectionResultOf (NonEmpty TxOut)))
makeChangeRepeatedly s = case mChangeGenerated of
Right change | length change >= length outputsToCover ->
-- We've succeeded in making at least the optimal number of change
-- outputs, and can terminate here.
--
-- Note that we can't use an exact length equality check here, as
-- the 'makeChange' function will split up change outputs if they
-- are oversized in any way. (See 'splitOversizedMaps'.)
--
-- It is therefore possible for 'makeChange' to generate more change
-- outputs than the number of user-specified outputs.
--
pure $ Right $ mkSelectionResult change
Right change ->
-- We've succeeded in making change outputs, but the number of
-- change outputs is fewer than optimal, because the supply of ada