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

-- | Operation-owned native sub-builder. Runtime roots callback plans through
-- native builder destruction and joins callback cancellation before scope exit.
module Cometa.Internal.SubTransactionBuilder (Config (..), build, runUnchecked, runWithDispatch, dispatch) where

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

import qualified Codec.CBOR.Decoding as D
import qualified Codec.CBOR.Encoding as E
import Cometa.AssetId (AssetId (Ada))
import Cometa.Error (Error (..))
import qualified Cometa.Error.Code as Code
import qualified Cometa.Internal.FFI.Native as Status
import qualified Cometa.Internal.FFI.Runtime as Raw
import qualified Cometa.Internal.FFI.SubTransactionBuilder as FFI
import qualified Cometa.Internal.ParameterSnapshot as Snapshot
import qualified Cometa.Internal.Runtime as Runtime
import Cometa.Internal.SubTransactionPlan (Plan)
import qualified Cometa.Internal.SubTransactionPlan as Plan
import qualified Cometa.Internal.TransactionCbor as Cbor
import qualified Cometa.Internal.TransactionPlan as Common
import qualified Cometa.Internal.TransactionValue as ValueCbor
import qualified Cometa.PlutusData as Data
import qualified Cometa.Protocol.ExUnits as Ex
import Cometa.Protocol.Parameters (Parameters)
import qualified Cometa.Protocol.Parameters as Parameters
import Cometa.SlotConfig (SlotConfig)
import qualified Cometa.SlotConfig as Slots
import Cometa.SubTransaction (SubTransaction)
import qualified Cometa.SubTransaction as Sub
import qualified Cometa.SubTransaction.Body as SubBody
import qualified Cometa.Transaction as Tx
import qualified Cometa.Transaction.Body as Body
import Cometa.Transaction.Fields (BodyNetwork (..))
import qualified Cometa.Transaction.Fields as Fields
import qualified Cometa.Transaction.Output as Output
import qualified Cometa.Transaction.Redeemer as Redeemer
import qualified Cometa.Transaction.Utxo as Utxo
import qualified Cometa.Transaction.Witnesses as Witnesses
import qualified Cometa.Value as Value
import Control.Exception (bracket)
import Control.Monad (unless)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Int (Int64)
import Data.List (sort, sortOn)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import qualified Data.Sequence as Seq
import qualified Data.Text.Encoding as Text
import Data.Word (Word64)
import Foreign.Marshal.Alloc (alloca)
import Foreign.Ptr (Ptr, nullPtr)
import Foreign.Storable (peek, poke)

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

-- | Context for building an intent. Protocol parameters supply deposits, cost
-- models and language availability; the schedule converts explicit validity
-- slots, and the network is written into the local body.
data Config = Config
  { -- | Complete protocol parameter snapshot.
    Config -> Parameters
parameters :: !Parameters,
    -- | Constant-duration schedule in Unix milliseconds.
    Config -> SlotConfig
slotConfig :: !SlotConfig,
    -- | Ledger body network, distinct from network magic.
    Config -> BodyNetwork
networkId :: !BodyNetwork
  }
  deriving (Config -> Config -> Bool
(Config -> Config -> Bool)
-> (Config -> Config -> Bool) -> Eq Config
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Config -> Config -> Bool
== :: Config -> Config -> Bool
$c/= :: Config -> Config -> Bool
/= :: Config -> Config -> Bool
Eq, Int -> Config -> ShowS
[Config] -> ShowS
Config -> String
(Int -> Config -> ShowS)
-> (Config -> String) -> ([Config] -> ShowS) -> Show Config
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Config -> ShowS
showsPrec :: Int -> Config -> ShowS
$cshow :: Config -> String
show :: Config -> String
$cshowList :: [Config] -> ShowS
showList :: [Config] -> ShowS
Show)

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

-- | Build exactly the requested inputs and outputs with no fee, collateral,
-- balancing or change. Deferred arguments run once on the local zero-fee draft
-- before native V4 evaluation and script-data commitment. An unused or cancelled
-- mint group does not invoke its callback. Native expected errors return 'Left';
-- callback exceptions propagate after native cleanup. Aggregate quantities and
-- deposits must fit signed 64-bit. The result must fit the configured transaction
-- size and execution limits, and output values must fit their configured limit.
-- Later signatures and enclosing fields consume additional transaction space.
--
-- Scripts are evaluated at position zero in an otherwise empty enclosing batch.
-- A script that depends on the actual batch position or surrounding transaction
-- can need different budgets or fail when later assembled. Building does not
-- establish complete ledger admission, balance or the freshness of inputs.
build :: Config -> Plan -> IO (Either Error SubTransaction)
build :: Config -> Plan -> IO (Either Error SubTransaction)
build Config
config Plan
plan = case Config -> Plan -> Either Error ()
validate Config
config Plan
plan of
  Left Error
