-- Copyright 2026 Biglup Labs
-- SPDX-License-Identifier: Apache-2.0
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     https://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
{-# LANGUAGE OverloadedStrings #-}

-- | Owned selection domains, contextual invariants and private wire encoding.
module Cometa.Internal.CoinSelection
  ( Selector (..),
    Strategy (..),
    largestFirst,
    randomImprove,
    randomImproveWithSeed,
    randomImproveWithOptions,
    SelectionOptions (..),
    SelectionRequest,
    Selection (..),
    mkSelectionRequest,
    preselected,
    available,
    target,
    outputHints,
    changeAddress,
    parameters,
    validateSelection,
    encodeRequest,
    decodeRequest,
    encodeSelection,
    decodeSelection,
    select,
    checkChange,
  )
where

-- IMPORTS --------------------------------------------------------------------

import qualified Codec.CBOR.Decoding as D
import qualified Codec.CBOR.Encoding as E
import Cometa.Address (Address)
import qualified Cometa.Address as Address
import Cometa.AssetId (AssetId (Ada))
import Cometa.Error (Error (..))
import qualified Cometa.Internal.FFI.CoinSelection as Native
import qualified Cometa.Internal.ParameterSnapshot as Snapshot
import qualified Cometa.Internal.Runtime as Runtime
import qualified Cometa.Internal.TransactionCbor as Cbor
import qualified Cometa.Internal.TransactionValue as V
import Cometa.Protocol.Parameters (Parameters)
import qualified Cometa.Protocol.Parameters as Parameters
import Cometa.Transaction.Datum (Datum (NoDatum))
import Cometa.Transaction.Input (Input)
import Cometa.Transaction.Output (Output)
import qualified Cometa.Transaction.Output as Output
import Cometa.Transaction.Utxo (Utxo)
import qualified Cometa.Transaction.Utxo as Utxo
import Cometa.Value (Value)
import qualified Cometa.Value as Value
import Control.Monad (unless)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Int (Int64)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Word (Word64)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Ptr (castPtr)
import Foreign.Storable (peek)

-- TYPES ----------------------------------------------------------------------

-- | Application-supplied coin selection. The function receives an immutable,
-- validated request and returns the complete selection, remaining candidates and
-- change. Use 'select' to check contextual laws and change minimum Ada. Exceptions
-- propagate normally; 'Left' represents an expected selection failure.
newtype Selector = Selector
  { -- | Select all spending inputs, including mandatory preselected inputs.
    Selector -> SelectionRequest -> IO (Either Error Selection)
selectCoins :: SelectionRequest -> IO (Either Error Selection)
  }

-- | Random-improve input selection policy. Both policies may acquire more Ada
-- to fund change. Neither policy changes the authoritative target.
data Strategy
  = -- | Select enough of each asset to meet its required quantity.
    Minimal
  | -- | Attempt approximately twice the required quantity to improve change.
    Optimal
  deriving (Strategy -> Strategy -> Bool
(Strategy -> Strategy -> Bool)
-> (Strategy -> Strategy -> Bool) -> Eq Strategy
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Strategy -> Strategy -> Bool
== :: Strategy -> Strategy -> Bool
$c/= :: Strategy -> Strategy -> Bool
/= :: Strategy -> Strategy -> Bool
Eq, Eq Strategy
Eq Strategy =>
(Strategy -> Strategy -> Ordering)
-> (Strategy -> Strategy -> Bool)
-> (Strategy -> Strategy -> Bool)
-> (Strategy -> Strategy -> Bool)
-> (Strategy -> Strategy -> Bool)
-> (Strategy -> Strategy -> Strategy)
-> (Strategy -> Strategy -> Strategy)
-> Ord Strategy
Strategy -> Strategy -> Bool
Strategy -> Strategy -> Ordering
Strategy -> Strategy -> Strategy
forall a.
Eq a =>
(a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
$ccompare :: Strategy -> Strategy -> Ordering
compare :: Strategy -> Strategy -> Ordering
$c< :: Strategy -> Strategy -> Bool
< :: Strategy -> Strategy -> Bool
$c<= :: Strategy -> Strategy -> Bool
<= :: Strategy -> Strategy -> Bool
$c> :: Strategy -> Strategy -> Bool
> :: Strategy -> Strategy -> Bool
$c>= :: Strategy -> Strategy -> Bool
>= :: Strategy -> Strategy -> Bool
$cmax :: Strategy -> Strategy -> Strategy
max :: Strategy -> Strategy -> Strategy
$cmin :: Strategy -> Strategy -> Strategy
min :: Strategy -> Strategy -> Strategy
Ord, Int -> Strategy -> ShowS
[Strategy] -> ShowS
Strategy -> String
(Int -> Strategy -> ShowS)
-> (Strategy -> String) -> ([Strategy] -> ShowS) -> Show Strategy
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Strategy -> ShowS
showsPrec :: Int -> Strategy -> ShowS
$cshow :: Strategy -> String
show :: Strategy -> String
$cshowList :: [Strategy] -> ShowS
showList :: [Strategy] -> ShowS
Show, Strategy
Strategy -> Strategy -> Bounded Strategy
forall a. a -> a -> Bounded a
$cminBound :: Strategy
minBound :: Strategy
$cmaxBound :: Strategy
maxBound :: Strategy
Bounded, Int -> Strategy
Strategy -> Int
Strategy -> [Strategy]
Strategy -> Strategy
Strategy -> Strategy -> [Strategy]
Strategy -> Strategy -> Strategy -> [Strategy]
(Strategy -> Strategy)
-> (Strategy -> Strategy)
-> (Int -> Strategy)
-> (Strategy -> Int)
-> (Strategy -> [Strategy])
-> (Strategy -> Strategy -> [Strategy])
-> (Strategy -> Strategy -> [Strategy])
-> (Strategy -> Strategy -> Strategy -> [Strategy])
-> Enum Strategy
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
$csucc :: Strategy -> Strategy
succ :: Strategy -> Strategy
$cpred :: Strategy -> Strategy
pred :: Strategy -> Strategy
$ctoEnum :: Int -> Strategy
toEnum :: Int -> Strategy
$cfromEnum :: Strategy -> Int
fromEnum :: Strategy -> Int
$cenumFrom :: Strategy -> [Strategy]
enumFrom :: Strategy -> [Strategy]
$cenumFromThen :: Strategy -> Strategy -> [Strategy]
enumFromThen :: Strategy -> Strategy -> [Strategy]
$cenumFromTo :: Strategy -> Strategy -> [Strategy]
enumFromTo :: Strategy -> Strategy -> [Strategy]
$cenumFromThenTo :: Strategy -> Strategy -> Strategy -> [Strategy]
enumFromThenTo :: Strategy -> Strategy -> Strategy -> [Strategy]
Enum)

-- | Select the largest available quantities of required assets, with Ada last.
-- Aggregate eligible and hinted quantities must fit signed 64-bit arithmetic;
-- excessive minimum-Ada multiplication bounds return 'InvalidSelectionRequest'.
-- Output hints are ignored. A successful selection always spends an input,
-- including when the target is zero. Insufficient funding or change Ada returns
-- the native balance failure. Change respects a supplied maximum value size;
-- absent or zero maximum value size disables splitting.
largestFirst :: Selector
largestFirst :: Selector
largestFirst = Word64 -> Word64 -> Strategy -> Selector
nativeSelector Word64
0 Word64
0 Strategy
Optimal

-- | Round-robin random-improve with the 'Optimal' policy, seeded from the native
-- secure entropy source separately on every invocation. Aggregate bounds are
-- checked as for 'largestFirst'. Output hints influence
-- change shape, never the authoritative funding requirement.
randomImprove :: Selector
randomImprove :: Selector
randomImprove = Word64 -> Word64 -> Strategy -> Selector
nativeSelector Word64
1 Word64
0 Strategy
Optimal

-- | Deterministic random-improve using 'Optimal'. The same seed and request
-- replay the same selection on each call; this is not a persistent random stream.
randomImproveWithSeed :: Word64 -> Selector
randomImproveWithSeed :: Word64 -> Selector
randomImproveWithSeed Word64
seed = Word64 -> Strategy -> Selector
randomImproveWithOptions Word64
seed Strategy
Optimal

-- | Deterministic random-improve with an explicit seed and policy. Output hints
-- shape change; additional Ada inputs may be selected to satisfy minimum Ada.
-- Selection replays from the seed on each call. Deterministic replay applies to
-- the same library version; ordering can change between versions.
randomImproveWithOptions :: Word64 -> Strategy -> Selector
randomImproveWithOptions :: Word64 -> Strategy -> Selector
randomImproveWithOptions = Word64 -> Word64 -> Strategy -> Selector
nativeSelector Word64
2

-- Native selectors use independent operation-local owners; no mutable handle or
-- RNG state escapes. Validate aggregate arithmetic before native signed sums.
nativeSelector :: Word64 -> Word64 -> Strategy -> Selector
nativeSelector :: Word64 -> Word64 -> Strategy -> Selector
nativeSelector Word64
algorithm Word64
seed Strategy
strategy = (SelectionRequest -> IO (Either Error Selection)) -> Selector
Selector ((SelectionRequest -> IO (Either Error Selection)) -> Selector)
-> (SelectionRequest -> IO (Either Error Selection)) -> Selector
forall a b. (a -> b) -> a -> b
$ \SelectionRequest
request -> case SelectionRequest -> Either Error ()
validateNativeSelection SelectionRequest
request of
  Left Error
failure -> Either Error Selection -> IO (Either Error Selection)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Selection
forall a b. a -> Either a b
Left Error
failure)
  Right () -> ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error Selection))
