{-# LANGUAGE LambdaCase #-}
-- 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 #-}
{-# OPTIONS_HADDOCK hide #-}

-- | Scoped standalone balancing, including stable spending-redeemer identity.
module Cometa.Internal.TransactionBalancing (balance, balanceWithRedeemers) where

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

import qualified Codec.CBOR.Decoding as D
import qualified Codec.CBOR.Encoding as E
import qualified Codec.CBOR.Term as Term
import qualified Cometa.Address as Address
import Cometa.AssetId (AssetId (Ada))
import Cometa.Error (Error (..))
import qualified Cometa.Evaluation as Eval
import qualified Cometa.Internal.Balance as Balance
import qualified Cometa.Internal.BalancingScripts as Scripts
import qualified Cometa.Internal.BatchValidation as Batch
import qualified Cometa.Internal.Building as Building
import qualified Cometa.Internal.CoinSelection.Native as Selection
import qualified Cometa.Internal.Evaluation.Native as NativeEvaluation
import qualified Cometa.Internal.EvaluationNative as Evaluation
import qualified Cometa.Internal.FFI.TransactionBuilder as FFI
import qualified Cometa.Internal.ParameterSnapshot as Parameters
import qualified Cometa.Internal.Runtime as Runtime
import qualified Cometa.Internal.TransactionBuilder as Builder
import qualified Cometa.Internal.TransactionCbor as C
import qualified Cometa.PlutusData as Data
import qualified Cometa.Protocol.CostModels as Models
import qualified Cometa.Protocol.ExUnitPrices as Prices
import qualified Cometa.Protocol.ExUnits as Ex
import qualified Cometa.Protocol.Parameters as P
import qualified Cometa.Protocol.Rational as Rational
import qualified Cometa.Protocol.Version as Version
import qualified Cometa.SlotConfig as Slot
import qualified Cometa.SubTransaction as Sub
import qualified Cometa.SubTransaction.Body as SubBody
import Cometa.Transaction (Transaction)
import qualified Cometa.Transaction as Tx
import qualified Cometa.Transaction.Body as Body
import qualified Cometa.Transaction.Datum as Datum
import qualified Cometa.Transaction.Fields as Fields
import qualified Cometa.Transaction.Input as Input
import qualified Cometa.Transaction.Output as Output
import Cometa.Transaction.Plan (DeferredRedeemer)
import qualified Cometa.Transaction.Redeemer as Redeemer
import Cometa.Transaction.Utxo (Utxo)
import qualified Cometa.Transaction.Utxo as Utxo
import qualified Cometa.Transaction.Witnesses as Witnesses
import qualified Cometa.Value as Value
import Control.Monad (unless)
import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Int (Int64)
import Data.List (sort, sortOn)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe, isJust)
import qualified Data.Set as Set
import Data.Text (Text)
import Foreign.Ptr (nullPtr)

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

-- | Balance an existing transaction with the same configuration used by
-- 'Cometa.Transaction.Builder.build'. Supply resolved spending, reference and
-- collateral inputs for every level; wallet candidates in the configuration may
-- also provide these snapshots. Every existing outer output is treated as a
-- payment, including previous change. The existing fee and configured minimum
-- fee are lower bounds. The imported network id is retained.
--
-- The result drops outer key/bootstrap signatures and retains signed nested
-- intent bodies and witnesses. Native serialization may normalize enclosing CBOR
-- array framing; it does not promise byte-for-byte transaction interchange.
-- Spending redeemers follow their original inputs when selection changes
-- input order. Script budgets, commitments, collateral and fees are recalculated.
-- Missing/conflicting inputs or invalid redeemer positions fail explicitly.
-- Callback exceptions and cancellation release scoped resources before propagating.
-- No provider queries, signing or submission occur; ledger acceptance is separate.
balance :: Builder.Config -> [Utxo] -> Transaction -> IO (Either Error Transaction)
balance :: Config -> [Utxo] -> Transaction -> IO (Either Error Transaction)
balance Config
config [Utxo]
resolved = Config
-> [Utxo]
-> Map RedeemerId DeferredRedeemer
-> Transaction
-> IO (Either Error Transaction)
balanceWithRedeemers Config
config [Utxo]
resolved Map RedeemerId DeferredRedeemer
forall k a. Map k a
Map.empty

-- | Like 'balance', replacing selected outer redeemer payloads on every balancing
-- iteration. Keys identify purpose/index pairs in the ORIGINAL transaction; every
-- key must already have a witness redeemer. Spending associations follow their
-- original inputs even when their indices change. Other purposes retain their
-- existing body order. Callbacks receive the current draft and canonically ordered
-- resolved outer spending inputs. They may run repeatedly and must be deterministic.
-- Use "Cometa.Transaction.Deferred" to compose pure queries. Nested redeemers are
-- signed intent content and cannot be replaced by this operation.
balanceWithRedeemers :: Builder.Config -> [Utxo] -> Map Eval.RedeemerId DeferredRedeemer -> Transaction -> IO (Either Error Transaction)
balanceWithRedeemers :: Config
-> [Utxo]
-> Map RedeemerId DeferredRedeemer
-> Transaction
-> IO (Either Error Transaction)
balanceWithRedeemers Config
config [Utxo]
resolved Map RedeemerId DeferredRedeemer
callbacks Transaction
original = ExceptT Error IO Transaction -> IO (Either Error Transaction)
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (ExceptT Error IO Transaction -> IO (Either Error Transaction))
-> ExceptT Error IO Transaction -> IO (Either Error Transaction)
forall a b. (a -> b) -> a -> b
$ do
  [Utxo]
snapshots <- Either Error [Utxo] -> ExceptT Error IO [Utxo]
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (Config
-> [Utxo]
-> Map RedeemerId DeferredRedeemer
-> Transaction
-> Either Error [Utxo]
validate Config
config [Utxo]
resolved Map RedeemerId DeferredRedeemer
callbacks Transaction
original)
  IO (Either Error ()) -> ExceptT Error IO ()
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (Config -> [Utxo] -> Transaction -> IO (Either Error ())
preflight Config
config [Utxo]
snapshots Transaction
original)
  Transaction
prepared <- Either Error Transaction -> ExceptT Error IO Transaction
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (Transaction -> Either Error Transaction
reserveScriptHash Transaction
original)
  Transaction
balancedDraft <- IO (Either Error Transaction) -> ExceptT Error IO Transaction
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (Config
-> [Utxo]
-> Map RedeemerId DeferredRedeemer
-> Transaction
-> IO (Either Error Transaction)
runBalance Config
config [Utxo]
snapshots Map RedeemerId DeferredRedeemer
callbacks Transaction
prepared)
  CostModels
models <- IO (Either Error CostModels) -> ExceptT Error IO CostModels
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (Parameters -> [Utxo] -> Transaction -> IO (Either Error CostModels)
Scripts.usedCostModels (Config -> Parameters
Builder.parameters Config
config) [Utxo]
snapshots Transaction
balancedDraft)
  Maybe Hash32
commitment <- IO (Either Error (Maybe Hash32)) -> ExceptT Error IO (Maybe Hash32)
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (CostModels -> EncodedWitnesses -> IO (Either Error (Maybe Hash32))
Building.scriptDataHash CostModels
models (Transaction -> EncodedWitnesses
Tx.witnesses Transaction
balancedDraft))
  Transaction
result <- Either Error Transaction -> ExceptT Error IO Transaction
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (Maybe Hash32 -> Transaction -> Either Error Transaction
setScriptHash Maybe Hash32
commitment Transaction
balancedDraft)
  Either Error () -> ExceptT Error IO ()
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (Config -> Transaction -> Either Error ()
validateResult Config
config Transaction
result)
  let evaluator :: Evaluator
evaluator = Config -> Evaluator
evaluatorFor Config
config
  IO (Either Error ()) -> ExceptT Error IO ()
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (Evaluator -> [Utxo] -> Transaction -> IO (Either Error ())
Batch.validateSubBudgets Evaluator
evaluator [Utxo]
snapshots Transaction
result)
  Bool
balanced <- IO (Either Error Bool) -> ExceptT Error IO Bool
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (Parameters -> [Utxo] -> Transaction -> IO (Either Error Bool)
Balance.isBalanced (Config -> Parameters
Builder.parameters Config
config) [Utxo]
snapshots Transaction
result)
  Bool -> ExceptT Error IO () -> ExceptT Error IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless Bool
balanced (Either Error () -> ExceptT Error IO ()
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"balancing.conservation")))
  Transaction -> ExceptT Error IO Transaction