failure -> Either Error SubTransaction -> IO (Either Error SubTransaction)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Error -> Either Error SubTransaction
forall a b. a -> Either a b
Left Error
failure)
  Right () -> do
    Either Error ByteString
result <- Config -> Plan -> ByteString -> IO (Either Error ByteString)
runUnchecked Config
config Plan
plan (Word64 -> Plan -> ByteString
Common.encodePlan (Word64 -> Maybe Word64 -> Word64
forall a. a -> Maybe a -> a
fromMaybe Word64
0 (Parameters -> Maybe Word64
Parameters.parameterGovernanceActionDeposit (Config -> Parameters
parameters Config
config))) (Plan -> Plan
Plan.toPlan Plan
plan))
    Either Error SubTransaction -> IO (Either Error SubTransaction)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error SubTransaction -> IO (Either Error SubTransaction))
-> Either Error SubTransaction -> IO (Either Error SubTransaction)
forall a b. (a -> b) -> a -> b
$ do
      ByteString
bytes <- Either Error ByteString
result
      SubTransaction
transaction <- ByteString -> Either Error SubTransaction
Sub.decodeCbor ByteString
bytes
      Config -> SubTransaction -> Either Error ()
validateBuilt Config
config SubTransaction
transaction
      SubTransaction -> Either Error SubTransaction
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure SubTransaction
transaction

validate :: Config -> Plan -> Either Error ()
validate :: Config -> Plan -> Either Error ()
validate Config
config Plan
plan = do
  Parameters -> Either Error ()
Snapshot.validateNative Parameters
params
  Plan -> Either Error ()
Common.validatePlan Plan
common
  (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
Slots.slotToTime (Config -> SlotConfig
slotConfig Config
config)) (Plan -> [Word64]
Common.validitySlots Plan
common)
  let funding :: [Utxo]
funding = 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
input, Utxo
input) | Utxo
input <- Plan -> [Utxo]
Common.spendingInputs Plan
common])
  Value -> Either Error ()
boundedValue ((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) [Utxo]
funding Value -> Value -> Value
forall a. Semigroup a => a -> a -> a
<> Parameters -> Plan -> Value
Common.sourceExtras Parameters
params Plan
common)
  Value -> Either Error ()
boundedValue ((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 (Plan -> [Output]
Common.planOutputs Plan
common) Value -> Value -> Value
forall a. Semigroup a => a -> a -> a
<> Parameters -> Plan -> Value
Common.sinkExtras Parameters
params Plan
common)
  (Integer -> Either Error ()) -> [Integer] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_
    Integer -> Either Error ()
bounded
    [ Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
Parameters.parameterKeyDeposit Parameters
params),
      Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
Parameters.parameterPoolDeposit Parameters
params),
      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
Parameters.parameterGovernanceActionDeposit Parameters
params)),
      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
Parameters.parameterDrepDeposit Parameters
params))
    ]
  where
    common :: Plan
common = Plan -> Plan
Plan.toPlan Plan
plan
    params :: Parameters
params = Config -> Parameters
parameters Config
config
    bounded :: Integer -> Either Error ()
bounded Integer
amount = Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Integer
amount Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
>= Integer
0 Bool -> Bool -> Bool
&& Integer
amount 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
"Sub-transaction aggregate exceeds signed native bounds"))
    boundedValue :: Value -> Either Error ()
boundedValue Value
value = ((AssetId, Integer) -> Either Error ())
-> [(AssetId, Integer)] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Integer -> Either Error ()
bounded (Integer -> Either Error ())
-> ((AssetId, Integer) -> Integer)
-> (AssetId, Integer)
-> Either Error ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (AssetId, Integer) -> Integer
forall a b. (a, b) -> b
snd) (Value -> [(AssetId, Integer)]
Value.toList Value
value)

validateBuilt :: Config -> SubTransaction -> Either Error ()
validateBuilt :: Config -> SubTransaction -> Either Error ()
validateBuilt Config
config SubTransaction
transaction = do
  let params :: Parameters