-> IO (Either Error Selection)
forall a. ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a
Runtime.withBytes (SelectionRequest -> ByteString
encodeRequest (SelectionRequest -> SelectionRequest
disjointRequest SelectionRequest
request)) ((Ptr Word8 -> CSize -> IO (Either Error Selection))
 -> IO (Either Error Selection))
-> (Ptr Word8 -> CSize -> IO (Either Error Selection))
-> IO (Either Error Selection)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
bytes CSize
size -> do
    Either Error ByteString
response <- Text
-> (Ptr (Ptr Buffer) -> IO CUInt) -> IO (Either Error ByteString)
Runtime.withOwnedBuffer Text
"coinSelection.native" (CUInt
-> Word64
-> CUInt
-> Ptr Word8
-> CSize
-> Ptr (Ptr Buffer)
-> IO CUInt
Native.cNativeSelect (Word64 -> CUInt
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word64
algorithm) Word64
seed (if Strategy
strategy Strategy -> Strategy -> Bool
forall a. Eq a => a -> a -> Bool
== Strategy
Minimal then CUInt
0 else CUInt
1) Ptr Word8
bytes CSize
size)
    Either Error Selection -> IO (Either Error Selection)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error ByteString
response Either Error ByteString
-> (ByteString -> Either Error Selection) -> Either Error Selection
forall a b.
Either Error a -> (a -> Either Error b) -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ByteString -> Either Error Selection
decodeSelection)

-- Native random-improve concatenates mandatory and available pools without
-- deduplicating. P09 permits identical overlap, so marshal only optional
-- candidates; returned remaining is unchanged because mandatory is selected.
disjointRequest :: SelectionRequest -> SelectionRequest
disjointRequest :: SelectionRequest -> SelectionRequest
disjointRequest request :: SelectionRequest
request@(SelectionRequest SelectionOptions
options) = SelectionOptions -> SelectionRequest
SelectionRequest SelectionOptions
options {selectionAvailable = filter (\Utxo
item -> Input -> Map Input () -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.notMember (Utxo -> Input
Utxo.input Utxo
item) Map Input ()
mandatory) (available request)}
  where
    mandatory :: Map Input ()