forall a. a -> ExceptT Error IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Transaction
result

-- | Resolve identities once; duplicates within a supplied snapshot are rejected.
validate :: Builder.Config -> [Utxo] -> Map Eval.RedeemerId DeferredRedeemer -> Transaction -> Either Error [Utxo]
validate :: Config
-> [Utxo]
-> Map RedeemerId DeferredRedeemer
-> Transaction
-> Either Error [Utxo]
validate Config
config [Utxo]
resolved Map RedeemerId DeferredRedeemer
callbacks Transaction
transaction = do
  Parameters -> Either Error ()
Parameters.validateNative (Config -> Parameters
Builder.parameters Config
config)
  ([Utxo] -> Either Error ()) -> [[Utxo]] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ [Utxo] -> Either Error ()
unique [[Utxo]
resolved, Config -> [Utxo]
Builder.availableUtxos Config
config, Config -> [Utxo]
Builder.collateralUtxos Config
config]
  let allInputs :: [Utxo]
allInputs = [Utxo]
resolved [Utxo] -> [Utxo] -> [Utxo]
forall a. Semigroup a => a -> a -> a
<> Config -> [Utxo]
Builder.availableUtxos Config
config [Utxo] -> [Utxo] -> [Utxo]
forall a. Semigroup a => a -> a -> a
<> Config -> [Utxo]
Builder.collateralUtxos Config
config
      grouped :: Map Input [Utxo]
grouped = ([Utxo] -> [Utxo] -> [Utxo])
-> [(Input, [Utxo])] -> Map Input [Utxo]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith [Utxo] -> [Utxo] -> [Utxo]
forall a. Semigroup a => a -> a -> a
(<>) [(Utxo -> Input
Utxo.input Utxo
u, [Utxo
u]) | Utxo
u <- [Utxo]
allInputs]
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (([Utxo] -> Bool) -> [[Utxo]] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all [Utxo] -> Bool
forall {a}. Eq a => [a] -> Bool
agrees (Map Input [Utxo] -> [[Utxo]]
forall k a. Map k a -> [a]
Map.elems Map Input [Utxo]
grouped)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Conflicting resolved input snapshots"))
  let snapshots :: Map Input Utxo
snapshots = [(Input, Utxo)] -> Map Input Utxo
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(Utxo -> Input
Utxo.input Utxo
u, Utxo
u) | Utxo
u <- [Utxo]
allInputs]
      body :: Body
body = EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
transaction)
      fields :: Fields
fields = Body -> Fields
Body.bodyFields Body
body
      subFields :: [Fields]
subFields = [Fields]
-> ([SubTransaction] -> [Fields])
-> Maybe [SubTransaction]
-> [Fields]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ((SubTransaction -> Fields) -> [SubTransaction] -> [Fields]
forall a b. (a -> b) -> [a] -> [b]
map (Body -> Fields
SubBody.fields (Body -> Fields)
-> (SubTransaction -> Body) -> SubTransaction -> Fields
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedBody -> Body
SubBody.toBody (EncodedBody -> Body)
-> (SubTransaction -> EncodedBody) -> SubTransaction -> Body
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> EncodedBody
Sub.body)) (Body -> Maybe [SubTransaction]
Body.bodySubTransactions Body
body)
      required :: [Input]
required = (Fields -> [Input]) -> [Fields] -> [Input]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Fields -> [Input]
references (Fields
fields Fields -> [Fields] -> [Fields]
forall a. a -> [a] -> [a]
: [Fields]
subFields) [Input] -> [Input] -> [Input]
forall a. Semigroup a => a -> a -> a
<> [Input] -> Maybe [Input] -> [Input]
forall a. a -> Maybe a -> a
fromMaybe [] (Body -> Maybe [Input]
Body.bodyCollateral Body
body)
      redeemers :: [Redeemer]
redeemers = Transaction -> [Redeemer]
outerRedeemers Transaction
transaction
      identifiers :: [RedeemerId]
identifiers = (Redeemer -> RedeemerId) -> [Redeemer] -> [RedeemerId]
forall a b. (a -> b) -> [a] -> [b]
map Redeemer -> RedeemerId
identifier [Redeemer]
redeemers
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((Input -> Bool) -> [Input] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Input -> Map Input Utxo -> Bool
forall k a. Ord k => k -> Map k a -> Bool
`Map.member` Map Input Utxo
snapshots) [Input]
required) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"A transaction input has no resolved UTxO"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((Fields -> Bool) -> [Fields] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Fields -> Bool
uniqueReferences (Fields
fields Fields -> [Fields] -> [Fields]
forall a. a -> [a] -> [a]
: [Fields]
subFields)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Duplicate transaction input reference"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Set RedeemerId -> Int
forall a. Set a -> Int
Set.size ([RedeemerId] -> Set RedeemerId
forall a. Ord a => [a] -> Set a
Set.fromList [RedeemerId]
identifiers) Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [RedeemerId] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [RedeemerId]
identifiers) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Duplicate redeemer purpose and index"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((RedeemerId -> Bool) -> [RedeemerId] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (RedeemerId -> [RedeemerId] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [RedeemerId]
identifiers) (Map RedeemerId DeferredRedeemer -> [RedeemerId]
forall k a. Map k a -> [k]
Map.keys Map RedeemerId DeferredRedeemer
callbacks)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Deferred redeemer has no existing witness"))
  (Redeemer -> Either Error (Maybe Input))
-> [Redeemer] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Fields -> Redeemer -> Either Error (Maybe Input)
spendingInput Fields
fields) [Redeemer]
redeemers
  (Redeemer -> Either Error ()) -> [Redeemer] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Transaction -> Redeemer -> Either Error ()
validatePurpose Transaction
transaction) [Redeemer]
redeemers
  (Word64 -> Either Error Word64) -> [Word64] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (SlotConfig -> Word64 -> Either Error Word64
Slot.slotToTime (Config -> SlotConfig
Builder.slotConfig Config
config)) ([Word64] -> (Word64 -> [Word64]) -> Maybe Word64 -> [Word64]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Word64 -> [Word64]
forall a. a -> [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Fields -> Maybe Word64
Fields.fieldInvalidBefore Fields
fields) [Word64] -> [Word64] -> [Word64]
forall a. Semigroup a => a -> a -> a
<> [Word64] -> (Word64 -> [Word64]) -> Maybe Word64 -> [Word64]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] Word64 -> [Word64]
forall a. a -> [a]
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Fields -> Maybe Word64
Fields.fieldInvalidAfter Fields
fields))
  [Utxo] -> Either Error [Utxo]
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Map Input Utxo -> [Utxo]
forall k a. Map k a -> [a]
Map.elems Map Input Utxo
snapshots)
  where
    unique :: [Utxo] -> Either Error ()
unique [Utxo]
values = Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Set Input -> Int
forall a. Set a -> Int
Set.size ([Input] -> Set Input
forall a. Ord a => [a] -> Set a
Set.fromList ((Utxo -> Input) -> [Utxo] -> [Input]
forall a b. (a -> b) -> [a] -> [b]
map Utxo -> Input
Utxo.input [Utxo]
values)) 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 (Text -> Error
InvalidBuildingRequest Text
"Duplicate resolved input snapshot"))
    agrees :: [a] -> Bool
agrees [] = Bool
True
    agrees (a
x : [a]
xs) = (a -> Bool) -> [a] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
x) [a]
xs
    uniqueReferences :: Fields -> Bool
uniqueReferences Fields
fields = let refs :: [Input]
refs = Fields -> [Input]
Fields.fieldInputs Fields
fields in Set Input -> Int
forall a. Set a -> Int
Set.size ([Input] -> Set Input
forall a. Ord a => [a] -> Set a
Set.fromList [Input]
refs) Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
== [Input] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Input]
refs

-- | Spending indices refer to sorted original input identities, not list storage.
spendingInput :: Fields.Fields -> Redeemer.Redeemer -> Either Error (Maybe Input.Input)
spendingInput :: Fields -> Redeemer -> Either Error (Maybe Input)
spendingInput Fields
fields Redeemer
redeemer
  | Redeemer -> Purpose