params = Config -> Parameters
parameters Config
config
      fields :: Fields
fields = Body -> Fields
SubBody.fields (EncodedBody -> Body
SubBody.toBody (SubTransaction -> EncodedBody
Sub.body SubTransaction
transaction))
      units :: [ExUnits]
units = (Redeemer -> ExUnits) -> [Redeemer] -> [ExUnits]
forall a b. (a -> b) -> [a] -> [b]
map Redeemer -> ExUnits
Redeemer.executionUnits (Witnesses -> [Redeemer]
Witnesses.redeemers (EncodedWitnesses -> Witnesses
Witnesses.toWitnesses (SubTransaction -> EncodedWitnesses
Sub.witnesses SubTransaction
transaction)))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Int -> Integer
forall a. Integral a => a -> Integer
toInteger (ByteString -> Int
B.length (SubTransaction -> ByteString
Sub.encodeCbor SubTransaction
transaction)) Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
Parameters.parameterMaxTxSize Parameters
params)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Sub-transaction exceeds maximum transaction size"))
  (Output -> Either Error ()) -> [Output] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Maybe Word64 -> Output -> Either Error ()
checkOutputSize (Parameters -> Maybe Word64
Parameters.parameterMaxValueSize Parameters
params)) (Fields -> [Output]
Fields.fieldOutputs Fields
fields)
  case ([ExUnits]
units, Parameters -> Maybe ExUnits
Parameters.parameterMaxTxExUnits Parameters
params) of
    ([], Maybe ExUnits
_) -> () -> Either Error ()
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    ([ExUnits]
_, Maybe ExUnits
Nothing) -> Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Maximum transaction execution units are required")
    ([ExUnits]
_, Just ExUnits
cap) ->
      Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless
        ([Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ((ExUnits -> Integer) -> [ExUnits] -> [Integer]
forall a b. (a -> b) -> [a] -> [b]
map (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Word64 -> Integer) -> (ExUnits -> Word64) -> ExUnits -> Integer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ExUnits -> Word64
Ex.memory) [ExUnits]
units) Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (ExUnits -> Word64
Ex.memory ExUnits
cap) Bool -> Bool -> Bool
&& [Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ((ExUnits -> Integer) -> [ExUnits] -> [Integer]
forall a b. (a -> b) -> [a] -> [b]
map (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Word64 -> Integer) -> (ExUnits -> Word64) -> ExUnits -> Integer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ExUnits -> Word64
Ex.steps) [ExUnits]
units) Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (ExUnits -> Word64
Ex.steps ExUnits
cap))
        (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidEvaluationResult Text
"Sub-transaction exceeds maximum transaction execution units"))

checkOutputSize :: Maybe Word64 -> Output.Output -> Either Error ()
checkOutputSize :: Maybe Word64 -> Output -> Either Error ()
checkOutputSize Maybe Word64
Nothing Output
_ = () -> Either Error ()
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
checkOutputSize (Just Word64
limit) Output
output =
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Int -> Integer
forall a. Integral a => a -> Integer
toInteger (ByteString -> Int
B.length (Encoding -> ByteString
Cbor.encode Encoding
encoding)) Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
limit) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidBuildingRequest Text
"Sub-transaction output exceeds maximum value size"))
  where
    value :: Value
value = Output -> Value
Output.value Output
output
    coin :: Encoding
coin = Integer -> Encoding
E.encodeInteger (AssetId -> Value -> Integer
Value.quantity AssetId
Ada Value
value)
    assets :: [(AssetId, Integer)]
assets = Value -> [(AssetId, Integer)]
Value.toList (Value -> Value -> Value
Value.difference Value
value (Integer -> Value
Value.lovelace (AssetId -> Value -> Integer
Value.quantity AssetId
Ada Value
value)))
    encoding :: Encoding
encoding = if [(AssetId, Integer)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(AssetId, Integer)]
assets then Encoding
coin else Word -> Encoding
E.encodeListLen Word
2 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Encoding
coin Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Value -> Encoding
ValueCbor.encodeAssets Value
value

-- | Test-only malformed instruction boundary. The runtime still encloses every
-- native owner and callback, including expected errors and asynchronous unwind.
runUnchecked :: Config -> Plan -> ByteString -> IO (Either Error ByteString)
runUnchecked :: Config -> Plan -> ByteString -> IO (Either Error ByteString)
runUnchecked Config
config Plan
plan = Config -> Dispatch -> ByteString -> IO (Either Error ByteString)
runWithDispatch Config
config (Plan -> Dispatch
dispatch Plan
plan)