mandatory = [(Input, ())] -> Map Input ()
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(Utxo -> Input
Utxo.input Utxo
item, ()) | Utxo
item <- SelectionRequest -> [Utxo]
preselected SelectionRequest
request]

validateNativeSelection :: SelectionRequest -> Either Error ()
validateNativeSelection :: SelectionRequest -> Either Error ()
validateNativeSelection SelectionRequest
request = do
  let eligible :: [Utxo]
eligible = Map Input Utxo -> [Utxo]
forall k a. Map k a -> [a]
Map.elems ([(Input, Utxo)] -> Map Input Utxo
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(Utxo -> Input
Utxo.input Utxo
item, Utxo
item) | Utxo
item <- SelectionRequest -> [Utxo]
preselected SelectionRequest
request [Utxo] -> [Utxo] -> [Utxo]
forall a. [a] -> [a] -> [a]
++ SelectionRequest -> [Utxo]
available SelectionRequest
request])
      total :: Value
total = [Utxo] -> Value
sumUtxos [Utxo]
eligible
      capacity :: Value
capacity = Value
total Value -> Value -> Value
forall a. Semigroup a => a -> a -> a
<> [(AssetId, Integer)] -> Value
Value.fromList [(AssetId
asset, Integer -> Integer
forall a. Num a => a -> a
negate Integer
amount) | (AssetId
asset, Integer
amount) <- Value -> [(AssetId, Integer)]
Value.toList (SelectionRequest -> Value
target SelectionRequest
request), Integer
amount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
0]
      hints :: Value
hints = Value -> ([Output] -> Value) -> Maybe [Output] -> Value
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Value
forall a. Monoid a => a
mempty ((Output -> Value) -> [Output] -> Value
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap Output -> Value
Output.value) (SelectionRequest -> Maybe [Output]
outputHints SelectionRequest
request)
      maps :: Int
maps = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
1 (Int -> ([Output] -> Int) -> Maybe [Output] -> Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Int
0 [Output] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (SelectionRequest -> Maybe [Output]
outputHints SelectionRequest
request))
      assets :: Int
assets = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
1 ([(AssetId, Integer)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length (((AssetId, Integer) -> Bool)
-> [(AssetId, Integer)] -> [(AssetId, Integer)]
forall a. (a -> Bool) -> [a] -> [a]
filter ((AssetId -> AssetId -> Bool
forall a. Eq a => a -> a -> Bool
/= AssetId
Ada) (AssetId -> Bool)
-> ((AssetId, Integer) -> AssetId) -> (AssetId, Integer) -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (AssetId, Integer) -> AssetId
forall a b. (a, b) -> a
fst) (Value -> [(AssetId, Integer)]
Value.toList Value
capacity)))
      outputCount :: Integer
outputCount = Int -> Integer
forall a. Integral a => a -> Integer
toInteger Int
maps Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Int -> Integer
forall a. Integral a => a -> Integer
toInteger Int
assets
      validate :: Value -> Either Error ()
validate Value
value = case Value -> Either Error ()
V.validateOutput Value
value of
        Left Error
_ -> Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelectionRequest Text
"Native selection aggregate quantities exceed int64")
        Right () -> () -> Either Error ()
forall a b. b -> Either a b
Right ()
  Value -> Either Error ()
validate Value
total
  Value -> Either Error ()
validate Value
capacity
  Value -> Either Error ()
validate Value
hints
  -- The aggregate output bounds every possible split change output's encoded
  -- size. Bound all possible split maps as native largest-first accumulates their
  -- unsigned minimum Ada and casts that sum to int64. Include fixed overhead
  -- and worst coin-width growth, including shape-hinted empty maps.
  Output
output <- Address -> Value -> Datum -> Maybe Script -> Either Error Output
Output.mkOutput (SelectionRequest -> Address
changeAddress SelectionRequest
request) Value
capacity Datum
NoDatum Maybe Script
forall a. Maybe a
Nothing
  case Parameters -> Maybe Word64
Parameters.parameterAdaPerUtxoByte (SelectionRequest -> Parameters
parameters SelectionRequest
request) of
    Just Word64
cost -> Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
cost Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* (Int -> Integer
forall a. Integral a => a -> Integer
toInteger (ByteString -> Int
B.length (Output -> ByteString
Output.encodeCbor Output
output)) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
168) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
outputCount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
maxBound :: Int64)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelectionRequest Text
"Native change minimum Ada arithmetic exceeds int64"))
    Maybe Word64
Nothing -> Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelectionRequest Text
"Ada per UTxO byte is required")

-- | Named input to request validation. Candidate lists must have unique
-- references. Identical references may occur once in both lists; conflicting
-- resolved outputs are rejected. Preselected inputs may be outside available.
data SelectionOptions = SelectionOptions
  { -- | Mandatory selected inputs. Each must survive in a successful selection.
    SelectionOptions -> [Utxo]
selectionPreselected :: ![Utxo],
    -- | Eligible candidate inputs, including any optional overlap with preselected.
    SelectionOptions -> [Utxo]
selectionAvailable :: ![Utxo],
    -- | Authoritative signed value to fund, including externally assessed fees,
    -- deposits, withdrawals and mint. Negative components are implicit surplus
    -- that must return as change. Ada counts lovelace; quantities fit Int64.
    SelectionOptions -> Value
selectionTarget :: !Value,
    -- | Optional output-shape hints, independent of authoritative target arithmetic.
    SelectionOptions -> Maybe [Output]
selectionOutputHints :: !(Maybe [Output]),
    -- | Required destination for every generated change output.
    SelectionOptions -> Address
selectionChangeAddress :: !Address,
    -- | Current protocol snapshot. Ada-per-UTxO-byte must be present for change
    -- minimum-Ada validation. This does not promise consistent chain observations.
    SelectionOptions -> Parameters
selectionParameters :: !Parameters
  }
  deriving (SelectionOptions -> SelectionOptions -> Bool
(SelectionOptions -> SelectionOptions -> Bool)
-> (SelectionOptions -> SelectionOptions -> Bool)
-> Eq SelectionOptions
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SelectionOptions -> SelectionOptions -> Bool
== :: SelectionOptions -> SelectionOptions -> Bool
$c/= :: SelectionOptions -> SelectionOptions -> Bool
/= :: SelectionOptions -> SelectionOptions -> Bool
Eq, Int -> SelectionOptions -> ShowS
[SelectionOptions] -> ShowS
SelectionOptions -> String
(Int -> SelectionOptions -> ShowS)
-> (SelectionOptions -> String)
-> ([SelectionOptions] -> ShowS)
-> Show SelectionOptions
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SelectionOptions -> ShowS
showsPrec :: Int -> SelectionOptions -> ShowS
$cshow :: SelectionOptions -> String
show :: SelectionOptions -> String
$cshowList :: [SelectionOptions] -> ShowS
showList :: [SelectionOptions] -> ShowS
Show)