Redeemer.purpose Redeemer
redeemer Purpose -> Purpose -> Bool
forall a. Eq a => a -> a -> Bool
/= Purpose
Redeemer.Spending = Maybe Input -> Either Error (Maybe Input)
forall a b. b -> Either a b
Right Maybe Input
forall a. Maybe a
Nothing
  | Bool
otherwise = case Word32 -> [Input] -> [Input]
forall {a} {a}. Integral a => a -> [a] -> [a]
dropInteger (Redeemer -> Word32
Redeemer.index Redeemer
redeemer) ([Input] -> [Input]
forall a. Ord a => [a] -> [a]
sort (Fields -> [Input]
Fields.fieldInputs Fields
fields)) of
      Input
value : [Input]
_ -> Maybe Input -> Either Error (Maybe Input)
forall a b. b -> Either a b
Right (Input -> Maybe Input
forall a. a -> Maybe a
Just Input
value)
      [] -> Error -> Either Error (Maybe Input)
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Spending redeemer index has no original input")
  where
    dropInteger :: a -> [a] -> [a]
dropInteger a
index [a]
values
      | a -> Integer
forall a. Integral a => a -> Integer
toInteger a
index Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Int -> Integer
forall a. Integral a => a -> Integer
toInteger ([a] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [a]
values) = []
      | Bool
otherwise = Int -> [a] -> [a]
forall a. Int -> [a] -> [a]
drop (a -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral a
index) [a]
values

-- | Conservative bounds protect intermediate native fee and value arithmetic.
preflight :: Builder.Config -> [Utxo] -> Transaction -> IO (Either Error ())
preflight :: Config -> [Utxo] -> Transaction -> IO (Either Error ())
preflight Config
config [Utxo]
snapshots Transaction
transaction = ExceptT Error IO () -> IO (Either Error ())
forall e (m :: * -> *) a. ExceptT e m a -> m (Either e a)
runExceptT (ExceptT Error IO () -> IO (Either Error ()))
-> ExceptT Error IO () -> IO (Either Error ())
forall a b. (a -> b) -> a -> b
$ do
  let params :: Parameters
params = Config -> Parameters
Builder.parameters Config
config
      body :: Body
body = EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
transaction)
      intents :: [SubTransaction]
intents = [SubTransaction] -> Maybe [SubTransaction] -> [SubTransaction]
forall a. a -> Maybe a -> a
fromMaybe [] (Body -> Maybe [SubTransaction]
Body.bodySubTransactions Body
body)
      allFields :: [Fields]
allFields = Body -> Fields
Body.bodyFields Body
body Fields -> [Fields] -> [Fields]
forall a. a -> [a] -> [a]
: (SubTransaction -> Fields) -> [SubTransaction] -> [Fields]
forall a b. (a -> b) -> [a] -> [b]
map (Body -> Fields
SubBody.fields (Body -> Fields)
-> (SubTransaction -> Body) -> SubTransaction -> Fields
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedBody -> Body
SubBody.toBody (EncodedBody -> Body)
-> (SubTransaction -> EncodedBody) -> SubTransaction -> Body
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> EncodedBody
Sub.body) [SubTransaction]
intents
      outputs :: [Output]
outputs = (Fields -> [Output]) -> [Fields] -> [Output]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Fields -> [Output]
Fields.fieldOutputs [Fields]
allFields
      redeemers :: [Redeemer]
redeemers = Transaction -> [Redeemer]
outerRedeemers Transaction
transaction [Redeemer] -> [Redeemer] -> [Redeemer]
forall a. Semigroup a => a -> a -> a
<> (SubTransaction -> [Redeemer]) -> [SubTransaction] -> [Redeemer]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Witnesses -> [Redeemer]
Witnesses.redeemers (Witnesses -> [Redeemer])
-> (SubTransaction -> Witnesses) -> SubTransaction -> [Redeemer]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedWitnesses -> Witnesses
Witnesses.toWitnesses (EncodedWitnesses -> Witnesses)
-> (SubTransaction -> EncodedWitnesses)
-> SubTransaction
-> Witnesses
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> EncodedWitnesses
Sub.witnesses) [SubTransaction]
intents
  ImplicitCoin
outer <- IO (Either Error ImplicitCoin) -> ExceptT Error IO ImplicitCoin
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (Parameters -> Transaction -> IO (Either Error ImplicitCoin)
Building.implicitCoin Parameters
params Transaction
transaction)
  [ImplicitCoin]
nested <- (SubTransaction -> ExceptT Error IO ImplicitCoin)
-> [SubTransaction] -> ExceptT Error IO [ImplicitCoin]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (IO (Either Error ImplicitCoin) -> ExceptT Error IO ImplicitCoin
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (IO (Either Error ImplicitCoin) -> ExceptT Error IO ImplicitCoin)
-> (SubTransaction -> IO (Either Error ImplicitCoin))
-> SubTransaction
-> ExceptT Error IO ImplicitCoin
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Parameters -> SubTransaction -> IO (Either Error ImplicitCoin)
Building.subTransactionImplicitCoin Parameters
params) [SubTransaction]
intents
  let implicit :: [ImplicitCoin]
implicit = ImplicitCoin
outer ImplicitCoin -> [ImplicitCoin] -> [ImplicitCoin]
forall a. a -> [a] -> [a]
: [ImplicitCoin]
nested
      coin :: Integer
coin = [Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (ImplicitCoin -> Word64
Building.deposits ImplicitCoin
x) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (ImplicitCoin -> Word64
Building.reclaimedDeposits ImplicitCoin
x) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (ImplicitCoin -> Word64
Building.withdrawals ImplicitCoin
x) | ImplicitCoin
x <- [ImplicitCoin]
implicit]
      spending :: Set Input
spending = [Input] -> Set Input
forall a. Ord a => [a] -> Set a
Set.fromList ((Fields -> [Input]) -> [Fields] -> [Input]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Fields -> [Input]
Fields.fieldInputs [Fields]
allFields)
      referenced :: Set Input
referenced = [Input] -> Set Input
forall a. Ord a => [a] -> Set a
Set.fromList ((Fields -> [Input]) -> [Fields] -> [Input]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ([Input] -> Maybe [Input] -> [Input]
forall a. a -> Maybe a -> a
fromMaybe [] (Maybe [Input] -> [Input])
-> (Fields -> Maybe [Input]) -> Fields -> [Input]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Fields -> Maybe [Input]
Fields.fieldReferenceInputs) [Fields]
allFields)
      authorized :: Set Input
authorized = [Input] -> Set Input
forall a. Ord a => [a] -> Set a
Set.fromList ((Utxo -> Input) -> [Utxo] -> [Input]
forall a b. (a -> b) -> [a] -> [b]
map Utxo -> Input
Utxo.input (Config -> [Utxo]
Builder.availableUtxos Config
config))
      potential :: [Utxo]