-- | Private dispatch injection for native callback-count and cleanup tests.
runWithDispatch :: Config -> Runtime.Dispatch -> ByteString -> IO (Either Error ByteString)
runWithDispatch :: Config -> Dispatch -> ByteString -> IO (Either Error ByteString)
runWithDispatch Config
config Dispatch
handler ByteString
instructions = Dispatch
-> (Runtime -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a.
Dispatch -> (Runtime -> IO (Either Error a)) -> IO (Either Error a)
Runtime.withRuntime Dispatch
handler ((Runtime -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Runtime -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Runtime
runtime ->
  Runtime
-> (Ptr Context -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a.
Runtime
-> (Ptr Context -> IO (Either Error a)) -> IO (Either Error a)
Runtime.withOperation Runtime
runtime ((Ptr Context -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr Context -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr Context
context ->
    ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a. ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a
Runtime.withBytes (Config -> ByteString
encodeConfig Config
config) ((Ptr Word8 -> CSize -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr Word8 -> CSize -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
configBytes CSize
configSize ->
      ByteString
-> (Ptr Word8 -> CSize -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a. ByteString -> (Ptr Word8 -> CSize -> IO a) -> IO a
Runtime.withBytes ByteString
instructions ((Ptr Word8 -> CSize -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr Word8 -> CSize -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr Word8
planBytes CSize
planSize ->
        (Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> IO NativeCode)
-> IO (Either Error ByteString)
withResult (Ptr Context
-> Ptr Word8
-> CSize
-> Ptr Word8
-> CSize
-> Ptr (Ptr Buffer)
-> Ptr (Ptr Buffer)
-> IO NativeCode
FFI.cBuild Ptr Context
context Ptr Word8
configBytes CSize
configSize Ptr Word8
planBytes CSize
planSize)

encodeConfig :: Config -> ByteString
encodeConfig :: Config -> ByteString
encodeConfig Config
config =
  Encoding -> ByteString
Cbor.encode
    ( Word -> Encoding
E.encodeListLen Word
5
        Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
E.encodeBytes (Parameters -> ByteString
Snapshot.encodeSnapshot (Config -> Parameters
parameters Config
config))
        Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word -> Encoding
E.encodeWord (case Config -> BodyNetwork
networkId Config
config of BodyNetwork
Testnet -> Word
0; BodyNetwork
Mainnet -> Word
1)
        Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word64 -> Encoding
E.encodeWord64 (SlotConfig -> Word64
Slots.zeroTime SlotConfig
slots)
        Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word64 -> Encoding
E.encodeWord64 (SlotConfig -> Word64
Slots.zeroSlot SlotConfig
slots)
        Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word64 -> Encoding
E.encodeWord64 (SlotConfig -> Word64
Slots.slotLength SlotConfig
slots)
    )
  where
    slots :: SlotConfig
slots = Config -> SlotConfig
slotConfig Config
config

-- Complete decoding, callback evaluation, payload encoding and native copying
-- happen inside the shared protected callback worker, forcing lazy failures.
dispatch :: Plan -> Runtime.Dispatch
dispatch :: Plan -> Dispatch
dispatch Plan
plan 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 sub-transaction deferred 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
Cbor.decodeAs Text -> Error
InvalidTransactionPlan Decoder s (Int, Transaction, [Utxo])
forall s. Decoder s (Int, Transaction, [Utxo])
parser ByteString
bytes
      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
"subTransaction.deferredIndex")) DeferredRedeemer -> Either Error DeferredRedeemer
forall a b. b -> Either a b
Right (Int -> Seq DeferredRedeemer -> Maybe DeferredRedeemer
forall a. Int -> Seq a -> Maybe a
Seq.lookup Int
index (Plan -> Seq DeferredRedeemer
Common.deferredRedeemers (Plan -> Plan
Plan.toPlan Plan
plan)))
      let canonical :: [Utxo]
canonical = (Utxo -> Input) -> [Utxo] -> [Utxo]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn Utxo -> Input
Utxo.input [Utxo]
inputs
          references :: [Input]
references = [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))))
      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]
canonical [Input] -> [Input] -> Bool
forall a. Eq a => a -> a -> Bool
== [Input]
references Bool -> Bool -> Bool
&& Body -> Word64
Body.fee (EncodedBody -> Body
Body.toBody (Transaction -> EncodedBody
Tx.body Transaction
transaction)) Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
== Word64
0) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"subTransaction.deferredInputs"))
      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]
canonical
  where
    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
Cbor.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
Cbor.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]
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))