-- | Validated request. Equality compares all owned fields and preserves list
-- order; validation does not select coins or access chain state.
newtype SelectionRequest = SelectionRequest SelectionOptions deriving (SelectionRequest -> SelectionRequest -> Bool
(SelectionRequest -> SelectionRequest -> Bool)
-> (SelectionRequest -> SelectionRequest -> Bool)
-> Eq SelectionRequest
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: SelectionRequest -> SelectionRequest -> Bool
== :: SelectionRequest -> SelectionRequest -> Bool
$c/= :: SelectionRequest -> SelectionRequest -> Bool
/= :: SelectionRequest -> SelectionRequest -> Bool
Eq, Int -> SelectionRequest -> ShowS
[SelectionRequest] -> ShowS
SelectionRequest -> String
(Int -> SelectionRequest -> ShowS)
-> (SelectionRequest -> String)
-> ([SelectionRequest] -> ShowS)
-> Show SelectionRequest
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> SelectionRequest -> ShowS
showsPrec :: Int -> SelectionRequest -> ShowS
$cshow :: SelectionRequest -> String
show :: SelectionRequest -> String
$cshowList :: [SelectionRequest] -> ShowS
showList :: [SelectionRequest] -> ShowS
Show)

-- | Full selection result. Assembly is total; 'select' checks contextual
-- eligibility, balance, remaining candidates, change destination and minimum Ada.
-- Equality compares list order and semantic fields; no random-choice equivalence
-- is implied. Empty change means an exact target match.
data Selection = Selection
  { -- | Complete selected inputs, including the preselected inputs, with unique refs.
    Selection -> [Utxo]
selected :: ![Utxo],
    -- | Exactly the available candidates not selected, with unique references.
    Selection -> [Utxo]
remaining :: ![Utxo],
    -- | Locally balanced outputs returning all excess value to the change address.
    Selection -> [Output]
change :: ![Output]
  }
  deriving (Selection -> Selection -> Bool
(Selection -> Selection -> Bool)
-> (Selection -> Selection -> Bool) -> Eq Selection
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Selection -> Selection -> Bool
== :: Selection -> Selection -> Bool
$c/= :: Selection -> Selection -> Bool
/= :: Selection -> Selection -> Bool
Eq, Int -> Selection -> ShowS
[Selection] -> ShowS
Selection -> String
(Int -> Selection -> ShowS)
-> (Selection -> String)
-> ([Selection] -> ShowS)
-> Show Selection
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Selection -> ShowS
showsPrec :: Int -> Selection -> ShowS
$cshow :: Selection -> String
show :: Selection -> String
$cshowList :: [Selection] -> ShowS
showList :: [Selection] -> ShowS
Show)

-- DEFINITIONS ----------------------------------------------------------------

-- | Validate unique references and nonconflicting overlapping snapshots, a
-- signed native-range target, an available Ada-per-UTxO-byte parameter,
-- and supported parameter bounds. Failure returns 'InvalidSelectionRequest' or
-- 'InvalidParameterSnapshot'. This does not query input eligibility on chain.
mkSelectionRequest :: SelectionOptions -> Either Error SelectionRequest
mkSelectionRequest :: SelectionOptions -> Either Error SelectionRequest
mkSelectionRequest SelectionOptions
options = do
  Map Input Utxo
mandatory <- Error -> [Utxo] -> Either Error (Map Input Utxo)
indexUtxos (Text -> Error
InvalidSelectionRequest Text
"Duplicate preselected reference") (SelectionOptions -> [Utxo]
selectionPreselected SelectionOptions
options)
  Map Input Utxo
candidates <- Error -> [Utxo] -> Either Error (Map Input Utxo)
indexUtxos (Text -> Error
InvalidSelectionRequest Text
"Duplicate available reference") (SelectionOptions -> [Utxo]
selectionAvailable SelectionOptions
options)
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
and (Map Input Bool -> [Bool]
forall k a. Map k a -> [a]
Map.elems ((Utxo -> Utxo -> Bool)
-> Map Input Utxo -> Map Input Utxo -> Map Input Bool
forall k a b c.
Ord k =>
(a -> b -> c) -> Map k a -> Map k b -> Map k c
Map.intersectionWith Utxo -> Utxo -> Bool
forall a. Eq a => a -> a -> Bool
(==) Map Input Utxo
mandatory Map Input Utxo
candidates))) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelectionRequest Text
"Conflicting overlapping UTxO snapshots"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless
    (((AssetId, Integer) -> Bool) -> [(AssetId, Integer)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (\(AssetId
_, Integer
quantity) -> Integer
quantity Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
minBound :: Int64) Bool -> Bool -> Bool
&& Integer
quantity Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Int64
forall a. Bounded a => a
maxBound :: Int64)) (Value -> [(AssetId, Integer)]
Value.toList (SelectionOptions -> Value
selectionTarget SelectionOptions
options)))
    (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelectionRequest Text
"Target quantities must fit int64"))
  case Parameters -> Maybe Word64