potential = (Utxo -> Bool) -> [Utxo] -> [Utxo]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Utxo
u -> Utxo -> Input
Utxo.input Utxo
u Input -> Set Input -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set Input
spending Bool -> Bool -> Bool
|| (Utxo -> Input
Utxo.input Utxo
u Input -> Set Input -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set Input
authorized Bool -> Bool -> Bool
&& Utxo -> Input
Utxo.input Utxo
u Input -> Set Input -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.notMember` Set Input
referenced)) [Utxo]
snapshots
      mint :: [(AssetId, Integer)]
mint = (Fields -> [(AssetId, Integer)])
-> [Fields] -> [(AssetId, Integer)]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ([(AssetId, Integer)]
-> (Mint -> [(AssetId, Integer)])
-> Maybe Mint
-> [(AssetId, Integer)]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] (Value -> [(AssetId, Integer)]
Value.toList (Value -> [(AssetId, Integer)])
-> (Mint -> Value) -> Mint -> [(AssetId, Integer)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Mint -> Value
Fields.mintValue) (Maybe Mint -> [(AssetId, Integer)])
-> (Fields -> Maybe Mint) -> Fields -> [(AssetId, Integer)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Fields -> Maybe Mint
Fields.fieldMint) [Fields]
allFields
      consumed :: Map AssetId Integer
consumed = (Integer -> Integer -> Integer)
-> [(AssetId, Integer)] -> Map AssetId Integer
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
(+) ((Utxo -> [(AssetId, Integer)]) -> [Utxo] -> [(AssetId, Integer)]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Value -> [(AssetId, Integer)]
Value.toList (Value -> [(AssetId, Integer)])
-> (Utxo -> Value) -> Utxo -> [(AssetId, Integer)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Output -> Value
Output.value (Output -> Value) -> (Utxo -> Output) -> Utxo -> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Utxo -> Output
Utxo.output) [Utxo]
potential [(AssetId, Integer)]
-> [(AssetId, Integer)] -> [(AssetId, Integer)]
forall a. Semigroup a => a -> a -> a
<> [(AssetId
asset, Integer
amount) | (AssetId
asset, Integer
amount) <- [(AssetId, Integer)]
mint, Integer
amount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer
0])
      produced :: Map AssetId Integer
produced = (Integer -> Integer -> Integer)
-> [(AssetId, Integer)] -> Map AssetId Integer
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
(+) ((Output -> [(AssetId, Integer)])
-> [Output] -> [(AssetId, Integer)]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Value -> [(AssetId, Integer)]
Value.toList (Value -> [(AssetId, Integer)])
-> (Output -> Value) -> Output -> [(AssetId, Integer)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Output -> Value
Output.value) [Output]
outputs [(AssetId, Integer)]
-> [(AssetId, Integer)] -> [(AssetId, Integer)]
forall a. Semigroup a => a -> a -> a
<> [(AssetId
asset, Integer -> Integer
forall a. Num a => a -> a
negate Integer
amount) | (AssetId
asset, Integer
amount) <- [(AssetId, Integer)]
mint, Integer
amount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Integer
0])
      totals :: Map AssetId Integer
totals = (Integer -> Integer -> Integer)
-> Map AssetId Integer
-> Map AssetId Integer
-> Map AssetId Integer
forall k a. Ord k => (a -> a -> a) -> Map k a -> Map k a -> Map k a
Map.unionWith Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
max Map AssetId Integer
consumed Map AssetId Integer
produced
      collateral :: Map AssetId Integer
collateral = (Integer -> Integer -> Integer)
-> [(AssetId, Integer)] -> Map AssetId Integer
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
(+) ((Utxo -> [(AssetId, Integer)]) -> [Utxo] -> [(AssetId, Integer)]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Value -> [(AssetId, Integer)]
Value.toList (Value -> [(AssetId, Integer)])
-> (Utxo -> Value) -> Utxo -> [(AssetId, Integer)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Output -> Value
Output.value (Output -> Value) -> (Utxo -> Output) -> Utxo -> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Utxo -> Output
Utxo.output) (Config -> [Utxo]
Builder.collateralUtxos Config
config))
  Either Error () -> ExceptT Error IO ()
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except ((Integer -> Either Error ()) -> [Integer] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Text -> Integer -> Either Error ()
bounded Text
"Aggregate balance exceeds signed native bounds") (Integer
coin Integer -> [Integer] -> [Integer]
forall a. a -> [a] -> [a]
: Map AssetId Integer -> [Integer]
forall k a. Map k a -> [a]
Map.elems Map AssetId Integer
totals [Integer] -> [Integer] -> [Integer]
forall a. Semigroup a => a -> a -> a
<> Map AssetId Integer -> [Integer]
forall k a. Map k a -> [a]
Map.elems Map AssetId Integer
collateral))
  Either Error () -> ExceptT Error IO ()
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (Text -> Integer -> Either Error ()
bounded Text
"Deposit exceeds signed native bounds" (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
P.parameterKeyDeposit Parameters
params) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
P.parameterPoolDeposit Parameters
params)))
  let maximumSize :: Integer
maximumSize = Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
P.parameterMaxTxSize Parameters
params)
      extraKeys :: Integer
extraKeys = Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Config -> Word64
Builder.extraSigners Config
config)
      snapshotSize :: Integer
snapshotSize = Int -> Integer
forall a. Integral a => a -> Integer
toInteger (ByteString -> Int
B.length (Transaction -> ByteString
Tx.encodeCbor Transaction
transaction)) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ [Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Int -> Integer
forall a. Integral a => a -> Integer
toInteger (ByteString -> Int
B.length (Utxo -> ByteString
Utxo.encodeCbor Utxo
u)) | Utxo
u <- [Utxo]
snapshots]
      changeSize :: Integer
changeSize = (Int -> Integer
forall a. Integral a => a -> Integer
toInteger ([Output] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Output]
outputs) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
1) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* (Integer
snapshotSize Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
1) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* (Integer
snapshotSize Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Int -> Integer
forall a. Integral a => a -> Integer
toInteger (ByteString -> Int
B.length (Address -> ByteString
Address.toBytes (Config -> Address
Builder.changeAddress Config
config))) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
256)
      sizeBound :: Integer
sizeBound = Integer
snapshotSize Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
changeSize Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
1024 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
101 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* (Integer
extraKeys Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Int -> Integer
forall a. Integral a => a -> Integer
toInteger ([Utxo] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Utxo]
snapshots))
  Either Error () -> ExceptT Error IO ()
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Integer
extraKeys Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Integer
maximumSize Integer -> Integer -> Integer
forall a. Integral a => a -> a -> a
`div` Integer
101) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Additional signer witnesses exceed maximum transaction size")))
  Either Error () -> ExceptT Error IO ()
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (Text -> Integer -> Either Error ()
bounded Text
"Minimum Ada multiplication exceeds signed bounds" (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Word64 -> Maybe Word64 -> Word64
forall a. a -> Maybe a -> a
fromMaybe Word64
0 (Parameters -> Maybe Word64
P.parameterAdaPerUtxoByte Parameters
params)) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* (Integer
maximumSize Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
160)))
  Either Error () -> ExceptT Error IO ()
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (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 ((Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Integer
maximumSize) (Integer -> Bool) -> (Output -> Integer) -> Output -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Integer
forall a. Integral a => a -> Integer
toInteger (Int -> Integer) -> (Output -> Int) -> Output -> Integer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Int
B.length (ByteString -> Int) -> (Output -> ByteString) -> Output -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Output -> ByteString
Output.encodeCbor) [Output]
outputs) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Output exceeds maximum transaction size")))
  Word64
referenceFee <- if (Utxo -> Bool) -> [Utxo] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (Maybe Script -> Bool
forall a. Maybe a -> Bool
isJust (Maybe Script -> Bool) -> (Utxo -> Maybe Script) -> Utxo -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Output -> Maybe Script
Output.referenceScript (Output -> Maybe Script)
-> (Utxo -> Output) -> Utxo -> Maybe Script
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Utxo -> Output
Utxo.output) [Utxo]
snapshots then IO (Either Error Word64) -> ExceptT Error IO Word64
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (Parameters -> [Utxo] -> IO (Either Error Word64)
Builder.pricedReferenceFee Parameters
params ([Utxo]
snapshots [Utxo] -> [Utxo] -> [Utxo]
forall a. Semigroup a => a -> a -> a
<> (SubTransaction -> [Utxo]) -> [SubTransaction] -> [Utxo]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ([Utxo] -> SubTransaction -> [Utxo]
forall a b. a -> b -> a
const [Utxo]
snapshots) [SubTransaction]
intents)) else Word64 -> ExceptT Error IO Word64
forall a. a -> ExceptT Error IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Word64
0
  Integer
executionFee <-
    Either Error Integer -> ExceptT Error IO Integer
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (Either Error Integer -> ExceptT Error IO Integer)
-> Either Error Integer -> ExceptT Error IO Integer
forall a b. (a -> b) -> a -> b
$
      if [Redeemer] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Redeemer]
redeemers
        then Integer -> Either Error Integer
forall a b. b -> Either a b
Right Integer
0
        else do
          ExUnitPrices
prices <- Either Error ExUnitPrices
-> (ExUnitPrices -> Either Error ExUnitPrices)
-> Maybe ExUnitPrices
-> Either Error ExUnitPrices
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Error -> Either Error ExUnitPrices
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Script execution prices are required")) ExUnitPrices -> Either Error ExUnitPrices
forall a b. b -> Either a b
Right (Parameters -> Maybe ExUnitPrices
P.parameterExecutionCosts Parameters
params)
          ExUnits
cap <- Either Error ExUnits
-> (ExUnits -> Either Error ExUnits)
-> Maybe ExUnits
-> Either Error ExUnits
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Error -> Either Error ExUnits
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Maximum transaction execution units are required")) ExUnits -> Either Error ExUnits
forall a b. b -> Either a b
Right (Parameters -> Maybe ExUnits
P.parameterMaxTxExUnits Parameters
params)
          Integer -> Either Error Integer
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Rational -> Integer
forall b. Integral b => Rational -> b
forall a b. (RealFrac a, Integral b) => a -> b
ceiling (Word64 -> Rational
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ExUnits -> Word64
Ex.memory ExUnits
cap) Rational -> Rational -> Rational
forall a. Num a => a -> a -> a
* NonNegativeRational -> Rational
Rational.toRational (ExUnitPrices -> NonNegativeRational
Prices.memoryPrice ExUnitPrices
prices) Rational -> Rational -> Rational
forall a. Num a => a -> a -> a
+ Word64 -> Rational
forall a b. (Integral a, Num b) => a -> b
fromIntegral (ExUnits -> Word64
Ex.steps ExUnits
cap) Rational -> Rational -> Rational
forall a. Num a => a -> a -> a
* NonNegativeRational -> Rational
Rational.toRational (ExUnitPrices -> NonNegativeRational
Prices.stepPrice ExUnitPrices
prices)))
  let feeBound :: Integer
feeBound = Integer -> Integer -> Integer
forall a. Ord a => a -> a -> a
max (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Word64 -> Word64 -> Word64
forall a. Ord a => a -> a -> a
max (Body -> Word64
Body.fee Body
body) (Config -> Word64
Builder.minimumFee Config
config))) (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
P.parameterMinFeeB Parameters
params) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
P.parameterMinFeeA Parameters
params) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
sizeBound Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
executionFee Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
referenceFee)
  Either Error () -> ExceptT Error IO ()
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (Text -> Integer -> Either Error ()
bounded Text
"Priced transaction exceeds signed balance bounds" (Integer
feeBound Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
coin Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer -> AssetId -> Map AssetId Integer -> Integer
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Integer
0 AssetId
Ada Map AssetId Integer
totals))

bounded :: Text -> Integer -> Either Error ()
bounded :: Text -> Integer -> Either Error ()
bounded Text
message Integer
value = Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Integer
value Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Integer
0 Bool -> Bool -> Bool
&& Integer
value 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
InvalidBuildingRequest Text
message))

-- | Run all callback owners under the same protected native operation.
runBalance :: Builder.Config -> [Utxo] -> Map Eval.RedeemerId DeferredRedeemer -> Transaction -> IO (Either Error Transaction)
runBalance :: Config
-> [Utxo]
-> Map RedeemerId DeferredRedeemer
-> Transaction
-> IO (Either Error Transaction)
runBalance Config
config [Utxo]
snapshots Map RedeemerId DeferredRedeemer
callbacks Transaction
original =
  Dispatch
-> (Runtime -> IO (Either Error Transaction))
-> IO (Either Error Transaction)
forall a.
Dispatch -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
Runtime.withRuntime Dispatch
selection ((Runtime -> IO (Either Error Transaction))
 -> IO (Either Error Transaction))
-> (Runtime -> IO (Either Error Transaction))
-> IO (Either Error Transaction)
forall a b. (a -> b) -> a -> b
$ \Runtime
selector ->
    Dispatch
-> (Runtime -> IO (Either Error Transaction))
-> IO (Either Error Transaction)
forall a.
Dispatch -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
Runtime.withRuntime (Evaluator -> Target -> Dispatch
Evaluation.dispatch (Config -> Evaluator -> Evaluator
Builder.checkedEvaluator Config
config (Config -> Evaluator
evaluatorFor Config
config)) Target
Eval.TopLevel) ((Runtime -> IO (Either Error Transaction))
 -> IO (Either Error Transaction))
-> (Runtime -> IO (Either Error Transaction))
-> IO (Either Error Transaction)
forall a b. (a -> b) -> a -> b
$ \Runtime
evaluator ->
      Dispatch
-> (Runtime -> IO (Either Error Transaction))
-> IO (Either Error Transaction)
forall a.
Dispatch -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
Runtime.withRuntime (Transaction -> Map RedeemerId DeferredRedeemer -> Dispatch
deferredDispatch Transaction
original Map RedeemerId DeferredRedeemer
callbacks) ((Runtime -> IO (Either Error Transaction))
 -> IO (Either Error Transaction))
-> (Runtime -> IO (Either Error Transaction))
-> IO (Either Error Transaction)
forall a b. (a -> b) -> a -> b
$ \Runtime
deferred -> do
        Either Error (ByteString, Word64)
result <- [Runtime]
-> ([Ptr Context] -> IO (Either Error (ByteString, Word64)))
-> IO (Either Error (ByteString, Word64))
forall a.
[Runtime]
-> ([Ptr Context] -> IO (Either Error a)) -> IO (Either Error a)
Runtime.withOperations [Runtime
selector, Runtime
evaluator, Runtime
deferred] (([Ptr Context] -> IO (Either Error (ByteString, Word64)))
 -> IO (Either Error (ByteString, Word64)))
-> ([Ptr Context] -> IO (Either Error (ByteString, Word64)))
-> IO (Either Error (ByteString, Word64))
forall a b. (a -> b) -> a -> b
$ \case
          [Ptr Context
selectionContext, Ptr Context
evaluationContext, Ptr Context
deferredContext] ->
            ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error (ByteString, Word64)))
-> IO (Either Error (ByteString, Word64))
forall a. ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a
Runtime.withBytes (Plan -> Config -> ByteString
Builder.encodeConfig Plan
forall a. Monoid a => a
mempty Config
configured) ((Ptr Word8 -> CSize -> IO (Either Error (ByteString, Word64)))
 -> IO (Either Error (ByteString, Word64)))
-> (Ptr Word8 -> CSize -> IO (Either Error (ByteString, Word64)))
-> IO (Either Error (ByteString, Word64))
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
configBytes CSize
configSize ->
              ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error (ByteString, Word64)))
-> IO (Either Error (ByteString, Word64))
forall a. ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a
Runtime.withBytes ([Utxo]
-> Map RedeemerId DeferredRedeemer -> Transaction -> ByteString
encodeRequest [Utxo]
snapshots Map RedeemerId DeferredRedeemer
callbacks Transaction
unsigned) ((Ptr Word8 -> CSize -> IO (Either Error (ByteString, Word64)))
 -> IO (Either Error (ByteString, Word64)))
-> (Ptr Word8 -> CSize -> IO (Either Error (ByteString, Word64)))
-> IO (Either Error (ByteString, Word64))
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
requestBytes CSize
requestSize ->
                Text
-> (Ptr (Ptr Buffer)
    -> Ptr (Ptr Buffer) -> Ptr Word64 -> IO NativeCode)
-> IO (Either Error (ByteString, Word64))
Builder.withResultNamed Text
"transaction.balance" (Ptr Context
-> Ptr Context
-> Ptr Context
-> Ptr Word8
-> CSize
-> Ptr Word8
-> CSize
-> Ptr (Ptr Buffer)
-> Ptr (Ptr Buffer)
-> Ptr Word64
-> IO NativeCode
FFI.cBalance (if Maybe Selector -> Bool
forall a. Maybe a -> Bool
isJust (Config -> Maybe Selector
Builder.selector Config
config) then Ptr Context
selectionContext else Ptr Context
forall a. Ptr a
nullPtr) Ptr Context
evaluationContext Ptr Context
deferredContext Ptr Word8
configBytes CSize
configSize Ptr Word8
requestBytes CSize
requestSize)
          [Ptr Context]
_ -> Either Error (ByteString, Word64)
-> IO (Either Error (ByteString, Word64))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error (ByteString, Word64)
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"balancing.contexts"))
        Either Error Transaction -> IO (Either Error Transaction)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error Transaction -> IO (Either Error Transaction))
-> Either Error Transaction -> IO (Either Error Transaction)
forall a b. (a -> b) -> a -> b
$ do
          (ByteString
bytes, Word64
keys) <- Either Error (ByteString, Word64)
result
          Transaction
transaction <- ByteString -> Either Error Transaction
Tx.decodeCbor ByteString
bytes
          let reserve :: Integer
reserve = [Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Integer
180 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Int -> Integer
forall a. Integral a => a -> Integer
toInteger (ByteString -> Int
B.length ByteString
address) | ByteString
address <- Set ByteString -> [ByteString]
forall a. Set a -> [a]
Set.toList ([Utxo] -> Transaction -> Set ByteString
byronAddresses [Utxo]
snapshots Transaction
transaction)]
              size :: Integer
size = Int -> Integer
forall a. Integral a => a -> Integer
toInteger (ByteString -> Int
B.length ByteString
bytes) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
101 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
keys Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
reserve Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
32
          Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Integer
size Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
P.parameterMaxTxSize (Config -> Parameters
Builder.parameters Config
config))) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Balanced transaction and witnesses exceed maximum size"))
          Transaction -> Either Error Transaction
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Transaction
transaction
  where
    unsigned :: Transaction
unsigned = EncodedWitnesses -> Transaction -> Transaction
Tx.setWitnesses (EncodedWitnesses -> EncodedWitnesses
Witnesses.removeKeyWitnesses (Transaction -> EncodedWitnesses
Tx.witnesses Transaction
original)) Transaction
original
    body :: Body
body = EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
original)
    fields :: Fields
fields = Body -> Fields
Body.bodyFields Body
body
    reserved :: [Input]
reserved = Fields -> [Input]
references Fields
fields
    nestedReferences :: [Input]
nestedReferences = [Input]
-> ([SubTransaction] -> [Input])
-> Maybe [SubTransaction]
-> [Input]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ((SubTransaction -> [Input]) -> [SubTransaction] -> [Input]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Fields -> [Input]
references (Fields -> [Input])
-> (SubTransaction -> Fields) -> SubTransaction -> [Input]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Body -> Fields
SubBody.fields (Body -> Fields)
-> (SubTransaction -> Body) -> SubTransaction -> Fields
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedBody -> Body
SubBody.toBody (EncodedBody -> Body)
-> (SubTransaction -> EncodedBody) -> SubTransaction -> Body
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> EncodedBody
Sub.body)) (Body -> Maybe [SubTransaction]
Body.bodySubTransactions Body
body)
    originalCollateral :: [Input]
originalCollateral = [Input] -> Maybe [Input] -> [Input]
forall a. a -> Maybe a -> a
fromMaybe [] (Body -> Maybe [Input]
Body.bodyCollateral Body
body)
    configured :: Config
configured =
      Config
config
        { Builder.availableUtxos = Map.elems (Map.fromList [(Utxo.input u, u) | u <- Builder.availableUtxos config <> filter (\Utxo
u -> Utxo -> Input
Utxo.input Utxo
u Input -> [Input] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Input]
nestedReferences) snapshots, Utxo.input u `notElem` reserved]),
          Builder.collateralUtxos = Map.elems (Map.fromList [(Utxo.input u, u) | u <- Builder.collateralUtxos config <> filter (\Utxo
u -> Utxo -> Input
Utxo.input Utxo
u Input -> [Input] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Input]
originalCollateral) snapshots])
        }
    selection :: Dispatch
selection = Dispatch -> (Selector -> Dispatch) -> Maybe Selector -> Dispatch
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (\Word32
_ ByteString
_ -> Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"balancing.selector"))) Selector -> Dispatch
Selection.dispatch (Config -> Maybe Selector
Builder.selector Config
config)

-- | Native evaluator remains explicit IO, including inside native callback dispatch.
evaluatorFor :: Builder.Config -> Eval.Evaluator
evaluatorFor :: Config -> Evaluator
evaluatorFor Config
config = Evaluator -> Maybe Evaluator -> Evaluator
forall a. a -> Maybe a -> a
fromMaybe Evaluator
native (Config -> Maybe Evaluator
Builder.evaluator Config
config)
  where
    Version.ProtocolVersion Word64
major Word32
_ = Parameters -> ProtocolVersion
P.parameterProtocolVersion (Config -> Parameters
Builder.parameters Config
config)
    native :: Evaluator
native = Config -> Evaluator
NativeEvaluation.evaluator (SlotConfig -> Word64 -> CostModels -> Config
NativeEvaluation.Config (Config -> SlotConfig
Builder.slotConfig Config
config) Word64
major (CostModels -> Maybe CostModels -> CostModels
forall a. a -> Maybe a -> a
fromMaybe CostModels
Models.empty (Parameters -> Maybe CostModels
P.parameterCostModels (Config -> Parameters
Builder.parameters Config
config))))

validateResult :: Builder.Config -> Transaction -> Either Error ()
validateResult :: Config -> Transaction -> Either Error ()
validateResult Config
config Transaction
transaction = Config -> [ExUnits] -> Either Error ()
Builder.validateBudget Config
config ((Redeemer -> ExUnits) -> [Redeemer] -> [ExUnits]
forall a b. (a -> b) -> [a] -> [b]
map Redeemer -> ExUnits
Redeemer.executionUnits [Redeemer]
redeemers)
  where
    redeemers :: [Redeemer]
redeemers = Transaction -> [Redeemer]
outerRedeemers Transaction
transaction [Redeemer] -> [Redeemer] -> [Redeemer]
forall a. Semigroup a => a -> a -> a
<> [Redeemer]
-> ([SubTransaction] -> [Redeemer])
-> Maybe [SubTransaction]
-> [Redeemer]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] ((SubTransaction -> [Redeemer]) -> [SubTransaction] -> [Redeemer]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Witnesses -> [Redeemer]
Witnesses.redeemers (Witnesses -> [Redeemer])
-> (SubTransaction -> Witnesses) -> SubTransaction -> [Redeemer]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedWitnesses -> Witnesses
Witnesses.toWitnesses (EncodedWitnesses -> Witnesses)
-> (SubTransaction -> EncodedWitnesses)
-> SubTransaction
-> Witnesses
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> EncodedWitnesses
Sub.witnesses)) (Body -> Maybe [SubTransaction]
Body.bodySubTransactions (EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
transaction)))

references :: Fields.Fields -> [Input.Input]
references :: Fields -> [Input]
references Fields
fields = Fields -> [Input]
Fields.fieldInputs Fields
fields [Input] -> [Input] -> [Input]
forall a. Semigroup a => a -> a -> a
<> [Input] -> Maybe [Input] -> [Input]
forall a. a -> Maybe a -> a
fromMaybe [] (Fields -> Maybe [Input]
Fields.fieldReferenceInputs Fields
fields)

outerRedeemers :: Transaction -> [Redeemer.Redeemer]
outerRedeemers :: Transaction -> [Redeemer]
outerRedeemers = Witnesses -> [Redeemer]
Witnesses.redeemers (Witnesses -> [Redeemer])
-> (Transaction -> Witnesses) -> Transaction -> [Redeemer]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedWitnesses -> Witnesses
Witnesses.toWitnesses (EncodedWitnesses -> Witnesses)
-> (Transaction -> EncodedWitnesses) -> Transaction -> Witnesses
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Transaction -> EncodedWitnesses
Tx.witnesses

identifier :: Redeemer.Redeemer -> Eval.RedeemerId
identifier :: Redeemer -> RedeemerId
identifier Redeemer
r = Purpose -> Word32 -> RedeemerId
Eval.RedeemerId (Redeemer -> Purpose
Redeemer.purpose Redeemer
r) (Redeemer -> Word32
Redeemer.index Redeemer
r)

encodeRequest :: [Utxo] -> Map Eval.RedeemerId DeferredRedeemer -> Transaction -> ByteString
encodeRequest :: [Utxo]
-> Map RedeemerId DeferredRedeemer -> Transaction -> ByteString
encodeRequest [Utxo]
snapshots Map RedeemerId DeferredRedeemer
callbacks Transaction
transaction =
  Encoding -> ByteString
C.encode (Encoding -> ByteString) -> Encoding -> ByteString
forall a b. (a -> b) -> a -> b
$
    Word -> Encoding
E.encodeListLen Word
4
      Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
E.encodeBytes (Transaction -> ByteString
Tx.encodeCbor Transaction
transaction)
      Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> [Utxo] -> Encoding
forall {t :: * -> *}. Foldable t => t Utxo -> Encoding
utxos [Utxo]
refs
      Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> [Utxo] -> Encoding
forall {t :: * -> *}. Foldable t => t Utxo -> Encoding
utxos [Utxo]
spending
      Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word -> Encoding
E.encodeListLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Redeemer] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Redeemer]
redeemers))
      Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Redeemer -> Encoding) -> [Redeemer] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap Redeemer -> Encoding
entry [Redeemer]
redeemers
  where
    fields :: Fields
fields = Body -> Fields
Body.bodyFields (EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
transaction))
    redeemers :: [Redeemer]
redeemers = Transaction -> [Redeemer]
outerRedeemers Transaction
transaction
    refs :: [Utxo]
refs = (Utxo -> Bool) -> [Utxo] -> [Utxo]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Utxo
u -> Utxo -> Input
Utxo.input Utxo
u Input -> [Input] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Input] -> Maybe [Input] -> [Input]
forall a. a -> Maybe a -> a
fromMaybe [] (Fields -> Maybe [Input]
Fields.fieldReferenceInputs Fields
fields)) [Utxo]
snapshots
    spending :: [Utxo]
spending = (Utxo -> Bool) -> [Utxo] -> [Utxo]
forall a. (a -> Bool) -> [a] -> [a]
filter (\Utxo
u -> Utxo -> Input
Utxo.input Utxo
u Input -> [Input] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` Fields -> [Input]
Fields.fieldInputs Fields
fields) [Utxo]
snapshots
    utxos :: t Utxo -> Encoding