-- Initialize and bracket both transferred buffer obligations before calling C.
withResult :: (Ptr (Ptr Raw.Buffer) -> Ptr (Ptr Raw.Buffer) -> IO Status.NativeCode) -> IO (Either Error ByteString)
withResult :: (Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> IO NativeCode)
-> IO (Either Error ByteString)
withResult Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> IO NativeCode
call = (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr (Ptr Buffer) -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr (Ptr Buffer)
output -> (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca ((Ptr (Ptr Buffer) -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (Ptr (Ptr Buffer) -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \Ptr (Ptr Buffer)
diagnostic ->
  IO ()
-> (() -> IO ())
-> (() -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b c. IO a -> (a -> IO b) -> (a -> IO c) -> IO c
bracket
    (Ptr (Ptr Buffer) -> Ptr Buffer -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke Ptr (Ptr Buffer)
output Ptr Buffer
forall a. Ptr a
nullPtr IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Ptr (Ptr Buffer) -> Ptr Buffer -> IO ()
forall a. Storable a => Ptr a -> a -> IO ()
poke Ptr (Ptr Buffer)
diagnostic Ptr Buffer
forall a. Ptr a
nullPtr)
    (\() -> Ptr (Ptr Buffer) -> IO ()
Raw.cBufferRelease Ptr (Ptr Buffer)
output IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Ptr (Ptr Buffer) -> IO ()
Raw.cBufferRelease Ptr (Ptr Buffer)
diagnostic)
    ((() -> IO (Either Error ByteString))
 -> IO (Either Error ByteString))
-> (() -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. (a -> b) -> a -> b
$ \() -> do
      NativeCode
status <- Ptr (Ptr Buffer) -> Ptr (Ptr Buffer) -> IO NativeCode
call Ptr (Ptr Buffer)
output Ptr (Ptr Buffer)
diagnostic
      if NativeCode
status NativeCode -> NativeCode -> Bool
forall a. Eq a => a -> a -> Bool
== NativeCode
Status.success
        then Ptr (Ptr Buffer) -> IO (Ptr Buffer)
forall a. Storable a => Ptr a -> IO a
peek Ptr (Ptr Buffer)
output IO (Ptr Buffer)
-> (Ptr Buffer -> IO (Either Error ByteString))
-> IO (Either Error ByteString)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Text -> Ptr Buffer -> IO (Either Error ByteString)
Runtime.copyBuffer Text
"subTransaction.build"
        else do
          Ptr Buffer
pointer <- Ptr (Ptr Buffer) -> IO (Ptr Buffer)
forall a. Storable a => Ptr a -> IO a
peek Ptr (Ptr Buffer)
diagnostic
          if Ptr Buffer
pointer Ptr Buffer -> Ptr Buffer -> Bool
forall a. Eq a => a -> a -> Bool
== Ptr Buffer
forall a. Ptr a
nullPtr
            then do
              Either Error ()
checked <- Text -> NativeCode -> IO (Either Error ())
Runtime.checkStatus Text
"subTransaction.build" NativeCode
status
              Either Error ByteString -> IO (Either Error ByteString)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either Error ()
checked Either Error ()
-> Either Error ByteString -> Either Error ByteString
forall a b. Either Error a -> Either Error b -> Either Error b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Text -> Error
NativeContractViolation Text
"subTransaction.status"))
            else do
              Either Error ByteString
copied <- Text -> Ptr Buffer -> IO (Either Error ByteString)
Runtime.copyBuffer Text
"subTransaction.diagnostic" Ptr Buffer
pointer
              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
$ case Either Error ByteString
copied of
                Left Error
failure -> Error -> Either Error ByteString
forall a b. a -> Either a b
Left Error
failure
                Right ByteString
bytes -> Error -> Either Error ByteString
forall a b. a -> Either a b
Left (Text -> ErrorCode -> Text -> Error
NativeError Text
"subTransaction.build" (Integer -> ErrorCode
Code.fromNumber (NativeCode -> Integer
forall a. Integral a => a -> Integer
toInteger NativeCode
status)) (OnDecodeError -> ByteString -> Text
Text.decodeUtf8With (\String
_ Maybe Word8
_ -> Char -> Maybe Char
forall a. a -> Maybe a
Just Char
'\xfffd') ByteString
bytes))