Parameters.parameterAdaPerUtxoByte (SelectionOptions -> Parameters
selectionParameters SelectionOptions
options) of
    Maybe Word64
Nothing -> Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelectionRequest Text
"Ada per UTxO byte is required")
    Just Word64
_ -> () -> Either Error ()
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  Parameters -> Either Error ()
Snapshot.validateNative (SelectionOptions -> Parameters
selectionParameters SelectionOptions
options)
  SelectionRequest -> Either Error SelectionRequest
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (SelectionOptions -> SelectionRequest
SelectionRequest SelectionOptions
options)

-- | Mandatory input snapshots in caller order.
preselected :: SelectionRequest -> [Utxo]
preselected :: SelectionRequest -> [Utxo]
preselected (SelectionRequest SelectionOptions
options) = SelectionOptions -> [Utxo]
selectionPreselected SelectionOptions
options

-- | Eligible candidate snapshots in caller order.
available :: SelectionRequest -> [Utxo]
available :: SelectionRequest -> [Utxo]
available (SelectionRequest SelectionOptions
options) = SelectionOptions -> [Utxo]
selectionAvailable SelectionOptions
options

-- | Authoritative funding requirement; output hints do not change it.
target :: SelectionRequest -> Value
target :: SelectionRequest -> Value
target (SelectionRequest SelectionOptions
options) = SelectionOptions -> Value
selectionTarget SelectionOptions
options

-- | Optional output-shape hints, retaining absence versus an empty hint list.
outputHints :: SelectionRequest -> Maybe [Output]
outputHints :: SelectionRequest -> Maybe [Output]
outputHints (SelectionRequest SelectionOptions
options) = SelectionOptions -> Maybe [Output]
selectionOutputHints SelectionOptions
options

-- | Destination required for each change output.
changeAddress :: SelectionRequest -> Address
changeAddress :: SelectionRequest -> Address
changeAddress (SelectionRequest SelectionOptions
options) = SelectionOptions -> Address
selectionChangeAddress SelectionOptions
options

-- | Protocol snapshot supplied with the request.
parameters :: SelectionRequest -> Parameters
parameters :: SelectionRequest -> Parameters
parameters (SelectionRequest SelectionOptions
options) = SelectionOptions -> Parameters
selectionParameters SelectionOptions
options

-- | Check unique references, unaltered eligible snapshots, mandatory inclusion,
-- exact remaining accounting and componentwise selected = target + change.
-- Change destinations must match. Ordering does not affect these laws. This
-- pure check does not assess minimum Ada; 'select' performs that additional check.
validateSelection :: SelectionRequest -> Selection -> Either Error ()
validateSelection :: SelectionRequest -> Selection -> Either Error ()
validateSelection SelectionRequest
request Selection
result = do
  Map Input Utxo
chosen <- Error -> [Utxo] -> Either Error (Map Input Utxo)
indexUtxos (Text -> Error
InvalidSelection Text
"Repeated selected reference") (Selection -> [Utxo]
selected Selection
result)
  Map Input Utxo
rest <- Error -> [Utxo] -> Either Error (Map Input Utxo)
indexUtxos (Text -> Error
InvalidSelection Text
"Repeated remaining reference") (Selection -> [Utxo]
remaining Selection
result)
  let mandatory :: Map Input Utxo
mandatory = [(Input, Utxo)] -> Map Input Utxo
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(Utxo -> Input
Utxo.input Utxo
value, Utxo
value) | Utxo
value <- SelectionRequest -> [Utxo]
preselected SelectionRequest
request]
      candidates :: Map Input Utxo
candidates = [(Input, Utxo)] -> Map Input Utxo
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(Utxo -> Input
Utxo.input Utxo
value, Utxo
value) | Utxo
value <- SelectionRequest -> [Utxo]
available SelectionRequest
request]
      eligible :: Map Input Utxo
eligible = Map Input Utxo -> Map Input Utxo -> Map Input Utxo
forall k a. Ord k => Map k a -> Map k a -> Map k a
Map.union Map Input Utxo
mandatory Map Input Utxo
candidates
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((Utxo -> Utxo -> Bool) -> Map Input Utxo -> Map Input Utxo -> Bool
forall k a b.
Ord k =>
(a -> b -> Bool) -> Map k a -> Map k b -> Bool
Map.isSubmapOfBy Utxo -> Utxo -> Bool
forall a. Eq a => a -> a -> Bool
(==) Map Input Utxo
chosen Map Input Utxo
eligible) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelection Text
"Selection contains an ineligible or changed snapshot"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((Utxo -> Utxo -> Bool) -> Map Input Utxo -> Map Input Utxo -> Bool
forall k a b.
Ord k =>
(a -> b -> Bool) -> Map k a -> Map k b -> Bool
Map.isSubmapOfBy Utxo -> Utxo -> Bool
forall a. Eq a => a -> a -> Bool
(==) Map Input Utxo
mandatory Map Input Utxo
chosen) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelection Text
"Preselected input was dropped or changed"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Map Input Utxo
rest Map Input Utxo -> Map Input Utxo -> Bool
forall a. Eq a => a -> a -> Bool
== Map Input Utxo -> Map Input Utxo -> Map Input Utxo
forall k a b. Ord k => Map k a -> Map k b -> Map k a
Map.difference Map Input Utxo
candidates Map Input Utxo
chosen) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelection Text
"Remaining candidates do not account exactly for the available set"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((Output -> Bool) -> [Output] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all ((Address -> Address -> Bool
forall a. Eq a => a -> a -> Bool
== SelectionRequest -> Address
changeAddress SelectionRequest
request) (Address -> Bool) -> (Output -> Address) -> Output -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Output -> Address
Output.address) (Selection -> [Output]
change Selection
result)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelection Text
"Change destination differs from request"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([Utxo] -> Value
sumUtxos (Selection -> [Utxo]
selected Selection
result) Value -> Value -> Bool
forall a. Eq a => a -> a -> Bool
== SelectionRequest -> Value
target SelectionRequest
request Value -> Value -> Value
forall a. Semigroup a => a -> a -> a
<> (Output -> Value) -> [Output] -> Value
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap Output -> Value
Output.value (Selection -> [Output]
change Selection
result)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelection Text
"Selected value differs from target plus change"))