utxos t Utxo
values = Word -> Encoding
E.encodeListLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (t Utxo -> Int
forall a. t a -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length t Utxo
values)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Utxo -> Encoding) -> t Utxo -> Encoding
forall m a. Monoid m => (a -> m) -> t a -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (ByteString -> Encoding
C.raw (ByteString -> Encoding)
-> (Utxo -> ByteString) -> Utxo -> Encoding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Utxo -> ByteString
Utxo.encodeCbor) t Utxo
values
    entry :: Redeemer -> Encoding
entry Redeemer
r =
      Word -> Encoding
E.encodeListLen Word
4
        Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word -> Encoding
E.encodeWord (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Purpose -> Int
forall a. Enum a => a -> Int
fromEnum (Redeemer -> Purpose
Redeemer.purpose Redeemer
r)))
        Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word32 -> Encoding
E.encodeWord32 (Redeemer -> Word32
Redeemer.index Redeemer
r)
        Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
E.encodeBytes ((Error -> ByteString)
-> (Maybe Input -> ByteString)
-> Either Error (Maybe Input)
-> ByteString
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (ByteString -> Error -> ByteString
forall a b. a -> b -> a
const ByteString
forall a. Monoid a => a
mempty) (ByteString -> (Input -> ByteString) -> Maybe Input -> ByteString
forall b a. b -> (a -> b) -> Maybe a -> b
maybe ByteString
forall a. Monoid a => a
mempty Input -> ByteString
Input.encodeCbor) (Fields -> Redeemer -> Either Error (Maybe Input)
spendingInput Fields
fields Redeemer
r))
        Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Bool -> Encoding
