-- 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 #-}

-- | Verify declared intent budgets in the completed enclosing context without
-- mutating signed bodies. Each evaluator request remains operation-scoped.
module Cometa.Internal.BatchValidation (validateSubBudgets) where

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

import Cometa.Error (Error (..))
import qualified Cometa.Evaluation as Evaluation
import qualified Cometa.Protocol.ExUnits as Ex
import qualified Cometa.SubTransaction as Sub
import qualified Cometa.Transaction as Tx
import qualified Cometa.Transaction.Body as Body
import qualified Cometa.Transaction.Redeemer as Redeemer
import qualified Cometa.Transaction.Utxo as Utxo
import qualified Cometa.Transaction.Witnesses as Witnesses
import Control.Monad (unless)
import Control.Monad.Trans.Except (ExceptT (..), except, runExceptT)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)

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

validateSubBudgets :: Evaluation.Evaluator -> [Utxo.Utxo] -> Tx.Transaction -> IO (Either Error ())
validateSubBudgets :: Evaluator -> [Utxo] -> Transaction -> IO (Either Error ())
validateSubBudgets Evaluator
evaluator [Utxo]
resolved 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
$
    ((Word64, SubTransaction) -> ExceptT Error IO ())
-> [(Word64, SubTransaction)] -> ExceptT Error IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Word64, SubTransaction) -> ExceptT Error IO ()
check ([Word64] -> [SubTransaction] -> [(Word64, SubTransaction)]
forall a b. [a] -> [b] -> [(a, b)]
zip [Word64
0 ..] [SubTransaction]
subs)
  where
    subs :: [SubTransaction]
subs = [SubTransaction] -> Maybe [SubTransaction] -> [SubTransaction]
forall a. a -> Maybe a -> a
fromMaybe [] (Body -> Maybe [SubTransaction]
Body.bodySubTransactions (EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
transaction)))
    check :: (Word64, SubTransaction) -> ExceptT Error IO ()
check (Word64
index, SubTransaction
intent) = do
      let redeemers :: [Redeemer]
redeemers = Witnesses -> [Redeemer]
Witnesses.redeemers (EncodedWitnesses -> Witnesses
Witnesses.toWitnesses (SubTransaction -> EncodedWitnesses
Sub.witnesses SubTransaction
intent))
          declared :: Map RedeemerId ExUnits
declared = [(RedeemerId, ExUnits)] -> Map RedeemerId ExUnits
forall k a. Ord k => [(k, a)] -> Map k a
Map.fromList [(Purpose -> Word32 -> RedeemerId
Evaluation.RedeemerId (Redeemer -> Purpose
Redeemer.purpose Redeemer
value) (Redeemer -> Word32
Redeemer.index Redeemer
value), Redeemer -> ExUnits
Redeemer.executionUnits Redeemer
value) | Redeemer
value <- [Redeemer]
redeemers]
      Bool -> ExceptT Error IO () -> ExceptT Error IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([Redeemer] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Redeemer]
redeemers) (ExceptT Error IO () -> ExceptT Error IO ())
-> ExceptT Error IO () -> ExceptT Error IO ()
forall a b. (a -> b) -> a -> b
$ do
        Budgets
actual <- IO (Either Error Budgets) -> ExceptT Error IO Budgets
forall e (m :: * -> *) a. m (Either e a) -> ExceptT e m a
ExceptT (Evaluator
-> Target -> Transaction -> [Utxo] -> IO (Either Error Budgets)
Evaluation.evaluate Evaluator
evaluator (Word64 -> Target
Evaluation.SubTransaction Word64
index) Transaction
transaction [Utxo]
resolved)
        Either Error () -> ExceptT Error IO ()
forall (m :: * -> *) e a. Monad m => Either e a -> ExceptT e m a
except (((RedeemerId, ExUnits) -> Either Error ())
-> [(RedeemerId, ExUnits)] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Map RedeemerId ExUnits -> (RedeemerId, ExUnits) -> Either Error ()
forall {k}.
Ord k =>
Map k ExUnits -> (k, ExUnits) -> Either Error ()
within Map RedeemerId ExUnits
declared) (Budgets -> [(RedeemerId, ExUnits)]
Evaluation.budgets Budgets
actual))
    within :: Map k ExUnits -> (k, ExUnits) -> Either Error ()
within Map k ExUnits
declared (k
identifier, ExUnits
actual) = case k -> Map k ExUnits -> Maybe ExUnits
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup k
identifier Map k ExUnits
declared of
      Maybe ExUnits
Nothing -> Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidEvaluationResult Text
"Subtransaction evaluation returned an unknown redeemer")
      Just ExUnits
limit ->
        Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless
          (ExUnits -> Word64
Ex.memory ExUnits
actual Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
<= ExUnits -> Word64
Ex.memory ExUnits
limit Bool -> Bool -> Bool
&& ExUnits -> Word64
Ex.steps ExUnits
actual Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
<= ExUnits -> Word64
Ex.steps ExUnits
limit)
          (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Attached subtransaction execution exceeds its declared budget"))