indexUtxos :: Error -> [Utxo] -> Either Error (Map Input Utxo)
indexUtxos :: Error -> [Utxo] -> Either Error (Map Input Utxo)
indexUtxos Error
failure [Utxo]
values = do
  let result :: Map Input Utxo
result = [(Input, Utxo)] -> Map Input Utxo
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(Utxo -> Input
Utxo.input Utxo
value, Utxo
value) | Utxo
value <- [Utxo]
values]
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Map Input Utxo -> Int
forall k a. Map k a -> Int
Map.size Map Input Utxo
result Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [Utxo] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Utxo]
values) (Error -> Either Error ()
forall a b. a -> Either a b
Left Error
failure)
  Map Input Utxo -> Either Error (Map Input Utxo)
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Map Input Utxo
result

sumUtxos :: [Utxo] -> Value
sumUtxos :: [Utxo] -> Value
sumUtxos = (Utxo -> Value) -> [Utxo] -> Value
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Output -> Value
Output.value (Output -> Value) -> (Utxo -> Output) -> Utxo -> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Utxo -> Output
Utxo.output)

-- | Invoke an application selector once, validate its complete result and check
-- minimum Ada for every change output. No fees, additional inputs, witnesses or
-- output amounts are changed implicitly. Expected failures retain their error;
-- callback exceptions and asynchronous cancellation propagate normally.
select :: Selector -> SelectionRequest -> IO (Either Error Selection)
select :: Selector -> SelectionRequest -> IO (Either Error Selection)
select Selector
selector SelectionRequest
request = do
  Either Error Selection
result <- Selector -> SelectionRequest -> IO (Either Error Selection)
selectCoins Selector
selector SelectionRequest
request
  case Either Error Selection
result Either Error Selection
-> (Selection -> Either Error Selection) -> Either Error Selection
forall a b.
Either Error a -> (a -> Either Error b) -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (\Selection
selection -> SelectionRequest -> Selection -> Either Error ()
validateSelection SelectionRequest
request Selection
selection Either Error () -> Either Error Selection -> Either Error Selection
forall a b. Either Error a -> Either Error b -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Selection -> Either Error Selection
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Selection
selection) of
    Left Error
failure -> Either Error Selection -> IO (Either Error Selection)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Selection
forall a b. a -> Either a b
Left Error
failure)
    Right Selection
selection -> do
      Either Error ()
checked <- SelectionRequest -> [Output] -> IO (Either Error ())
checkChange SelectionRequest
request (Selection -> [Output]
change Selection
selection)
      Either Error Selection -> IO (Either Error Selection)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Selection
selection Selection -> Either Error () -> Either Error Selection
forall a b. a -> Either Error b -> Either Error a
forall (f :: * -> *) a b. Functor f => a -> f b -> f a
<$ Either Error ()
checked)

checkChange :: SelectionRequest -> [Output] -> IO (Either Error ())
checkChange :: SelectionRequest -> [Output] -> IO (Either Error ())
checkChange SelectionRequest
request [Output]
outputs = case Parameters -> Maybe Word64
Parameters.parameterAdaPerUtxoByte (SelectionRequest -> Parameters
parameters SelectionRequest
request) of
  Maybe Word64
Nothing -> Either Error () -> IO (Either Error ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelectionRequest Text
"Ada per UTxO byte is required"))
  Just Word64
cost -> Word64 -> [Output] -> IO (Either Error ())
go Word64
cost [Output]
outputs
  where
    go :: Word64 -> [Output] -> IO (Either Error ())
go Word64
_ [] = Either Error () -> IO (Either Error ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either Error ()
forall a b. b -> Either a b
Right ())
    go Word64
cost (Output
output : [Output]
rest) = do
      Either Error Word64
required <- Word64 -> Output -> IO (Either Error Word64)
minimumAda Word64
cost Output
output
      case Either Error Word64
required of
        Left Error
failure -> Either Error () -> IO (Either Error ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ()
forall a b. a -> Either a b
Left Error
failure)
        Right Word64
amount
          | AssetId -> Value -> Integer
Value.quantity AssetId
Ada (Output -> Value
Output.value Output
output) Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
amount -> Either Error () -> IO (Either Error ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidSelection Text
"Change output is below minimum Ada"))
          | Bool
otherwise -> Word64 -> [Output] -> IO (Either Error ())
go Word64
cost [Output]
rest

minimumAda :: Word64 -> Output -> IO (Either Error Word64)
minimumAda :: Word64 -> Output -> IO (Either Error Word64)
minimumAda Word64
cost Output
output = ByteString
-> (CStringLen -> IO (Either Error Word64))
-> IO (Either Error Word64)
forall a. ByteString -> (CStringLen -> IO a) -> IO a
B.useAsCStringLen (Output -> ByteString
Output.encodeCbor Output
output) ((CStringLen -> IO (Either Error Word64))
 -> IO (Either Error Word64))
-> (CStringLen -> IO (Either Error Word64))
-> IO (Either Error Word64)
forall a b. (a -> b) -> a -> b
$ \(Ptr CChar
bytes, Int
size) -> (Ptr Word64 -> IO (Either Error Word64))
-> IO (Either Error Word64)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr Word64 -> IO (Either Error Word64))
 -> IO (Either Error Word64))
-> (Ptr Word64 -> IO (Either Error Word64))
-> IO (Either Error Word64)
forall a b. (a -> b) -> a -> b
$ \Ptr Word64
result -> do
  CUInt
code <- Ptr Word8 -> CSize -> Word64 -> Ptr Word64 -> IO CUInt
Native.cMinimumAda (Ptr CChar -> Ptr Word8
forall a b. Ptr a -> Ptr b
castPtr Ptr CChar
bytes) (Int -> CSize
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
size) Word64
cost Ptr Word64
result
  Either Error ()