E.encodeBool (RedeemerId -> Map RedeemerId DeferredRedeemer -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member (Redeemer -> RedeemerId
identifier Redeemer
r) Map RedeemerId DeferredRedeemer
callbacks)

-- | Decode and fully force callback replies inside Runtime's exception boundary.
deferredDispatch :: Transaction -> Map Eval.RedeemerId DeferredRedeemer -> Runtime.Dispatch
deferredDispatch :: Transaction -> Map RedeemerId DeferredRedeemer -> Dispatch
deferredDispatch Transaction
original Map RedeemerId DeferredRedeemer
callbacks Word32
operation ByteString
bytes
  | Word32
operation Word32 -> Word32 -> Bool
forall a. Eq a => a -> a -> Bool
/= Word32
110 = Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Text -> Error
UnsupportedOperation Text
"Unknown balancing callback operation"))
  | Bool
otherwise = Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error ByteString -> IO (Either Error ByteString))
-> Either Error ByteString -> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ do
      (Int
index, Transaction
transaction, [Utxo]
inputs) <- (Text -> Error)
-> (forall s. Decoder s (Int, Transaction, [Utxo]))
-> ByteString
-> Either Error (Int, Transaction, [Utxo])
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
C.decodeAs Text -> Error
InvalidBuildingRequest Decoder s (Int, Transaction, [Utxo])
forall s. Decoder s (Int, Transaction, [Utxo])
parser ByteString
bytes
      RedeemerId
ident <- Either Error RedeemerId
-> (RedeemerId -> Either Error RedeemerId)
-> Maybe RedeemerId
-> Either Error RedeemerId
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Error -> Either Error RedeemerId
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"balancing.callbackIndex")) RedeemerId -> Either Error RedeemerId
forall a b. b -> Either a b
Right (Int -> Map Int RedeemerId -> Maybe RedeemerId
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Int
index Map Int RedeemerId
identifiers)
      DeferredRedeemer
callback <- Either Error DeferredRedeemer
-> (DeferredRedeemer -> Either Error DeferredRedeemer)
-> Maybe DeferredRedeemer
-> Either Error DeferredRedeemer
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Error -> Either Error DeferredRedeemer
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"balancing.callback")) DeferredRedeemer -> Either Error DeferredRedeemer
forall a b. b -> Either a b
Right (RedeemerId
-> Map RedeemerId DeferredRedeemer -> Maybe DeferredRedeemer
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup RedeemerId
ident Map RedeemerId DeferredRedeemer
callbacks)
      let selected :: [Utxo]
selected = (Utxo -> Input) -> [Utxo] -> [Utxo]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn Utxo -> Input
Utxo.input [Utxo]
inputs
      Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((Utxo -> Input) -> [Utxo] -> [Input]
forall a b. (a -> b) -> [a] -> [b]
map Utxo -> Input
Utxo.input [Utxo]
selected [Input] -> [Input] -> Bool
forall a. Eq a => a -> a -> Bool
== [Input] -> [Input]
forall a. Ord a => [a] -> [a]
sort (Fields -> [Input]
Fields.fieldInputs (Body -> Fields
Body.bodyFields (EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
transaction))))) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"balancing.callbackInputs"))
      EncodedPlutusData -> ByteString
Data.toCbor (EncodedPlutusData -> ByteString)
-> Either Error EncodedPlutusData -> Either Error ByteString
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> DeferredRedeemer
callback Transaction
transaction [Utxo]
selected
  where
    identifiers :: Map Int RedeemerId
identifiers = [(Int, RedeemerId)] -> Map Int RedeemerId
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList ([Int] -> [RedeemerId] -> [(Int, RedeemerId)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Int
0 :: Int ..] ((Redeemer -> RedeemerId) -> [Redeemer] -> [RedeemerId]
forall a b. (a -> b) -> [a] -> [b]
map Redeemer -> RedeemerId
identifier (Transaction -> [Redeemer]
outerRedeemers Transaction
original)))
    parser :: Decoder s (Int, Transaction, [Utxo])
parser = Int
-> Decoder s (Int, Transaction, [Utxo])
-> Decoder s (Int, Transaction, [Utxo])
forall s a. Int -> Decoder s a -> Decoder s a
C.array Int
3 ((,,) (Int -> Transaction -> [Utxo] -> (Int, Transaction, [Utxo]))
-> Decoder s Int
-> Decoder s (Transaction -> [Utxo] -> (Int, Transaction, [Utxo]))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Decoder s Int
forall s. Decoder s Int
D.decodeInt Decoder s (Transaction -> [Utxo] -> (Int, Transaction, [Utxo]))
-> Decoder s Transaction
-> Decoder s ([Utxo] -> (Int, Transaction, [Utxo]))
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 Transaction)
-> Decoder s Transaction
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
C.nested ByteString
bytes ByteString -> Either Error Transaction
Tx.decodeCbor Decoder s ([Utxo] -> (Int, Transaction, [Utxo]))
-> Decoder s [Utxo] -> Decoder s (Int, Transaction, [Utxo])
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]
C.list (ByteString -> (ByteString -> Either Error Utxo) -> Decoder s Utxo
forall a s.
ByteString -> (ByteString -> Either Error a) -> Decoder s a
C.nested ByteString
bytes ByteString -> Either Error Utxo
Utxo.decodeCbor))