status <- Text -> CUInt -> IO (Either Error ())
Runtime.checkStatus Text
"coinSelection.minimumAda" CUInt
code
  case Either Error ()
status of
    Left Error
failure -> Either Error Word64 -> IO (Either Error Word64)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error Word64
forall a b. a -> Either a b
Left Error
failure)
    Right () -> Word64 -> Either Error Word64
forall a b. b -> Either a b
Right (Word64 -> Either Error Word64)
-> IO Word64 -> IO (Either Error Word64)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Ptr Word64 -> IO Word64
forall a. Storable a => Ptr a -> IO a
peek Ptr Word64
result

encodeList :: (a -> ByteString) -> [a] -> E.Encoding
encodeList :: forall a. (a -> ByteString) -> [a] -> Encoding
encodeList a -> ByteString
encode [a]
values = Word -> Encoding
E.encodeListLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([a] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [a]
values)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (a -> Encoding) -> [a] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (ByteString -> Encoding
Cbor.raw (ByteString -> Encoding) -> (a -> ByteString) -> a -> Encoding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> ByteString
encode) [a]
values

-- Internal requests use signed coin plus signed native-asset quantities.
-- Ledger Value CBOR cannot represent negative coin, despite native value_t
-- supporting signed arithmetic for implicit sources during balancing.
encodeValue :: Value -> E.Encoding
encodeValue :: Value -> Encoding
encodeValue Value
value = Word -> Encoding
E.encodeListLen Word
2 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Integer -> Encoding
E.encodeInteger (AssetId -> Value -> Integer
Value.quantity AssetId
Ada Value
value) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Value -> Encoding
V.encodeAssets Value
value

decodeValue :: D.Decoder s Value
decodeValue :: forall s. Decoder s Value
decodeValue = Int -> Decoder s Value -> Decoder s Value
forall s a. Int -> Decoder s a -> Decoder s a
Cbor.array Int
2 ((Value -> Value -> Value
forall a. Semigroup a => a -> a -> a
(<>) (Value -> Value -> Value)
-> (Integer -> Value) -> Integer -> Value -> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Integer -> Value
Value.lovelace (Integer -> Value -> Value)
-> Decoder s Integer -> Decoder s (Value -> Value)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Integer
forall s. Decoder s Integer
D.decodeInteger) Decoder s (Value -> Value) -> Decoder s Value -> Decoder s Value
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder s Value
forall s. Decoder s Value
V.decodeAssets)

encodeRequest :: SelectionRequest -> ByteString
encodeRequest :: SelectionRequest -> ByteString
encodeRequest SelectionRequest
request = Encoding -> ByteString
Cbor.encode (Word -> Encoding
E.encodeListLen Word
6 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Utxo -> ByteString) -> [Utxo] -> Encoding
forall a. (a -> ByteString) -> [a] -> Encoding
encodeList Utxo -> ByteString
Utxo.encodeCbor (SelectionRequest -> [Utxo]
preselected SelectionRequest
request) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Utxo -> ByteString) -> [Utxo] -> Encoding
forall a. (a -> ByteString) -> [a] -> Encoding
encodeList Utxo -> ByteString
Utxo.encodeCbor (SelectionRequest -> [Utxo]
available SelectionRequest
request) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Value -> Encoding
encodeValue (SelectionRequest -> Value
target SelectionRequest
request) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Encoding -> ([Output] -> Encoding) -> Maybe [Output] -> Encoding
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Encoding
E.encodeNull ((Output -> ByteString) -> [Output] -> Encoding
forall a. (a -> ByteString) -> [a] -> Encoding
encodeList Output -> ByteString
Output.encodeCbor) (SelectionRequest -> Maybe [Output]
outputHints SelectionRequest
request) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
E.encodeBytes (Address -> ByteString
Address.toBytes (SelectionRequest -> Address
changeAddress SelectionRequest
request)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
Cbor.raw (Parameters -> ByteString
Snapshot.encodeSnapshot (SelectionRequest -> Parameters
parameters SelectionRequest
request)))

decodeRequest :: ByteString -> Either Error SelectionRequest
decodeRequest :: ByteString -> Either Error SelectionRequest
decodeRequest ByteString
bytes = (forall s. Decoder s SelectionOptions)
-> ByteString -> Either Error SelectionOptions
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decode Decoder s SelectionOptions
forall s. Decoder s SelectionOptions
parser ByteString
bytes Either Error SelectionOptions
-> (SelectionOptions -> Either Error SelectionRequest)
-> Either Error SelectionRequest
forall a b.
Either Error a -> (a -> Either Error b) -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= SelectionOptions -> Either Error SelectionRequest
mkSelectionRequest
  where
    parser :: Decoder s SelectionOptions
parser =
      Int -> Decoder s SelectionOptions -> Decoder s SelectionOptions
forall s a. Int -> Decoder s a -> Decoder s a
Cbor.array
        Int