-- | Inspect exact body collection lengths so imported zero mint groups still count.
validatePurpose :: Transaction -> Redeemer.Redeemer -> Either Error ()
validatePurpose :: Transaction -> Redeemer -> Either Error ()
validatePurpose Transaction
transaction Redeemer
redeemer = do
  let bytes :: ByteString
bytes = EncodedBody -> ByteString
Body.toCbor (Transaction -> EncodedBody
Tx.body Transaction
transaction)
      key :: Word64
key = case Redeemer -> Purpose
Redeemer.purpose Redeemer
redeemer of
        Purpose
Redeemer.Spending -> Word64
0
        Purpose
Redeemer.Minting -> Word64
9
        Purpose
Redeemer.Certifying -> Word64
4
        Purpose
Redeemer.Rewarding -> Word64
5
        Purpose
Redeemer.Voting -> Word64
19
        Purpose
Redeemer.Proposing -> Word64
20
        Purpose
Redeemer.Guarding -> Word64
14
  Map Word64 ByteString
fields <- (Text -> Error)
-> (forall s. Decoder s (Map Word64 ByteString))
-> ByteString
-> Either Error (Map Word64 ByteString)
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
C.decodeAs Text -> Error
InvalidBuildingRequest (ByteString -> Decoder s (Map Word64 ByteString)
forall s. ByteString -> Decoder s (Map Word64 ByteString)
C.mapFields ByteString
bytes) ByteString
bytes
  Int
count <- case Word64 -> Map Word64 ByteString -> Maybe ByteString
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Word64
key Map Word64 ByteString
fields of
    Maybe ByteString
Nothing -> Int -> Either Error Int
forall a b. b -> Either a b
Right Int
0
    Just ByteString
encoded -> Term -> Int
collectionLength (Term -> Int) -> Either Error Term -> Either Error Int
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Text -> Error)
-> (forall s. Decoder s Term) -> ByteString -> Either Error Term
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
C.decodeAs Text -> Error
InvalidBuildingRequest Decoder s Term
forall s. Decoder s Term
Term.decodeTerm ByteString
encoded
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Word32 -> Integer
forall a. Integral a => a -> Integer
toInteger (Redeemer -> Word32
Redeemer.index Redeemer
redeemer) Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
< Int -> Integer
forall a. Integral a => a -> Integer
toInteger Int
count) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Redeemer index has no body operation"))
  where
    collectionLength :: Term -> Int
collectionLength Term
term = case Term
term of
      Term.TTagged Word64
_ Term
value -> Term -> Int
collectionLength Term
value
      Term.TList [Term]
values -> [Term] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Term]
values
      Term.TListI [Term]
values -> [Term] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Term]
values
      Term.TMap [(Term, Term)]
values -> [(Term, Term)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Term, Term)]
values
      Term.TMapI [(Term, Term)]
values -> [(Term, Term)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(Term, Term)]
values
      Term
_ -> Int
0

-- | Reserve exactly the final commitment's byte length before fee calculation.
reserveScriptHash :: Transaction -> Either Error Transaction
reserveScriptHash :: Transaction -> Either Error Transaction
reserveScriptHash Transaction
transaction
  | [Redeemer] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Transaction -> [Redeemer]
outerRedeemers Transaction
transaction) Bool -> Bool -> Bool
&& [EncodedPlutusData] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Witnesses -> [EncodedPlutusData]
Witnesses.datums (EncodedWitnesses -> Witnesses
Witnesses.toWitnesses (Transaction -> EncodedWitnesses
Tx.witnesses Transaction
transaction))) = Maybe Hash32 -> Transaction -> Either Error Transaction
setScriptHash Maybe Hash32
forall a. Maybe a
Nothing Transaction
transaction
  | Bool
otherwise = ByteString -> Either Error Hash32
Datum.hashFromBytes (Int -> Word8 -> ByteString
B.replicate Int
32 Word8
0) Either Error Hash32
-> (Hash32 -> Either Error Transaction) -> Either Error Transaction
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
>>= \Hash32
hash -> Maybe Hash32 -> Transaction -> Either Error Transaction
setScriptHash (Hash32 -> Maybe Hash32
forall a. a -> Maybe a
Just Hash32
hash) Transaction
transaction

-- | Replace only the unsigned outer body's commitment; preserve other field bytes.
setScriptHash :: Maybe Datum.Hash32 -> Transaction -> Either Error Transaction
setScriptHash :: Maybe Hash32 -> Transaction -> Either Error Transaction
setScriptHash Maybe Hash32
commitment Transaction
transaction = do
  let bytes :: ByteString
bytes = EncodedBody -> ByteString
Body.toCbor (Transaction -> EncodedBody
Tx.body Transaction
transaction)
  Map Word64 ByteString
fields <- (Text -> Error)
-> (forall s. Decoder s (Map Word64 ByteString))
-> ByteString
-> Either Error (Map Word64 ByteString)
forall a.
(Text -> Error)
-> (forall s. Decoder s a) -> ByteString -> Either Error a
C.decodeAs Text -> Error
InvalidBuildingRequest (ByteString -> Decoder s (Map Word64 ByteString)
forall s. ByteString -> Decoder s (Map Word64 ByteString)
C.mapFields ByteString
bytes) ByteString
bytes
  let updated :: Map Word64 ByteString
updated = case Maybe Hash32
commitment of
        Maybe Hash32
Nothing -> Word64 -> Map Word64 ByteString -> Map Word64 ByteString
forall k a. Ord k => k -> Map k a -> Map k a
Map.delete Word64
11 Map Word64 ByteString
fields
        Just Hash32
hash -> Word64
-> ByteString -> Map Word64 ByteString -> Map Word64 ByteString
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert Word64
11 (Encoding -> ByteString
C.encode (ByteString -> Encoding
E.encodeBytes (Hash32 -> ByteString
Datum.hashBytes Hash32
hash))) Map Word64 ByteString
fields
      encoded :: ByteString
encoded = Encoding -> ByteString
C.encode (Word -> Encoding
E.encodeMapLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Map Word64 ByteString -> Int
forall k a. Map k a -> Int
Map.size Map Word64 ByteString
updated)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ((Word64, ByteString) -> Encoding)
-> [(Word64, ByteString)] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(Word64
key, ByteString
value) -> Word64 -> Encoding
E.encodeWord64 Word64
key Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
C.raw ByteString
value) (Map Word64 ByteString -> [(Word64, ByteString)]
forall k a. Map k a -> [(k, a)]
Map.toAscList Map Word64 ByteString
updated))
  EncodedBody
replacement <- ByteString -> Either Error EncodedBody
Body.decodeCbor ByteString
encoded
  Transaction -> Either Error Transaction
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (EncodedBody -> Transaction -> Transaction
Tx.setBody EncodedBody
replacement Transaction
transaction)

-- | Only actual spending/collateral Byron addresses need bootstrap reserves.
byronAddresses :: [Utxo] -> Transaction -> Set.Set ByteString
byronAddresses :: [Utxo] -> Transaction -> Set ByteString
byronAddresses [Utxo]
snapshots Transaction
transaction =
  [ByteString] -> Set ByteString
forall a. Ord a => [a] -> Set a
Set.fromList
    [ Address -> ByteString
Address.toBytes Address
address
    | Utxo
u <- [Utxo]
snapshots,
      Utxo -> Input
Utxo.input Utxo
u Input -> [Input] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Input]
used,
      let address :: Address
address = Output -> Address
Output.address (Utxo -> Output
Utxo.output Utxo
u),
      case Address
address of Address.ByronAddress Address
_ -> Bool
True; Address
_ -> Bool
False
    ]
  where
    body :: Body
body = EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
transaction)
    used :: [Input]
used = Fields -> [Input]
Fields.fieldInputs (Body -> Fields
Body.bodyFields Body
body) [Input] -> [Input] -> [Input]
forall a. Semigroup a => a -> a -> a
<> [Input] -> Maybe [Input] -> [Input]
forall a. a -> Maybe a -> a
fromMaybe [] (Body -> Maybe [Input]
Body.bodyCollateral Body
body)