6
        ( [Utxo]
-> [Utxo]
-> Value
-> Maybe [Output]
-> Address
-> Parameters
-> SelectionOptions
SelectionOptions
            ([Utxo]
 -> [Utxo]
 -> Value
 -> Maybe [Output]
 -> Address
 -> Parameters
 -> SelectionOptions)
-> Decoder s [Utxo]
-> Decoder
     s
     ([Utxo]
      -> Value
      -> Maybe [Output]
      -> Address
      -> Parameters
      -> SelectionOptions)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Utxo -> Decoder s [Utxo]
forall s a. Decoder s a -> Decoder s [a]
Cbor.list (ByteString -> (ByteString -> Either Error Utxo) -> Decoder s Utxo
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString
bytes ByteString -> Either Error Utxo
Utxo.decodeCbor)
            Decoder
  s
  ([Utxo]
   -> Value
   -> Maybe [Output]
   -> Address
   -> Parameters
   -> SelectionOptions)
-> Decoder s [Utxo]
-> Decoder
     s
     (Value
      -> Maybe [Output] -> Address -> Parameters -> SelectionOptions)
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder s Utxo -> Decoder s [Utxo]
forall s a. Decoder s a -> Decoder s [a]
Cbor.list (ByteString -> (ByteString -> Either Error Utxo) -> Decoder s Utxo
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString
bytes ByteString -> Either Error Utxo
Utxo.decodeCbor)
            Decoder
  s
  (Value
   -> Maybe [Output] -> Address -> Parameters -> SelectionOptions)
-> Decoder s Value
-> Decoder
     s (Maybe [Output] -> Address -> Parameters -> SelectionOptions)
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder s Value
forall s. Decoder s Value
decodeValue
            Decoder
  s (Maybe [Output] -> Address -> Parameters -> SelectionOptions)
-> Decoder s (Maybe [Output])
-> Decoder s (Address -> Parameters -> SelectionOptions)
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder s [Output] -> Decoder s (Maybe [Output])
forall s a. Decoder s a -> Decoder s (Maybe a)
Cbor.optional (Decoder s Output -> Decoder s [Output]
forall s a. Decoder s a -> Decoder s [a]
Cbor.list (EncodedOutput -> Output
Output.toOutput (EncodedOutput -> Output)
-> Decoder s EncodedOutput -> Decoder s Output
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString
-> (ByteString -> Either Error EncodedOutput)
-> Decoder s EncodedOutput
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString
bytes ByteString -> Either Error EncodedOutput
Output.decodeCbor))
            Decoder s (Address -> Parameters -> SelectionOptions)
-> Decoder s Address -> Decoder s (Parameters -> SelectionOptions)
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> (Decoder s ByteString
forall s. Decoder s ByteString
D.decodeBytes Decoder s ByteString
-> (ByteString -> Decoder s Address) -> Decoder s Address
forall a b. Decoder s a -> (a -> Decoder s b) -> Decoder s b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= (Error -> Decoder s Address)
-> (Address -> Decoder s Address)
-> Either Error Address
-> Decoder s Address
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (String -> Decoder s Address
forall a. String -> Decoder s a
forall (m :: * -> *) a. MonadFail m => String -> m a
fail (String -> Decoder s Address)
-> (Error -> String) -> Error -> Decoder s Address
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Error -> String
forall a. Show a => a -> String
show) Address -> Decoder s Address
forall a. a -> Decoder s a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error Address -> Decoder s Address)
-> (ByteString -> Either Error Address)
-> ByteString
-> Decoder s Address
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Either Error Address
Address.fromBytes)
            Decoder s (Parameters -> SelectionOptions)
-> Decoder s Parameters -> Decoder s SelectionOptions
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> ByteString
-> (ByteString -> Either Error Parameters) -> Decoder s Parameters
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString
bytes ByteString -> Either Error Parameters
Snapshot.decodeSnapshot
        )

encodeSelection :: Selection -> ByteString
encodeSelection :: Selection -> ByteString
encodeSelection Selection
result = Encoding -> ByteString
Cbor.encode (Word -> Encoding
E.encodeListLen Word
3 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Utxo -> ByteString) -> [Utxo] -> Encoding
forall a. (a -> ByteString) -> [a] -> Encoding
encodeList Utxo -> ByteString
Utxo.encodeCbor (Selection -> [Utxo]
selected Selection
result) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Utxo -> ByteString) -> [Utxo] -> Encoding
forall a. (a -> ByteString) -> [a] -> Encoding
encodeList Utxo -> ByteString
Utxo.encodeCbor (Selection -> [Utxo]
remaining Selection
result) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Output -> ByteString) -> [Output] -> Encoding
forall a. (a -> ByteString) -> [a] -> Encoding
encodeList Output -> ByteString
Output.encodeCbor (Selection -> [Output]
change Selection
result))

decodeSelection :: ByteString -> Either Error Selection
decodeSelection :: ByteString -> Either Error Selection
decodeSelection ByteString
bytes = (forall s. Decoder s Selection)
-> ByteString -> Either Error Selection
forall a. (forall s. Decoder s a) -> ByteString -> Either Error a
Cbor.decode (Int -> Decoder s Selection -> Decoder s Selection
forall s a. Int -> Decoder s a -> Decoder s a
Cbor.array Int
3 ([Utxo] -> [Utxo] -> [Output] -> Selection
Selection ([Utxo] -> [Utxo] -> [Output] -> Selection)
-> Decoder s [Utxo] -> Decoder s ([Utxo] -> [Output] -> Selection)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Utxo -> Decoder s [Utxo]
forall s a. Decoder s a -> Decoder s [a]
Cbor.list (ByteString -> (ByteString -> Either Error Utxo) -> Decoder s Utxo
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString
bytes ByteString -> Either Error Utxo
Utxo.decodeCbor) Decoder s ([Utxo] -> [Output] -> Selection)
-> Decoder s [Utxo] -> Decoder s ([Output] -> Selection)
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder s Utxo -> Decoder s [Utxo]
forall s a. Decoder s a -> Decoder s [a]
Cbor.list (ByteString -> (ByteString -> Either Error Utxo) -> Decoder s Utxo
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString
bytes ByteString -> Either Error Utxo
Utxo.decodeCbor) Decoder s ([Output] -> Selection)
-> Decoder s [Output] -> Decoder s Selection
forall a b. Decoder s (a -> b) -> Decoder s a -> Decoder s b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> Decoder s Output -> Decoder s [Output]
forall s a. Decoder s a -> Decoder s [a]
Cbor.list (EncodedOutput -> Output
Output.toOutput (EncodedOutput -> Output)
-> Decoder s EncodedOutput -> Decoder s Output
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString
-> (ByteString -> Either Error EncodedOutput)
-> Decoder s EncodedOutput
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
Cbor.nested ByteString
bytes ByteString -> Either Error EncodedOutput
Output.decodeCbor))) ByteString
bytes