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

-- | Owned composable builder instructions and preflight conflict checks.
module Cometa.Internal.TransactionPlan
  ( Plan,
    payTo,
    spend,
    spendWith,
    DeferredRedeemer,
    spendWithDeferredRedeemer,
    mintWithDeferredRedeemer,
    certificateWithDeferredRedeemer,
    withdrawWithDeferredRedeemer,
    deferredRedeemers,
    referenceInput,
    attachScript,
    mint,
    mintWithRedeemer,
    metadata,
    attachDatum,
    certificate,
    certificateWithRedeemer,
    withdraw,
    withdrawWithRedeemer,
    requireSigner,
    validFrom,
    validUntil,
    requireGuard,
    guardWithRedeemer,
    directDeposit,
    accountBalance,
    startingAccountBalance,
    donate,
    currentTreasuryValue,
    propose,
    proposeWithRedeemer,
    proposeWithDeferredRedeemer,
    vote,
    voteWithRedeemer,
    voteWithDeferredRedeemer,
    attachSubTransaction,
    subTransactions,
    requireTopLevelGuard,
    validateTopLevel,
    reservedInputs,
    outerResolvedInputs,
    encodePlan,
    validatePlan,
    resolvedInputs,
    spendingInputs,
    planOutputs,
    sourceExtras,
    sinkExtras,
    validitySlots,
    witnessCount,
    requiresEvaluation,
  )
where

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

import qualified Codec.CBOR.Encoding as E
import Cometa.Address.Reward (RewardAddress)
import qualified Cometa.Address.Reward as Reward
import Cometa.AssetId (AssetId (..))
import Cometa.AssetName (AssetName)
import qualified Cometa.AssetName as AssetName
import Cometa.Certificate (Certificate)
import qualified Cometa.Certificate as Certificate
import qualified Cometa.Certificate.Collection as Certificates
import Cometa.Credential (Credential, Guard, KeyHash, Payment, ScriptHash)
import qualified Cometa.Credential as Credential
import Cometa.Error (Error (..))
import Cometa.Governance.Action (Action)
import qualified Cometa.Governance.Action as Action
import Cometa.Governance.ActionId (ActionId)
import qualified Cometa.Governance.ActionId as ActionId
import Cometa.Governance.Anchor (Anchor)
import qualified Cometa.Governance.Proposal as Proposal
import Cometa.Governance.Voting (Voter, VotingProcedure)
import qualified Cometa.Governance.Voting as Voting
import qualified Cometa.Internal.TransactionCbor as C
import Cometa.Metadata (Metadatum)
import qualified Cometa.Metadata as Metadata
import Cometa.PlutusData (EncodedPlutusData)
import qualified Cometa.PlutusData as Data
import Cometa.PolicyId (PolicyId)
import qualified Cometa.PolicyId as Policy
import qualified Cometa.Protocol.Parameters as Parameters
import Cometa.Script (Script)
import qualified Cometa.Script as Script
import qualified Cometa.Script.Native as NativeScript
import qualified Cometa.Script.Plutus as Plutus
import Cometa.SubTransaction (SubTransaction)
import qualified Cometa.SubTransaction as Sub
import qualified Cometa.SubTransaction.Body as SubBody
import Cometa.Transaction (Transaction)
import Cometa.Transaction.Fields (BalanceInterval (..))
import qualified Cometa.Transaction.Fields as Fields
import qualified Cometa.Transaction.Input
import Cometa.Transaction.Output (Output)
import qualified Cometa.Transaction.Output as Output
import Cometa.Transaction.Utxo (Utxo)
import qualified Cometa.Transaction.Utxo as Utxo
import qualified Cometa.Transaction.Witnesses as Witnesses
import qualified Cometa.Value as Value
import Control.Monad (unless, when)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import Data.Foldable (toList)
import Data.Int (Int64)
import Data.Maybe (catMaybes, fromMaybe, isJust)
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import Data.Word (Word64)

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

-- | Compute an argument from the balanced draft and its selected spending inputs
-- in canonical order. The callback may run on every balancing iteration. It must
-- be pure and deterministic; return an explicit error to abort the build. Values
-- are ordinary owned snapshots and may be inspected without resource scopes.
type DeferredRedeemer = Transaction -> [Utxo] -> Either Error EncodedPlutusData

data Argument = Immediate EncodedPlutusData | Deferred Int deriving (Argument -> Argument -> Bool
(Argument -> Argument -> Bool)
-> (Argument -> Argument -> Bool) -> Eq Argument
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Argument -> Argument -> Bool
== :: Argument -> Argument -> Bool
$c/= :: Argument -> Argument -> Bool
/= :: Argument -> Argument -> Bool
Eq, Int -> Argument -> ShowS
[Argument] -> ShowS
Argument -> String
(Int -> Argument -> ShowS)
-> (Argument -> String) -> ([Argument] -> ShowS) -> Show Argument
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Argument -> ShowS
showsPrec :: Int -> Argument -> ShowS
$cshow :: Argument -> String
show :: Argument -> String
$cshowList :: [Argument] -> ShowS
showList :: [Argument] -> ShowS
Show)

data Operation
  = Pay Output
  | Spend Utxo (Maybe Argument) (Maybe EncodedPlutusData)
  | Reference Utxo
  | Script Script
  | Mint AssetId Int64 (Maybe Argument)
  | Metadata Word64 Metadatum
  | Datum EncodedPlutusData
  | Certificate Certificate (Maybe Argument)
  | Withdraw RewardAddress Word64 (Maybe Argument)
  | Signer (KeyHash Payment)
  | From Word64
  | Until Word64
  | Guard (Credential Guard) (Maybe EncodedPlutusData)
  | DirectDeposit RewardAddress Word64
  | AccountBalance RewardAddress BalanceInterval
  | StartingBalance RewardAddress BalanceInterval
  | Donation Word64
  | TreasuryValue Word64
  | Propose RewardAddress Action Anchor (Maybe Argument)
  | Vote Voter ActionId VotingProcedure (Maybe Argument)
  | Sub SubTransaction [Utxo]
  | TopLevelGuard (Credential Guard) (Maybe EncodedPlutusData)
  deriving (Operation -> Operation -> Bool
(Operation -> Operation -> Bool)
-> (Operation -> Operation -> Bool) -> Eq Operation
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: Operation -> Operation -> Bool
== :: Operation -> Operation -> Bool
$c/= :: Operation -> Operation -> Bool
/= :: Operation -> Operation -> Bool
Eq, Int -> Operation -> ShowS
[Operation] -> ShowS
Operation -> String
(Int -> Operation -> ShowS)
-> (Operation -> String)
-> ([Operation] -> ShowS)
-> Show Operation
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> Operation -> ShowS
showsPrec :: Int -> Operation -> ShowS
$cshow :: Operation -> String
show :: Operation -> String
$cshowList :: [Operation] -> ShowS
showList :: [Operation] -> ShowS
Show)

-- | Ordered immutable instructions. Composition preserves output order and
-- combines requirements; conflicts are reported by the single build boundary.
-- Function values have no structural equality or printable representation.
-- Plan intentionally has neither Eq nor Show; its monoid laws concern behavior.
data Plan = Plan (Seq.Seq Operation) (Seq.Seq DeferredRedeemer)

instance Semigroup Plan where
  Plan Seq Operation
a Seq DeferredRedeemer
callbacksA <> :: Plan -> Plan -> Plan
<> Plan Seq Operation
b Seq DeferredRedeemer
callbacksB =
    Seq Operation -> Seq DeferredRedeemer -> Plan
Plan (Seq Operation
a Seq Operation -> Seq Operation -> Seq Operation
forall a. Semigroup a => a -> a -> a
<> (Operation -> Operation) -> Seq Operation -> Seq Operation
forall a b. (a -> b) -> Seq a -> Seq b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (Int -> Operation -> Operation
shiftCallbacks (Seq DeferredRedeemer -> Int
forall a. Seq a -> Int
Seq.length Seq DeferredRedeemer
callbacksA)) Seq Operation
b) (Seq DeferredRedeemer
callbacksA Seq DeferredRedeemer
-> Seq DeferredRedeemer -> Seq DeferredRedeemer
forall a. Semigroup a => a -> a -> a
<> Seq DeferredRedeemer
callbacksB)

instance Monoid Plan where
  mempty :: Plan
mempty = Seq Operation -> Seq DeferredRedeemer -> Plan
Plan Seq Operation
forall a. Seq a
Seq.empty Seq DeferredRedeemer
forall a. Seq a
Seq.empty

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

one :: Operation -> Plan
one :: Operation -> Plan
one Operation
op = Seq Operation -> Seq DeferredRedeemer -> Plan
Plan (Operation -> Seq Operation
forall a. a -> Seq a
Seq.singleton Operation
op) Seq DeferredRedeemer
forall a. Seq a
Seq.empty

-- | Append a payment output; minimum Ada is checked when building.
payTo :: Output -> Plan
payTo :: Output -> Plan
payTo = Operation -> Plan
one (Operation -> Plan) -> (Output -> Operation) -> Output -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Output -> Operation
Pay

-- | Spend a key-controlled resolved output without script arguments.
spend :: Utxo -> Plan
spend :: Utxo -> Plan
spend Utxo
u = Utxo -> Maybe EncodedPlutusData -> Maybe EncodedPlutusData -> Plan
spendWith Utxo
u Maybe EncodedPlutusData
forall a. Maybe a
Nothing Maybe EncodedPlutusData
forall a. Maybe a
Nothing

-- | Spend a resolved output with optional redeemer argument followed by optional
-- datum witness. Inline datums do not need a separate datum witness.
spendWith :: Utxo -> Maybe EncodedPlutusData -> Maybe EncodedPlutusData -> Plan
spendWith :: Utxo -> Maybe EncodedPlutusData -> Maybe EncodedPlutusData -> Plan
spendWith Utxo
u Maybe EncodedPlutusData
r = Operation -> Plan
one (Operation -> Plan)
-> (Maybe EncodedPlutusData -> Operation)
-> Maybe EncodedPlutusData
-> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Utxo -> Maybe Argument -> Maybe EncodedPlutusData -> Operation
Spend Utxo
u (EncodedPlutusData -> Argument
Immediate (EncodedPlutusData -> Argument)
-> Maybe EncodedPlutusData -> Maybe Argument
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe EncodedPlutusData
r)

-- | Resolve a reference input without consuming its value.
referenceInput :: Utxo -> Plan
referenceInput :: Utxo -> Plan
referenceInput = Operation -> Plan
one (Operation -> Plan) -> (Utxo -> Operation) -> Utxo -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Utxo -> Operation
Reference

-- | Attach a native or Plutus script witness. Repeated attachments of the same
-- language and script bytes contribute one witness, ordered by the first
-- attachment. Different Plutus versions remain distinct.
attachScript :: Script -> Plan
attachScript :: Script -> Plan
attachScript = Operation -> Plan
one (Operation -> Plan) -> (Script -> Operation) -> Script -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Script -> Operation
Script

-- | Mint positive or burn negative token units under a native policy. Ada and
-- overflowing combined quantities are rejected when building.
mint :: AssetId -> Int64 -> Plan
mint :: AssetId -> Int64 -> Plan
mint AssetId
a Int64
n = Operation -> Plan
one (AssetId -> Int64 -> Maybe Argument -> Operation
Mint AssetId
a Int64
n Maybe Argument
forall a. Maybe a
Nothing)

-- | Mint or burn units under a Plutus policy using its redeemer argument.
mintWithRedeemer :: AssetId -> Int64 -> EncodedPlutusData -> Plan
mintWithRedeemer :: AssetId -> Int64 -> EncodedPlutusData -> Plan
mintWithRedeemer AssetId
a Int64
n = Operation -> Plan
one (Operation -> Plan)
-> (EncodedPlutusData -> Operation) -> EncodedPlutusData -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. AssetId -> Int64 -> Maybe Argument -> Operation
Mint AssetId
a Int64
n (Maybe Argument -> Operation)
-> (EncodedPlutusData -> Maybe Argument)
-> EncodedPlutusData
-> Operation
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Argument -> Maybe Argument
forall a. a -> Maybe a
Just (Argument -> Maybe Argument)
-> (EncodedPlutusData -> Argument)
-> EncodedPlutusData
-> Maybe Argument
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedPlutusData -> Argument
Immediate

-- | Require metadata under a label. Conflicting values fail when building.
metadata :: Word64 -> Metadatum -> Plan
metadata :: Word64 -> Metadatum -> Plan
metadata Word64
label = Operation -> Plan
one (Operation -> Plan)
-> (Metadatum -> Operation) -> Metadatum -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word64 -> Metadatum -> Operation
Metadata Word64
label

-- | Attach a datum witness. Repeated exact CBOR encodings contribute one
-- witness, including data supplied to spending inputs. First occurrence order
-- is retained; different encodings remain distinct because their hashes differ.
attachDatum :: EncodedPlutusData -> Plan
attachDatum :: EncodedPlutusData -> Plan
attachDatum = Operation -> Plan
one (Operation -> Plan)
-> (EncodedPlutusData -> Operation) -> EncodedPlutusData -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedPlutusData -> Operation
Datum

-- | Append a certificate without a script argument.
certificate :: Certificate -> Plan
certificate :: Certificate -> Plan
certificate Certificate
c = Operation -> Plan
one (Certificate -> Maybe Argument -> Operation
Certificate Certificate
c Maybe Argument
forall a. Maybe a
Nothing)

-- | Append a certificate authorized by the supplied Plutus argument.
certificateWithRedeemer :: Certificate -> EncodedPlutusData -> Plan
certificateWithRedeemer :: Certificate -> EncodedPlutusData -> Plan
certificateWithRedeemer Certificate
c = Operation -> Plan
one (Operation -> Plan)
-> (EncodedPlutusData -> Operation) -> EncodedPlutusData -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Certificate -> Maybe Argument -> Operation
Certificate Certificate
c (Maybe Argument -> Operation)
-> (EncodedPlutusData -> Maybe Argument)
-> EncodedPlutusData
-> Operation
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Argument -> Maybe Argument
forall a. a -> Maybe a
Just (Argument -> Maybe Argument)
-> (EncodedPlutusData -> Argument)
-> EncodedPlutusData
-> Maybe Argument
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedPlutusData -> Argument
Immediate

-- | Withdraw lovelace from a key-controlled reward account. Amounts above Int64
-- are rejected when building.
withdraw :: RewardAddress -> Word64 -> Plan
withdraw :: RewardAddress -> Word64 -> Plan
withdraw RewardAddress
a Word64
n = Operation -> Plan
one (RewardAddress -> Word64 -> Maybe Argument -> Operation
Withdraw RewardAddress
a Word64
n Maybe Argument
forall a. Maybe a
Nothing)

-- | Withdraw lovelace from a script reward account using its Plutus argument.
withdrawWithRedeemer :: RewardAddress -> Word64 -> EncodedPlutusData -> Plan
withdrawWithRedeemer :: RewardAddress -> Word64 -> EncodedPlutusData -> Plan
withdrawWithRedeemer RewardAddress
a Word64
n = Operation -> Plan
one (Operation -> Plan)
-> (EncodedPlutusData -> Operation) -> EncodedPlutusData -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RewardAddress -> Word64 -> Maybe Argument -> Operation
Withdraw RewardAddress
a Word64
n (Maybe Argument -> Operation)
-> (EncodedPlutusData -> Maybe Argument)
-> EncodedPlutusData
-> Operation
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Argument -> Maybe Argument
forall a. a -> Maybe a
Just (Argument -> Maybe Argument)
-> (EncodedPlutusData -> Argument)
-> EncodedPlutusData
-> Maybe Argument
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedPlutusData -> Argument
Immediate

-- | Require a payment key hash to sign the completed transaction.
requireSigner :: KeyHash Payment -> Plan
requireSigner :: KeyHash Payment -> Plan
requireSigner = Operation -> Plan
one (Operation -> Plan)
-> (KeyHash Payment -> Operation) -> KeyHash Payment -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. KeyHash Payment -> Operation
Signer

-- | Inclusive lower validity slot. Composition takes the greatest lower bound.
validFrom :: Word64 -> Plan
validFrom :: Word64 -> Plan
validFrom = Operation -> Plan
one (Operation -> Plan) -> (Word64 -> Operation) -> Word64 -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word64 -> Operation
From

-- | Exclusive upper validity slot. Composition takes the least upper bound.
validUntil :: Word64 -> Plan
validUntil :: Word64 -> Plan
validUntil = Operation -> Plan
one (Operation -> Plan) -> (Word64 -> Operation) -> Word64 -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word64 -> Operation
Until

validatePlan :: Plan -> Either Error ()
validatePlan :: Plan -> Either Error ()
validatePlan (Plan Seq Operation
instructions Seq DeferredRedeemer
callbacks) = do
  let ops :: [Operation]
ops = Seq Operation -> [Operation]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq Operation
instructions
      inputs :: [(Input, (Utxo, Maybe Argument, Maybe EncodedPlutusData))]
inputs = [(Utxo -> Input
Utxo.input Utxo
u, (Utxo
u, Maybe Argument
r, Maybe EncodedPlutusData
d)) | Spend Utxo
u Maybe Argument
r Maybe EncodedPlutusData
d <- [Operation]
ops]
      refs :: [(Input, Utxo)]
refs = [(Utxo -> Input
Utxo.input Utxo
u, Utxo
u) | Reference Utxo
u <- [Operation]
ops]
      metas :: [(Word64, Metadatum)]
metas = [(Word64
k, Metadatum
v) | Metadata Word64
k Metadatum
v <- [Operation]
ops]
      withdrawals :: [(RewardAddress, (Word64, Maybe Argument))]
withdrawals = [(RewardAddress
a, (Word64
n, Maybe Argument
r)) | Withdraw RewardAddress
a Word64
n Maybe Argument
r <- [Operation]
ops]
      certificates :: [(Certificate, Maybe Argument)]
certificates = [(Certificate
c, Maybe Argument
r) | Certificate Certificate
c Maybe Argument
r <- [Operation]
ops]
      mints :: [(PolicyId, Maybe Argument)]
mints = [(PolicyId
p, Maybe Argument
r) | Mint (Native PolicyId
p AssetName
_) Int64
_ Maybe Argument
r <- [Operation]
ops]
      lows :: [Word64]
lows = [Word64
n | From Word64
n <- [Operation]
ops]
      highs :: [Word64]
highs = [Word64
n | Until Word64
n <- [Operation]
ops]
  Text
-> [(Input, (Utxo, Maybe Argument, Maybe EncodedPlutusData))]
-> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting requirements for one spending input" [(Input, (Utxo, Maybe Argument, Maybe EncodedPlutusData))]
inputs
  Text -> [(Input, Utxo)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting reference input snapshots" [(Input, Utxo)]
refs
  Text -> [(Input, Utxo)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting resolved input snapshots" [(Utxo -> Input
Utxo.input Utxo
u, Utxo
u) | Utxo
u <- Plan -> [Utxo]
resolvedInputs (Seq Operation -> Seq DeferredRedeemer -> Plan
Plan Seq Operation
instructions Seq DeferredRedeemer
callbacks)]
  Text -> [(Word64, Metadatum)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting metadata label" [(Word64, Metadatum)]
metas
  Text
-> [(RewardAddress, (Word64, Maybe Argument))] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting reward withdrawal" [(RewardAddress, (Word64, Maybe Argument))]
withdrawals
  Text -> [(PolicyId, Maybe Argument)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting minting policy redeemers" [(PolicyId, Maybe Argument)]
mints
  Text -> [(Certificate, Maybe Argument)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting certificate redeemers" [(Certificate, Maybe Argument)]
certificates
  Text
-> [(Credential Guard, Maybe EncodedPlutusData)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting required top-level guard arguments" [(Credential Guard
g, Maybe EncodedPlutusData
r) | TopLevelGuard Credential Guard
g Maybe EncodedPlutusData
r <- [Operation]
ops]
  Text
-> [(Credential Guard, Maybe EncodedPlutusData)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting guard redeemers" [(Credential Guard
g, Maybe EncodedPlutusData
r) | Guard Credential Guard
g Maybe EncodedPlutusData
r <- [Operation]
ops]
  Text -> [(RewardAddress, BalanceInterval)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting account balance intervals" [(RewardAddress
a, BalanceInterval
i) | AccountBalance RewardAddress
a BalanceInterval
i <- [Operation]
ops]
  Text -> [(RewardAddress, BalanceInterval)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting starting account balance intervals" [(RewardAddress
a, BalanceInterval
i) | StartingBalance RewardAddress
a BalanceInterval
i <- [Operation]
ops]
  Text -> [((Voter, ActionId), VotingProcedure)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting votes for one action" [((Voter
v, ActionId
a), VotingProcedure
p) | Vote Voter
v ActionId
a VotingProcedure
p Maybe Argument
_ <- [Operation]
ops]
  Text -> [(Voter, Maybe Argument)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting voter redeemers" [(Voter
v, Maybe Argument
r) | Vote Voter
v ActionId
_ VotingProcedure
_ Maybe Argument
r <- [Operation]
ops]
  Text -> [((), Word64)] -> Either Error ()
forall {t :: * -> *} {a} {a}.
(Foldable t, Eq a, Eq a) =>
Text -> t (a, a) -> Either Error ()
consistent Text
"Conflicting current treasury values" [((), Word64
amount) | TreasuryValue Word64
amount <- [Operation]
ops]
  let proposals :: [ByteString]
proposals = [Proposal -> ByteString
Proposal.encodeCbor (Word64 -> RewardAddress -> Action -> Anchor -> Proposal
Proposal.Proposal Word64
0 RewardAddress
account Action
action Anchor
anchor) | Propose RewardAddress
account Action
action Anchor
anchor Maybe Argument
_ <- [Operation]
ops]
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([ByteString] -> Bool
forall {a}. Eq a => [a] -> Bool
distinct [ByteString]
proposals) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
"Duplicate governance proposal"))
  (Operation -> Either Error ()) -> [Operation] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ Operation -> Either Error ()
validateProposal [Operation]
ops
  let donation :: Integer
donation = [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 Word64
n | Donation Word64
n <- [Operation]
ops]
      deposits :: [(RewardAddress, Integer)]
deposits = [(RewardAddress
a, [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 Word64
n | DirectDeposit RewardAddress
a' Word64
n <- [Operation]
ops, RewardAddress
a RewardAddress -> RewardAddress -> Bool
forall a. Eq a => a -> a -> Bool
== RewardAddress
a']) | DirectDeposit RewardAddress
a Word64
_ <- [Operation]
ops]
      subSpent :: [Input]
subSpent = ((SubTransaction, [Utxo]) -> [Input])
-> [(SubTransaction, [Utxo])] -> [Input]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Fields -> [Input]
Fields.fieldInputs (Fields -> [Input])
-> ((SubTransaction, [Utxo]) -> Fields)
-> (SubTransaction, [Utxo])
-> [Input]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> Fields
subFields (SubTransaction -> Fields)
-> ((SubTransaction, [Utxo]) -> SubTransaction)
-> (SubTransaction, [Utxo])
-> Fields
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (SubTransaction, [Utxo]) -> SubTransaction
forall a b. (a, b) -> a
fst) (Plan -> [(SubTransaction, [Utxo])]
subTransactions (Seq Operation -> Seq DeferredRedeemer -> Plan
Plan Seq Operation
instructions Seq DeferredRedeemer
callbacks))
      outerSpent :: [Input]
outerSpent = [Utxo -> Input
Utxo.input Utxo
u | Spend Utxo
u Maybe Argument
_ Maybe EncodedPlutusData
_ <- [Operation]
ops]
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Integer
donation 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
InvalidTransactionPlan Text
"Combined donation exceeds signed native bounds"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when
    (((RewardAddress, Integer) -> Bool)
-> [(RewardAddress, Integer)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(RewardAddress
_, Integer
n) -> Integer
n 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)) [(RewardAddress, Integer)]
deposits Bool -> Bool -> Bool
|| (Operation -> Bool) -> [Operation] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\case DirectDeposit RewardAddress
_ Word64
0 -> Bool
True; Operation
_ -> Bool
False) [Operation]
ops)
    (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
"Direct deposits must be positive and fit signed native bounds"))
  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 [Input]
subSpent) 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]
subSpent Bool -> Bool -> Bool
&& (Input -> Bool) -> [Input] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (Input -> [Input] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Input]
subSpent) [Input]
outerSpent)
    (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
"Spending inputs overlap between transaction levels"))
  ((SubTransaction, [Utxo]) -> Either Error ())
-> [(SubTransaction, [Utxo])] -> Either Error ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (SubTransaction, [Utxo]) -> Either Error ()
validateSub (Plan -> [(SubTransaction, [Utxo])]
subTransactions (Seq Operation -> Seq DeferredRedeemer -> Plan
Plan Seq Operation
instructions Seq DeferredRedeemer
callbacks))
  let totals :: [(AssetId, Integer)]
totals = [(AssetId
asset, [Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger Int64
amount | Mint AssetId
asset' Int64
amount Maybe Argument
_ <- [Operation]
ops, AssetId
asset AssetId -> AssetId -> Bool
forall a. Eq a => a -> a -> Bool
== AssetId
asset']) | Mint AssetId
asset Int64
_ Maybe Argument
_ <- [Operation]
ops]
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when
    (((AssetId, Integer) -> Bool) -> [(AssetId, Integer)] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (\(AssetId
_, Integer
amount) -> 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
minBound :: Int64) 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)) [(AssetId, Integer)]
totals)
    (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
"Combined mint quantity exceeds signed native bounds"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ((Operation -> Bool) -> [Operation] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Operation -> Bool
isAdaMint [Operation]
ops) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
"Ada cannot be minted"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when ((Operation -> Bool) -> [Operation] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Operation -> Bool
excessiveWithdrawal [Operation]
ops) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
"Withdrawal exceeds signed native amount"))
  Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([Word64] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Word64]
lows Bool -> Bool -> Bool
|| [Word64] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Word64]
highs Bool -> Bool -> Bool
|| [Word64] -> Word64
forall a. Ord a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
maximum [Word64]
lows Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
< [Word64] -> Word64
forall a. Ord a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
minimum [Word64]
highs) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
"Empty validity interval"))
  where
    distinct :: [a] -> Bool
distinct [] = Bool
True
    distinct (a
value : [a]
rest) = a
value a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [a]
rest Bool -> Bool -> Bool
&& [a] -> Bool
distinct [a]
rest
    validateProposal :: Operation -> Either Error ()
validateProposal (Propose RewardAddress
_ Action
action Anchor
_ (Just Argument
_)) =
      Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (Action -> Bool
hasPolicy Action
action) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
"A proposing redeemer requires a guardrails policy"))
    validateProposal Operation
_ = () -> Either Error ()
forall a. a -> Either Error a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    consistent :: Text -> t (a, a) -> Either Error ()
consistent Text
message t (a, a)
pairs = Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless (((a, a) -> Bool) -> t (a, a) -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (\(a
k, a
v) -> ((a, a) -> Bool) -> t (a, a) -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (\(a
k', a
v') -> a
k a -> a -> Bool
forall a. Eq a => a -> a -> Bool
/= a
k' Bool -> Bool -> Bool
|| a
v a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
v') t (a, a)
pairs) t (a, a)
pairs) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
message))
    isAdaMint :: Operation -> Bool
isAdaMint (Mint AssetId
Ada Int64
_ Maybe Argument
_) = Bool
True
    isAdaMint Operation
_ = Bool
False
    excessiveWithdrawal :: Operation -> Bool
excessiveWithdrawal (Withdraw RewardAddress
_ Word64
n Maybe Argument
_) = Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
n 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)
    excessiveWithdrawal Operation
_ = Bool
False

encodePlan :: Word64 -> Plan -> ByteString
encodePlan :: Word64 -> Plan -> ByteString
encodePlan Word64
deposit Plan
plan = Encoding -> ByteString
C.encode (Word -> Encoding
E.encodeListLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Operation] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Operation]
ops)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Operation -> Encoding) -> [Operation] -> 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 -> Operation -> Encoding
encodeOperation Word64
deposit) [Operation]
ops)
  where
    ops :: [Operation]
ops = Plan -> [Operation]
normalizedOperations Plan
plan

normalizedOperations :: Plan -> [Operation]
normalizedOperations :: Plan -> [Operation]
normalizedOperations (Plan Seq Operation
instructions Seq DeferredRedeemer
_) = [Operation]
ops
  where
    original :: [Operation]
original = Seq Operation -> [Operation]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq Operation
instructions
    ops :: [Operation]
ops = Set EncodedPlutusData -> [Operation] -> [Operation]
uniqueDatums Set EncodedPlutusData
forall a. Set a
Set.empty [Operation]
requirements
    requirements :: [Operation]
requirements =
      [Operation] -> [Operation]
normalizeMints ([Operation] -> [Operation]
deduplicate [Operation
op | Operation
op <- [Operation]
original, case Operation
op of From Word64
_ -> Bool
False; Until Word64
_ -> Bool
False; Donation Word64
_ -> Bool
False; Operation
_ -> Bool
True])
        [Operation] -> [Operation] -> [Operation]
forall a. Semigroup a => a -> a -> a
<> [Word64 -> Operation
Donation (Integer -> Word64
forall a. Num a => Integer -> a
fromInteger ([Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Integer]
ns)) | let ns :: [Integer]
ns = [Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
n | Donation Word64
n <- [Operation]
original], Bool -> Bool
not ([Integer] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Integer]
ns)]
        [Operation] -> [Operation] -> [Operation]
forall a. Semigroup a => a -> a -> a
<> [Word64 -> Operation
From ([Word64] -> Word64
forall a. Ord a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
maximum [Word64]
ns) | let ns :: [Word64]
ns = [Word64
n | From Word64
n <- [Operation]
original], Bool -> Bool
not ([Word64] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Word64]
ns)]
        [Operation] -> [Operation] -> [Operation]
forall a. Semigroup a => a -> a -> a
<> [Word64 -> Operation
Until ([Word64] -> Word64
forall a. Ord a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Ord a) => t a -> a
minimum [Word64]
ns) | let ns :: [Word64]
ns = [Word64
n | Until Word64
n <- [Operation]
original], Bool -> Bool
not ([Word64] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Word64]
ns)]

    -- Both native add_datum and add_input append to the same witness set.
    -- Keep datum hash preimages exactly; stripping a repeated input argument
    -- only avoids its second global insertion, not any input or callback.
    uniqueDatums :: Set EncodedPlutusData -> [Operation] -> [Operation]
uniqueDatums Set EncodedPlutusData
_ [] = []
    uniqueDatums Set EncodedPlutusData
seen (Datum EncodedPlutusData
datum : [Operation]
rest)
      | EncodedPlutusData
datum EncodedPlutusData -> Set EncodedPlutusData -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set EncodedPlutusData
seen = Set EncodedPlutusData -> [Operation] -> [Operation]
uniqueDatums Set EncodedPlutusData
seen [Operation]
rest
      | Bool
otherwise = EncodedPlutusData -> Operation
Datum EncodedPlutusData
datum Operation -> [Operation] -> [Operation]
forall a. a -> [a] -> [a]
: Set EncodedPlutusData -> [Operation] -> [Operation]
uniqueDatums (EncodedPlutusData -> Set EncodedPlutusData -> Set EncodedPlutusData
forall a. Ord a => a -> Set a -> Set a
Set.insert EncodedPlutusData
datum Set EncodedPlutusData
seen) [Operation]
rest
    uniqueDatums Set EncodedPlutusData
seen (Spend Utxo
input Maybe Argument
argument (Just EncodedPlutusData
datum) : [Operation]
rest)
      | EncodedPlutusData
datum EncodedPlutusData -> Set EncodedPlutusData -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set EncodedPlutusData
seen = Utxo -> Maybe Argument -> Maybe EncodedPlutusData -> Operation
Spend Utxo
input Maybe Argument
argument Maybe EncodedPlutusData
forall a. Maybe a
Nothing Operation -> [Operation] -> [Operation]
forall a. a -> [a] -> [a]
: Set EncodedPlutusData -> [Operation] -> [Operation]
uniqueDatums Set EncodedPlutusData
seen [Operation]
rest
      | Bool
otherwise = Utxo -> Maybe Argument -> Maybe EncodedPlutusData -> Operation
Spend Utxo
input Maybe Argument
argument (EncodedPlutusData -> Maybe EncodedPlutusData
forall a. a -> Maybe a
Just EncodedPlutusData
datum) Operation -> [Operation] -> [Operation]
forall a. a -> [a] -> [a]
: Set EncodedPlutusData -> [Operation] -> [Operation]
uniqueDatums (EncodedPlutusData -> Set EncodedPlutusData -> Set EncodedPlutusData
forall a. Ord a => a -> Set a -> Set a
Set.insert EncodedPlutusData
datum Set EncodedPlutusData
seen) [Operation]
rest
    uniqueDatums Set EncodedPlutusData
seen (Operation
operation : [Operation]
rest) = Operation
operation Operation -> [Operation] -> [Operation]
forall a. a -> [a] -> [a]
: Set EncodedPlutusData -> [Operation] -> [Operation]
uniqueDatums Set EncodedPlutusData
seen [Operation]
rest

    deduplicate :: [Operation] -> [Operation]
deduplicate [] = []
    deduplicate (Operation
op : [Operation]
rest) = Operation
op Operation -> [Operation] -> [Operation]
forall a. a -> [a] -> [a]
: [Operation] -> [Operation]
deduplicate (if Operation -> Bool
idempotent Operation
op then (Operation -> Bool) -> [Operation] -> [Operation]
forall a. (a -> Bool) -> [a] -> [a]
filter (Bool -> Bool
not (Bool -> Bool) -> (Operation -> Bool) -> Operation -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Operation -> Operation -> Bool
sameAttachment Operation
op) [Operation]
rest else [Operation]
rest)
    -- Native builder_witnesses.c (eadb95cd3ca7f711c203d7f2f4ee21c150d4d7f1)
    -- appends scripts without enforcing witness-set uniqueness. Match the exact
    -- hash preimage here; Plutus outer bytestring framing is not script identity.
    sameAttachment :: Operation -> Operation -> Bool
sameAttachment (Script Script
left) (Script Script
right) = Script -> (Int, ByteString)
scriptIdentity Script
left (Int, ByteString) -> (Int, ByteString) -> Bool
forall a. Eq a => a -> a -> Bool
== Script -> (Int, ByteString)
scriptIdentity Script
right
    sameAttachment Operation
left Operation
right = Operation
left Operation -> Operation -> Bool
forall a. Eq a => a -> a -> Bool
== Operation
right
    scriptIdentity :: Script -> (Int, ByteString)
scriptIdentity (Script.Native NativeScript
script) = (Int
0, NativeScript -> ByteString
NativeScript.encodeCbor NativeScript
script)
    scriptIdentity (Script.Plutus PlutusScript
script) = (Version -> Int
forall a. Enum a => a -> Int
fromEnum (PlutusScript -> Version
Plutus.version PlutusScript
script) Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
1, PlutusScript -> ByteString
Plutus.toBytes PlutusScript
script)
    idempotent :: Operation -> Bool
idempotent Operation
op = case Operation
op of
      Script {} -> Bool
True
      Spend {} -> Bool
True
      Reference {} -> Bool
True
      Metadata {} -> Bool
True
      Withdraw {} -> Bool
True
      Signer {} -> Bool
True
      Guard {} -> Bool
True
      TopLevelGuard {} -> Bool
True
      AccountBalance {} -> Bool
True
      StartingBalance {} -> Bool
True
      TreasuryValue {} -> Bool
True
      Vote {} -> Bool
True
      Operation
_ -> Bool
False

    normalizeMints :: [Operation] -> [Operation]
normalizeMints [] = []
    normalizeMints (Mint AssetId
asset Int64
_ Maybe Argument
redeemer : [Operation]
rest) =
      let amount :: Integer
amount = [Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger Int64
n | Mint AssetId
a Int64
n Maybe Argument
_ <- [Operation]
original, AssetId
a AssetId -> AssetId -> Bool
forall a. Eq a => a -> a -> Bool
== AssetId
asset]
          remaining :: [Operation]
remaining = (Operation -> Bool) -> [Operation] -> [Operation]
forall a. (a -> Bool) -> [a] -> [a]
filter (\case Mint AssetId
a Int64
_ Maybe Argument
_ -> AssetId
a AssetId -> AssetId -> Bool
forall a. Eq a => a -> a -> Bool
/= AssetId
asset; Operation
_ -> Bool
True) [Operation]
rest
       in [AssetId -> Int64 -> Maybe Argument -> Operation
Mint AssetId
asset (Integer -> Int64
forall a. Num a => Integer -> a
fromInteger Integer
amount) Maybe Argument
redeemer | Integer
amount Integer -> Integer -> Bool
forall a. Eq a => a -> a -> Bool
/= Integer
0] [Operation] -> [Operation] -> [Operation]
forall a. Semigroup a => a -> a -> a
<> [Operation] -> [Operation]
normalizeMints [Operation]
remaining
    normalizeMints (Operation
op : [Operation]
rest) = Operation
op Operation -> [Operation] -> [Operation]
forall a. a -> [a] -> [a]
: [Operation] -> [Operation]
normalizeMints [Operation]
rest

requiresEvaluation :: Plan -> Bool
requiresEvaluation :: Plan -> Bool
requiresEvaluation = (Operation -> Bool) -> [Operation] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any Operation -> Bool
needs ([Operation] -> Bool) -> (Plan -> [Operation]) -> Plan -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Plan -> [Operation]
normalizedOperations
  where
    needs :: Operation -> Bool
needs (Spend Utxo
_ (Just Argument
_) Maybe EncodedPlutusData
_) = Bool
True
    needs (Guard Credential Guard
_ (Just EncodedPlutusData
_)) = Bool
True
    needs (Vote Voter
_ ActionId
_ VotingProcedure
_ (Just Argument
_)) = Bool
True
    needs (Propose RewardAddress
_ Action
action Anchor
_ Maybe Argument
_) = Action -> Bool
hasPolicy Action
action
    needs (Sub SubTransaction
transaction [Utxo]
_) = Bool -> Bool
not ([Redeemer] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (Witnesses -> [Redeemer]
Witnesses.redeemers (EncodedWitnesses -> Witnesses
Witnesses.toWitnesses (SubTransaction -> EncodedWitnesses
Sub.witnesses SubTransaction
transaction))))
    needs (Mint AssetId
_ Int64
_ (Just Argument
_)) = Bool
True
    needs (Certificate Certificate
_ (Just Argument
_)) = Bool
True
    needs (Withdraw RewardAddress
_ Word64
_ (Just Argument
_)) = Bool
True
    needs Operation
_ = Bool
False

validitySlots :: Plan -> [Word64]
validitySlots :: Plan -> [Word64]
validitySlots (Plan Seq Operation
instructions Seq DeferredRedeemer
_) = (Operation -> [Word64]) -> [Operation] -> [Word64]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Operation -> [Word64]
slots (Seq Operation -> [Operation]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq Operation
instructions)
  where
    slots :: Operation -> [Word64]
slots (From Word64
n) = [Word64
n]
    slots (Until Word64
n) = [Word64
n]
    slots (Sub SubTransaction
transaction [Utxo]
_) =
      let fields :: Fields
fields = SubTransaction -> Fields
subFields SubTransaction
transaction
       in [Maybe Word64] -> [Word64]
forall a. [Maybe a] -> [a]
catMaybes [Fields -> Maybe Word64
Fields.fieldInvalidBefore Fields
fields, Fields -> Maybe Word64
Fields.fieldInvalidAfter Fields
fields]
    slots Operation
_ = []

-- Native unique_signers does not inspect keys embedded in native scripts;
-- applications provide those additional witnesses through extraSigners.
witnessCount :: Plan -> Integer
witnessCount :: Plan -> Integer
witnessCount = [Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum ([Integer] -> Integer) -> (Plan -> [Integer]) -> Plan -> Integer
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Operation -> Integer) -> [Operation] -> [Integer]
forall a b. (a -> b) -> [a] -> [b]
map Operation -> Integer
count ([Operation] -> [Integer])
-> (Plan -> [Operation]) -> Plan -> [Integer]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Plan -> [Operation]
normalizedOperations
  where
    count :: Operation -> Integer
count (Signer KeyHash Payment
_) = Integer
1
    count (Guard (Credential.KeyCredential KeyHash Guard
_) Maybe EncodedPlutusData
_) = Integer
1
    count Vote {} = Integer
1
    count Withdraw {} = Integer
1
    count (Certificate Certificate
c Maybe Argument
_) = Integer
1 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Int -> Integer
forall a. Integral a => a -> Integer
toInteger (ByteString -> Int
B.length (Certificate -> ByteString
Certificate.encodeCbor Certificate
c)) Integer -> Integer -> Integer
forall a. Integral a => a -> a -> a
`div` Integer
28
    count Operation
_ = Integer
0

spendingInputs :: Plan -> [Utxo]
spendingInputs :: Plan -> [Utxo]
spendingInputs (Plan Seq Operation
instructions Seq DeferredRedeemer
_) = [Utxo
u | Spend Utxo
u Maybe Argument
_ Maybe EncodedPlutusData
_ <- Seq Operation -> [Operation]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq Operation
instructions]

planOutputs :: Plan -> [Output]
planOutputs :: Plan -> [Output]
planOutputs (Plan Seq Operation
instructions Seq DeferredRedeemer
_) = [Output
o | Pay Output
o <- Seq Operation -> [Operation]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq Operation
instructions]

sourceExtras :: Parameters.Parameters -> Plan -> Value.Value
sourceExtras :: Parameters -> Plan -> Value
sourceExtras Parameters
params = (Operation -> Value) -> [Operation] -> Value
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap Operation -> Value
source ([Operation] -> Value) -> (Plan -> [Operation]) -> Plan -> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Plan -> [Operation]
normalizedOperations
  where
    source :: Operation -> Value
source (Mint AssetId
a Int64
n Maybe Argument
_) | Int64
n Int64 -> Int64 -> Bool
forall a. Ord a => a -> a -> Bool
> Int64
0 = AssetId -> Integer -> Value
Value.singleton AssetId
a (Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger Int64
n)
    source (Withdraw RewardAddress
_ Word64
n Maybe Argument
_) = Integer -> Value
Value.lovelace (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
n)
    source (Certificate Certificate
cert Maybe Argument
_) =
      Integer -> Value
Value.lovelace
        ( case Certificate
cert of
            Certificate.StakeDeregistration Credential Stake
_ -> Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
Parameters.parameterKeyDeposit Parameters
params)
            Certificate.Unregistration Credential Stake
_ Word64
amount -> Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
amount
            Certificate.UnregisterDRep Credential DRep
_ Word64
amount -> Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
amount
            Certificate
_ -> Integer
0
        )
    source (Sub SubTransaction
transaction [Utxo]
resolved) =
      let fields :: Fields
fields = SubTransaction -> Fields
subFields SubTransaction
transaction
          spent :: [Input]
spent = Fields -> [Input]
Fields.fieldInputs Fields
fields
          funding :: Value
funding = (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
u | Utxo
u <- [Utxo]
resolved, 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]
spent]
       in Value
funding Value -> Value -> Value
forall a. Semigroup a => a -> a -> a
<> (Operation -> Value) -> [Operation] -> Value
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap Operation -> Value
source (Fields -> [Operation]
operationsFromFields Fields
fields)
    source Operation
_ = Value
forall a. Monoid a => a
mempty

sinkExtras :: Parameters.Parameters -> Plan -> Value.Value
sinkExtras :: Parameters -> Plan -> Value
sinkExtras Parameters
params = (Operation -> Value) -> [Operation] -> Value
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap Operation -> Value
sink ([Operation] -> Value) -> (Plan -> [Operation]) -> Plan -> Value
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Plan -> [Operation]
normalizedOperations
  where
    sink :: Operation -> Value
sink (Mint AssetId
a Int64
n Maybe Argument
_) | Int64
n Int64 -> Int64 -> Bool
forall a. Ord a => a -> a -> Bool
< Int64
0 = AssetId -> Integer -> Value
Value.singleton AssetId
a (Integer -> Integer
forall a. Num a => a -> a
negate (Int64 -> Integer
forall a. Integral a => a -> Integer
toInteger Int64
n))
    sink (Certificate Certificate
cert Maybe Argument
_) =
      Integer -> Value
Value.lovelace
        ( case Certificate
cert of
            Certificate.StakeRegistration Credential Stake
_ -> Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
Parameters.parameterKeyDeposit Parameters
params)
            Certificate.PoolRegistration PoolParameters
_ -> Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger (Parameters -> Word64
Parameters.parameterPoolDeposit Parameters
params)
            Certificate.Registration Credential Stake
_ Word64
amount -> Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
amount
            Certificate.StakeRegistrationDelegation Credential Stake
_ KeyHash StakePool
_ Word64
amount -> Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
amount
            Certificate.VoteRegistrationDelegation Credential Stake
_ DRep
_ Word64
amount -> Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
amount
            Certificate.StakeVoteRegistrationDelegation Credential Stake
_ KeyHash StakePool
_ DRep
_ Word64
amount -> Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
amount
            Certificate.RegisterDRep Credential DRep
_ Word64
amount Maybe Anchor
_ -> Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
amount
            Certificate
_ -> Integer
0
        )
    sink (DirectDeposit RewardAddress
_ Word64
n) = Integer -> Value
Value.lovelace (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
n)
    sink (Donation Word64
n) = Integer -> Value
Value.lovelace (Word64 -> Integer
forall a. Integral a => a -> Integer
toInteger Word64
n)
    sink Propose {} = Integer -> Value
Value.lovelace (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)))
    sink (Sub SubTransaction
transaction [Utxo]
_) =
      let fields :: Fields
fields = SubTransaction -> Fields
subFields SubTransaction
transaction
          deposits :: Integer
deposits = [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 (Proposal -> Word64
Proposal.proposalDeposit Proposal
proposal) | Just Proposals
proposals <- [Fields -> Maybe Proposals
Fields.fieldProposalProcedures Fields
fields], Proposal
proposal <- Proposals -> [Proposal]
Proposal.toList Proposals
proposals]
       in (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 (Fields -> [Output]
Fields.fieldOutputs Fields
fields) Value -> Value -> Value
forall a. Semigroup a => a -> a -> a
<> Integer -> Value
Value.lovelace Integer
deposits Value -> Value -> Value
forall a. Semigroup a => a -> a -> a
<> (Operation -> Value) -> [Operation] -> Value
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap Operation -> Value
sink (Fields -> [Operation]
operationsFromFields Fields
fields)
    sink Operation
_ = Value
forall a. Monoid a => a
mempty

resolvedInputs :: Plan -> [Utxo]
resolvedInputs :: Plan -> [Utxo]
resolvedInputs (Plan Seq Operation
instructions Seq DeferredRedeemer
_) = (Operation -> [Utxo]) -> [Operation] -> [Utxo]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Operation -> [Utxo]
resolved (Seq Operation -> [Operation]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq Operation
instructions)
  where
    resolved :: Operation -> [Utxo]
resolved (Spend Utxo
u Maybe Argument
_ Maybe EncodedPlutusData
_) = [Utxo
u]
    resolved (Reference Utxo
u) = [Utxo
u]
    resolved (Sub SubTransaction
_ [Utxo]
values) = [Utxo]
values
    resolved Operation
_ = []

encodeOperation :: Word64 -> Operation -> E.Encoding
encodeOperation :: Word64 -> Operation -> Encoding
encodeOperation Word64
deposit Operation
operation = case Operation
operation of
  Pay Output
o -> Word -> [Encoding] -> Encoding
fields Word
0 [ByteString -> Encoding
bytes (Output -> ByteString
Output.encodeCbor Output
o)]
  Spend Utxo
u (Just (Deferred Int
index)) Maybe EncodedPlutusData
d -> Word -> [Encoding] -> Encoding
fields Word
12 [ByteString -> Encoding
bytes (Utxo -> ByteString
Utxo.encodeCbor Utxo
u), Int -> Encoding
E.encodeInt Int
index, Maybe EncodedPlutusData -> Encoding
optional Maybe EncodedPlutusData
d]
  Spend Utxo
u Maybe Argument
r Maybe EncodedPlutusData
d -> Word -> [Encoding] -> Encoding
fields Word
1 [ByteString -> Encoding
bytes (Utxo -> ByteString
Utxo.encodeCbor Utxo
u), Maybe Argument -> Encoding
argument Maybe Argument
r, Maybe EncodedPlutusData -> Encoding
optional Maybe EncodedPlutusData
d]
  Reference Utxo
u -> Word -> [Encoding] -> Encoding
fields Word
2 [ByteString -> Encoding
bytes (Utxo -> ByteString
Utxo.encodeCbor Utxo
u)]
  Script Script
s -> Word -> [Encoding] -> Encoding
fields Word
3 [ByteString -> Encoding
bytes (Script -> ByteString
Script.encodeCbor Script
s)]
  Mint AssetId
Ada Int64
_ Maybe Argument
_ -> Word -> [Encoding] -> Encoding
fields Word
4 []
  Mint (Native PolicyId
p AssetName
n) Int64
amount (Just (Deferred Int
index)) -> Word -> [Encoding] -> Encoding
fields Word
13 [ByteString -> Encoding
bytes (PolicyId -> ByteString
Policy.toBytes PolicyId
p), ByteString -> Encoding
bytes (AssetName -> ByteString
AssetName.toBytes AssetName
n), Int64 -> Encoding
E.encodeInt64 Int64
amount, Int -> Encoding
E.encodeInt Int
index]
  Mint (Native PolicyId
p AssetName
n) Int64
amount Maybe Argument
r -> Word -> [Encoding] -> Encoding
fields Word
4 [ByteString -> Encoding
bytes (PolicyId -> ByteString
Policy.toBytes PolicyId
p), ByteString -> Encoding
bytes (AssetName -> ByteString
AssetName.toBytes AssetName
n), Int64 -> Encoding
E.encodeInt64 Int64
amount, Maybe Argument -> Encoding
argument Maybe Argument
r]
  Metadata Word64
label Metadatum
value -> Word -> [Encoding] -> Encoding
fields Word
5 [Word64 -> Encoding
E.encodeWord64 Word64
label, ByteString -> Encoding
bytes (Metadatum -> ByteString
Metadata.encodeMetadatumCbor Metadatum
value)]
  Datum EncodedPlutusData
d -> Word -> [Encoding] -> Encoding
fields Word
6 [ByteString -> Encoding
bytes (EncodedPlutusData -> ByteString
Data.toCbor EncodedPlutusData
d)]
  Certificate Certificate
c (Just (Deferred Int
index)) -> Word -> [Encoding] -> Encoding
fields Word
14 [ByteString -> Encoding
bytes (Certificate -> ByteString
Certificate.encodeCbor Certificate
c), Int -> Encoding
E.encodeInt Int
index]
  Certificate Certificate
c Maybe Argument
r -> Word -> [Encoding] -> Encoding
fields Word
7 [ByteString -> Encoding
bytes (Certificate -> ByteString
Certificate.encodeCbor Certificate
c), Maybe Argument -> Encoding
argument Maybe Argument
r]
  Withdraw RewardAddress
a Word64
amount (Just (Deferred Int
index)) -> Word -> [Encoding] -> Encoding
fields Word
15 [ByteString -> Encoding
bytes (RewardAddress -> ByteString
Reward.toBytes RewardAddress
a), Word64 -> Encoding
E.encodeWord64 Word64
amount, Int -> Encoding
E.encodeInt Int
index]
  Withdraw RewardAddress
a Word64
amount Maybe Argument
r -> Word -> [Encoding] -> Encoding
fields Word
8 [ByteString -> Encoding
bytes (RewardAddress -> ByteString
Reward.toBytes RewardAddress
a), Word64 -> Encoding
E.encodeWord64 Word64
amount, Maybe Argument -> Encoding
argument Maybe Argument
r]
  Signer KeyHash Payment
hash -> Word -> [Encoding] -> Encoding
fields Word
9 [ByteString -> Encoding
bytes (KeyHash Payment -> ByteString
forall purpose. KeyHash purpose -> ByteString
Credential.keyHashBytes KeyHash Payment
hash)]
  From Word64
n -> Word -> [Encoding] -> Encoding
fields Word
10 [Word64 -> Encoding
E.encodeWord64 Word64
n]
  Until Word64
n -> Word -> [Encoding] -> Encoding
fields Word
11 [Word64 -> Encoding
E.encodeWord64 Word64
n]
  Guard Credential Guard
credential Maybe EncodedPlutusData
redeemer -> Word -> [Encoding] -> Encoding
fields Word
16 [ByteString -> Encoding
bytes (Credential Guard -> ByteString
forall authority. Credential authority -> ByteString
credentialBytes Credential Guard
credential), Maybe EncodedPlutusData -> Encoding
optional Maybe EncodedPlutusData
redeemer]
  DirectDeposit RewardAddress
address Word64
amount -> Word -> [Encoding] -> Encoding
fields Word
18 [ByteString -> Encoding
bytes (RewardAddress -> ByteString
Reward.toBytes RewardAddress
address), Word64 -> Encoding
E.encodeWord64 Word64
amount]
  AccountBalance RewardAddress
address BalanceInterval
interval -> Word -> [Encoding] -> Encoding
fields Word
19 [ByteString -> Encoding
bytes (RewardAddress -> ByteString
Reward.toBytes RewardAddress
address), ByteString -> Encoding
bytes (BalanceInterval -> ByteString
intervalBytes BalanceInterval
interval)]
  StartingBalance RewardAddress
address BalanceInterval
interval -> Word -> [Encoding] -> Encoding
fields Word
20 [ByteString -> Encoding
bytes (RewardAddress -> ByteString
Reward.toBytes RewardAddress
address), ByteString -> Encoding
bytes (BalanceInterval -> ByteString
intervalBytes BalanceInterval
interval)]
  Donation Word64
amount -> Word -> [Encoding] -> Encoding
fields Word
21 [Word64 -> Encoding
E.encodeWord64 Word64
amount]
  TreasuryValue Word64
amount -> Word -> [Encoding] -> Encoding
fields Word
27 [Word64 -> Encoding
E.encodeWord64 Word64
amount]
  Propose RewardAddress
address Action
action Anchor
anchor (Just (Deferred Int
index)) -> Word -> [Encoding] -> Encoding
fields Word
28 [ByteString -> Encoding
bytes (Proposal -> ByteString
Proposal.encodeCbor (Word64 -> RewardAddress -> Action -> Anchor -> Proposal
Proposal.Proposal Word64
deposit RewardAddress
address Action
action Anchor
anchor)), Int -> Encoding
E.encodeInt Int
index]
  Propose RewardAddress
address Action
action Anchor
anchor Maybe Argument
redeemer -> Word -> [Encoding] -> Encoding
fields Word
22 [ByteString -> Encoding
bytes (Proposal -> ByteString
Proposal.encodeCbor (Word64 -> RewardAddress -> Action -> Anchor -> Proposal
Proposal.Proposal Word64
deposit RewardAddress
address Action
action Anchor
anchor)), Maybe Argument -> Encoding
argument Maybe Argument
redeemer]
  Vote Voter
voter ActionId
action VotingProcedure
procedure (Just (Deferred Int
index)) -> Word -> [Encoding] -> Encoding
fields Word
24 [ByteString -> Encoding
bytes (Voter -> ByteString
Voting.encodeVoter Voter
voter), ByteString -> Encoding
bytes (ActionId -> ByteString
ActionId.encodeCbor ActionId
action), ByteString -> Encoding
bytes (VotingProcedure -> ByteString
Voting.encodeProcedure VotingProcedure
procedure), Int -> Encoding
E.encodeInt Int
index]
  Vote Voter
voter ActionId
action VotingProcedure
procedure Maybe Argument
redeemer -> Word -> [Encoding] -> Encoding
fields Word
23 [ByteString -> Encoding
bytes (Voter -> ByteString
Voting.encodeVoter Voter
voter), ByteString -> Encoding
bytes (ActionId -> ByteString
ActionId.encodeCbor ActionId
action), ByteString -> Encoding
bytes (VotingProcedure -> ByteString
Voting.encodeProcedure VotingProcedure
procedure), Maybe Argument -> Encoding
argument Maybe Argument
redeemer]
  TopLevelGuard Credential Guard
credential Maybe EncodedPlutusData
datum -> Word -> [Encoding] -> Encoding
fields Word
26 [ByteString -> Encoding
bytes (Credential Guard -> ByteString
forall authority. Credential authority -> ByteString
credentialBytes Credential Guard
credential), Maybe EncodedPlutusData -> Encoding
optional Maybe EncodedPlutusData
datum]
  Sub SubTransaction
transaction [Utxo]
resolved -> Word -> [Encoding] -> Encoding
fields Word
25 [ByteString -> Encoding
bytes (SubTransaction -> ByteString
Sub.encodeCbor SubTransaction
transaction), Word -> Encoding
E.encodeListLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Utxo] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Utxo]
resolved)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> (Utxo -> Encoding) -> [Utxo] -> Encoding
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (ByteString -> Encoding
C.raw (ByteString -> Encoding)
-> (Utxo -> ByteString) -> Utxo -> Encoding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Utxo -> ByteString
Utxo.encodeCbor) [Utxo]
resolved]
  where
    fields :: Word -> [Encoding] -> Encoding
fields Word
tag [Encoding]
xs = Word -> Encoding
E.encodeListLen (Int -> Word
forall a b. (Integral a, Num b) => a -> b
fromIntegral (Int
1 Int -> Int -> Int
forall a. Num a => a -> a -> a
+ [Encoding] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Encoding]
xs)) Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Word -> Encoding
E.encodeWord Word
tag Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> [Encoding] -> Encoding
forall a. Monoid a => [a] -> a
mconcat [Encoding]
xs
    bytes :: ByteString -> Encoding
bytes = ByteString -> Encoding
E.encodeBytes
    argument :: Maybe Argument -> Encoding
argument Maybe Argument
Nothing = ByteString -> Encoding
bytes ByteString
forall a. Monoid a => a
mempty
    argument (Just (Immediate EncodedPlutusData
d)) = ByteString -> Encoding
bytes (EncodedPlutusData -> ByteString
Data.toCbor EncodedPlutusData
d)
    argument (Just (Deferred Int
index)) = Int -> Encoding
E.encodeInt Int
index
    optional :: Maybe EncodedPlutusData -> Encoding
optional = Encoding
-> (EncodedPlutusData -> Encoding)
-> Maybe EncodedPlutusData
-> Encoding
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (ByteString -> Encoding
E.encodeBytes ByteString
forall a. Monoid a => a
mempty) (ByteString -> Encoding
bytes (ByteString -> Encoding)
-> (EncodedPlutusData -> ByteString)
-> EncodedPlutusData
-> Encoding
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedPlutusData -> ByteString
Data.toCbor)

-- | Spend a resolved script output using a late argument and optional datum
-- witness. Register each spending input once when using a deferred argument.
spendWithDeferredRedeemer :: Utxo -> DeferredRedeemer -> Maybe EncodedPlutusData -> Plan
spendWithDeferredRedeemer :: Utxo -> DeferredRedeemer -> Maybe EncodedPlutusData -> Plan
spendWithDeferredRedeemer Utxo
u DeferredRedeemer
callback Maybe EncodedPlutusData
datum = Operation -> DeferredRedeemer -> Plan
deferred (Utxo -> Maybe Argument -> Maybe EncodedPlutusData -> Operation
Spend Utxo
u (Argument -> Maybe Argument
forall a. a -> Maybe a
Just (Int -> Argument
Deferred Int
0)) Maybe EncodedPlutusData
datum) DeferredRedeemer
callback

-- | Mint or burn several assets under one policy using one late argument.
-- Quantities for repeated names are combined; zero totals are omitted. Empty
-- or entirely cancelled groups never call the callback. Register each policy
-- once; combining separate deferred groups for one policy fails at build.
mintWithDeferredRedeemer :: PolicyId -> [(AssetName, Int64)] -> DeferredRedeemer -> Plan
mintWithDeferredRedeemer :: PolicyId -> [(AssetName, Int64)] -> DeferredRedeemer -> Plan
mintWithDeferredRedeemer PolicyId
policy [(AssetName, Int64)]
assets DeferredRedeemer
callback =
  Seq Operation -> Seq DeferredRedeemer -> Plan
Plan
    ([Operation] -> Seq Operation
forall a. [a] -> Seq a
Seq.fromList [AssetId -> Int64 -> Maybe Argument -> Operation
Mint (PolicyId -> AssetName -> AssetId
Native PolicyId
policy AssetName
name) Int64
amount (Argument -> Maybe Argument
forall a. a -> Maybe a
Just (Int -> Argument
Deferred Int
0)) | (AssetName
name, Int64
amount) <- [(AssetName, Int64)]
assets])
    (DeferredRedeemer -> Seq DeferredRedeemer
forall a. a -> Seq a
Seq.singleton DeferredRedeemer
callback)

-- | Append a certificate authorized by a late Plutus argument.
certificateWithDeferredRedeemer :: Certificate -> DeferredRedeemer -> Plan
certificateWithDeferredRedeemer :: Certificate -> DeferredRedeemer -> Plan
certificateWithDeferredRedeemer Certificate
cert = Operation -> DeferredRedeemer -> Plan
deferred (Certificate -> Maybe Argument -> Operation
Certificate Certificate
cert (Argument -> Maybe Argument
forall a. a -> Maybe a
Just (Int -> Argument
Deferred Int
0)))

-- | Withdraw rewards using a late argument. Register each reward account once
-- when using a deferred argument.
withdrawWithDeferredRedeemer :: RewardAddress -> Word64 -> DeferredRedeemer -> Plan
withdrawWithDeferredRedeemer :: RewardAddress -> Word64 -> DeferredRedeemer -> Plan
withdrawWithDeferredRedeemer RewardAddress
address Word64
amount = Operation -> DeferredRedeemer -> Plan
deferred (RewardAddress -> Word64 -> Maybe Argument -> Operation
Withdraw RewardAddress
address Word64
amount (Argument -> Maybe Argument
forall a. a -> Maybe a
Just (Int -> Argument
Deferred Int
0)))

deferred :: Operation -> DeferredRedeemer -> Plan
deferred :: Operation -> DeferredRedeemer -> Plan
deferred Operation
operation DeferredRedeemer
callback = Seq Operation -> Seq DeferredRedeemer -> Plan
Plan (Operation -> Seq Operation
forall a. a -> Seq a
Seq.singleton Operation
operation) (DeferredRedeemer -> Seq DeferredRedeemer
forall a. a -> Seq a
Seq.singleton DeferredRedeemer
callback)

deferredRedeemers :: Plan -> Seq.Seq DeferredRedeemer
deferredRedeemers :: Plan -> Seq DeferredRedeemer
deferredRedeemers (Plan Seq Operation
_ Seq DeferredRedeemer
callbacks) = Seq DeferredRedeemer
callbacks

shiftCallbacks :: Int -> Operation -> Operation
shiftCallbacks :: Int -> Operation -> Operation
shiftCallbacks Int
offset Operation
operation = case Operation
operation of
  Spend Utxo
u Maybe Argument
argument Maybe EncodedPlutusData
datum -> Utxo -> Maybe Argument -> Maybe EncodedPlutusData -> Operation
Spend Utxo
u (Argument -> Argument
shift (Argument -> Argument) -> Maybe Argument -> Maybe Argument
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Argument
argument) Maybe EncodedPlutusData
datum
  Mint AssetId
asset Int64
amount Maybe Argument
argument -> AssetId -> Int64 -> Maybe Argument -> Operation
Mint AssetId
asset Int64
amount (Argument -> Argument
shift (Argument -> Argument) -> Maybe Argument -> Maybe Argument
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Argument
argument)
  Certificate Certificate
cert Maybe Argument
argument -> Certificate -> Maybe Argument -> Operation
Certificate Certificate
cert (Argument -> Argument
shift (Argument -> Argument) -> Maybe Argument -> Maybe Argument
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Argument
argument)
  Withdraw RewardAddress
address Word64
amount Maybe Argument
argument -> RewardAddress -> Word64 -> Maybe Argument -> Operation
Withdraw RewardAddress
address Word64
amount (Argument -> Argument
shift (Argument -> Argument) -> Maybe Argument -> Maybe Argument
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Argument
argument)
  Vote Voter
voter ActionId
action VotingProcedure
procedure Maybe Argument
argument -> Voter -> ActionId -> VotingProcedure -> Maybe Argument -> Operation
Vote Voter
voter ActionId
action VotingProcedure
procedure (Argument -> Argument
shift (Argument -> Argument) -> Maybe Argument -> Maybe Argument
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Argument
argument)
  Propose RewardAddress
address Action
action Anchor
anchor Maybe Argument
argument -> RewardAddress -> Action -> Anchor -> Maybe Argument -> Operation
Propose RewardAddress
address Action
action Anchor
anchor (Argument -> Argument
shift (Argument -> Argument) -> Maybe Argument -> Maybe Argument
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe Argument
argument)
  Operation
_ -> Operation
operation
  where
    shift :: Argument -> Argument
shift (Deferred Int
index) = Int -> Argument
Deferred (Int
index Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
offset)
    shift Argument
argument = Argument
argument

-- | Require a key or script guard. Key guards require signatures; script guards
-- require a supplied script. Identical requirements are idempotent.
requireGuard :: Credential Guard -> Plan
requireGuard :: Credential Guard -> Plan
requireGuard Credential Guard
credential = Operation -> Plan
one (Credential Guard -> Maybe EncodedPlutusData -> Operation
Guard Credential Guard
credential Maybe EncodedPlutusData
forall a. Maybe a
Nothing)

-- | Require a script guard with its guarding argument. Guard positions preserve
-- insertion order, including ordinary required signers. Supply a Plutus V4 script
-- for a top-level guard; attaching the script remains explicit.
guardWithRedeemer :: ScriptHash -> EncodedPlutusData -> Plan
guardWithRedeemer :: ScriptHash -> EncodedPlutusData -> Plan
guardWithRedeemer ScriptHash
hash EncodedPlutusData
argument = Operation -> Plan
one (Credential Guard -> Maybe EncodedPlutusData -> Operation
Guard (ScriptHash -> Credential Guard
forall purpose. ScriptHash -> Credential purpose
Credential.ScriptCredential ScriptHash
hash) (EncodedPlutusData -> Maybe EncodedPlutusData
forall a. a -> Maybe a
Just EncodedPlutusData
argument))

-- | Pay positive lovelace directly into a reward account. Repeated amounts add;
-- each amount and their total must fit the native signed 64-bit balance range.
directDeposit :: RewardAddress -> Word64 -> Plan
directDeposit :: RewardAddress -> Word64 -> Plan
directDeposit RewardAddress
account = Operation -> Plan
one (Operation -> Plan) -> (Word64 -> Operation) -> Word64 -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RewardAddress -> Word64 -> Operation
DirectDeposit RewardAddress
account

-- | Require the account balance when this transaction is applied. Identical
-- intervals compose idempotently; differing intervals fail at build time.
accountBalance :: RewardAddress -> BalanceInterval -> Plan
accountBalance :: RewardAddress -> BalanceInterval -> Plan
accountBalance RewardAddress
account = Operation -> Plan
one (Operation -> Plan)
-> (BalanceInterval -> Operation) -> BalanceInterval -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RewardAddress -> BalanceInterval -> Operation
AccountBalance RewardAddress
account

-- | Require the account balance before any subtransaction of the batch applies.
startingAccountBalance :: RewardAddress -> BalanceInterval -> Plan
startingAccountBalance :: RewardAddress -> BalanceInterval -> Plan
startingAccountBalance RewardAddress
account = Operation -> Plan
one (Operation -> Plan)
-> (BalanceInterval -> Operation) -> BalanceInterval -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RewardAddress -> BalanceInterval -> Operation
StartingBalance RewardAddress
account

-- | Contribute lovelace to the treasury. Amounts add under composition, including
-- explicit zero; the total must fit the native signed 64-bit balance range.
donate :: Word64 -> Plan
 = Operation -> Plan
one (Operation -> Plan) -> (Word64 -> Operation) -> Word64 -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word64 -> Operation
Donation

-- | Declare the current treasury balance in lovelace. This is a ledger-state
-- assertion, not a donation or a source of transaction funds. Repeating the same
-- value is idempotent; conflicting values fail when building. Zero is explicit.
currentTreasuryValue :: Word64 -> Plan
currentTreasuryValue :: Word64 -> Plan
currentTreasuryValue = Operation -> Plan
one (Operation -> Plan) -> (Word64 -> Operation) -> Word64 -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Word64 -> Operation
TreasuryValue

-- | Append a governance proposal using the configured protocol deposit. A
-- parameter-change or treasury-withdrawal action with a guardrails policy uses
-- the unit redeemer @Constr 0 []@. An action without a policy needs no redeemer.
-- Attach the policy script or resolve its reference input separately.
propose :: RewardAddress -> Action -> Anchor -> Plan
propose :: RewardAddress -> Action -> Anchor -> Plan
propose RewardAddress
address Action
action Anchor
anchor = Operation -> Plan
one (RewardAddress -> Action -> Anchor -> Maybe Argument -> Operation
Propose RewardAddress
address Action
action Anchor
anchor Maybe Argument
argument)
  where
    argument :: Maybe Argument
argument = if Action -> Bool
hasPolicy Action
action then Argument -> Maybe Argument
forall a. a -> Maybe a
Just (EncodedPlutusData -> Argument
Immediate (PlutusData -> EncodedPlutusData
Data.fromData (Word64 -> [PlutusData] -> PlutusData
Data.Constr Word64
0 []))) else Maybe Argument
forall a. Maybe a
Nothing

-- | Append a proposal with an explicit guardrails argument. The action must
-- name a policy; other actions fail when building. Proposal order determines
-- the proposing redeemer index. Duplicate proposals fail rather than gaining
-- a second index. The configured protocol snapshot supplies the deposit.
proposeWithRedeemer :: RewardAddress -> Action -> Anchor -> EncodedPlutusData -> Plan
proposeWithRedeemer :: RewardAddress -> Action -> Anchor -> EncodedPlutusData -> Plan
proposeWithRedeemer RewardAddress
address Action
action Anchor
anchor = Operation -> Plan
one (Operation -> Plan)
-> (EncodedPlutusData -> Operation) -> EncodedPlutusData -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. RewardAddress -> Action -> Anchor -> Maybe Argument -> Operation
Propose RewardAddress
address Action
action Anchor
anchor (Maybe Argument -> Operation)
-> (EncodedPlutusData -> Maybe Argument)
-> EncodedPlutusData
-> Operation
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Argument -> Maybe Argument
forall a. a -> Maybe a
Just (Argument -> Maybe Argument)
-> (EncodedPlutusData -> Argument)
-> EncodedPlutusData
-> Maybe Argument
forall b c a. (b -> c) -> (a -> b) -> a -> c
. EncodedPlutusData -> Argument
Immediate

-- | Append a proposal whose guardrails argument is computed from the balanced
-- draft. The action must name a policy. The callback sees the proposal with its
-- configured deposit and may run repeatedly as balancing converges.
proposeWithDeferredRedeemer :: RewardAddress -> Action -> Anchor -> DeferredRedeemer -> Plan
proposeWithDeferredRedeemer :: RewardAddress -> Action -> Anchor -> DeferredRedeemer -> Plan
proposeWithDeferredRedeemer RewardAddress
address Action
action Anchor
anchor = Operation -> DeferredRedeemer -> Plan
deferred (RewardAddress -> Action -> Anchor -> Maybe Argument -> Operation
Propose RewardAddress
address Action
action Anchor
anchor (Argument -> Maybe Argument
forall a. a -> Maybe a
Just (Int -> Argument
Deferred Int
0)))

hasPolicy :: Action -> Bool
hasPolicy :: Action -> Bool
hasPolicy (Action.ParameterChange Maybe ActionId
_ Update
_ Maybe ScriptHash
policy) = Maybe ScriptHash -> Bool
forall a. Maybe a -> Bool
isJust Maybe ScriptHash
policy
hasPolicy (Action.TreasuryWithdrawals Withdrawals
_ Maybe ScriptHash
policy) = Maybe ScriptHash -> Bool
forall a. Maybe a -> Bool
isJust Maybe ScriptHash
policy
hasPolicy Action
_ = Bool
False

-- | Cast a key-authorized vote. Identical voter/action instructions are
-- idempotent; conflicting choices fail when building.
vote :: Voter -> ActionId -> VotingProcedure -> Plan
vote :: Voter -> ActionId -> VotingProcedure -> Plan
vote Voter
voter ActionId
action VotingProcedure
procedure = Operation -> Plan
one (Voter -> ActionId -> VotingProcedure -> Maybe Argument -> Operation
Vote Voter
voter ActionId
action VotingProcedure
procedure Maybe Argument
forall a. Maybe a
Nothing)

-- | Cast several votes authorized by one voter and one immediate argument.
-- A voter has one voting redeemer across all of its governance actions.
voteWithRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> EncodedPlutusData -> Plan
voteWithRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> EncodedPlutusData -> Plan
voteWithRedeemer Voter
voter [(ActionId, VotingProcedure)]
votes EncodedPlutusData
argument = ((ActionId, VotingProcedure) -> Plan)
-> [(ActionId, VotingProcedure)] -> Plan
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (\(ActionId
action, VotingProcedure
procedure) -> Operation -> Plan
one (Voter -> ActionId -> VotingProcedure -> Maybe Argument -> Operation
Vote Voter
voter ActionId
action VotingProcedure
procedure (Argument -> Maybe Argument
forall a. a -> Maybe a
Just (EncodedPlutusData -> Argument
Immediate EncodedPlutusData
argument)))) [(ActionId, VotingProcedure)]
votes

-- | Cast several votes using one late argument for the voter. Empty groups do
-- not invoke the callback. Register each deferred voter once per plan.
voteWithDeferredRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> DeferredRedeemer -> Plan
voteWithDeferredRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> DeferredRedeemer -> Plan
voteWithDeferredRedeemer Voter
voter [(ActionId, VotingProcedure)]
votes DeferredRedeemer
callback =
  Seq Operation -> Seq DeferredRedeemer -> Plan
Plan ([Operation] -> Seq Operation
forall a. [a] -> Seq a
Seq.fromList [Voter -> ActionId -> VotingProcedure -> Maybe Argument -> Operation
Vote Voter
voter ActionId
action VotingProcedure
procedure (Argument -> Maybe Argument
forall a. a -> Maybe a
Just (Int -> Argument
Deferred Int
0)) | (ActionId
action, VotingProcedure
procedure) <- [(ActionId, VotingProcedure)]
votes]) (DeferredRedeemer -> Seq DeferredRedeemer
forall a. a -> Seq a
Seq.singleton DeferredRedeemer
callback)

-- | Carry an independently built subtransaction, retaining its exact bytes and
-- signatures. Supply every spending and reference input as a resolved snapshot.
-- Spending inputs of different transaction levels must be disjoint. The parent
-- funds the batch's net deficit and supplies the fee and collateral.
attachSubTransaction :: SubTransaction -> [Utxo] -> Plan
attachSubTransaction :: SubTransaction -> [Utxo] -> Plan
attachSubTransaction SubTransaction
transaction = Operation -> Plan
one (Operation -> Plan) -> ([Utxo] -> Operation) -> [Utxo] -> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SubTransaction -> [Utxo] -> Operation
Sub SubTransaction
transaction

subTransactions :: Plan -> [(SubTransaction, [Utxo])]
subTransactions :: Plan -> [(SubTransaction, [Utxo])]
subTransactions (Plan Seq Operation
operations Seq DeferredRedeemer
_) = [(SubTransaction
transaction, [Utxo]
resolved) | Sub SubTransaction
transaction [Utxo]
resolved <- Seq Operation -> [Operation]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq Operation
operations]

subFields :: SubTransaction -> Fields.Fields
subFields :: SubTransaction -> Fields
subFields = 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

validateSub :: (SubTransaction, [Utxo]) -> Either Error ()
validateSub :: (SubTransaction, [Utxo]) -> Either Error ()
validateSub (SubTransaction
transaction, [Utxo]
resolved) = do
  let fields :: Fields
fields = SubTransaction -> Fields
subFields SubTransaction
transaction
      expected :: [Input]
expected = 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)
      actual :: [Input]
actual = (Utxo -> Input) -> [Utxo] -> [Input]
forall a b. (a -> b) -> [a] -> [b]
map Utxo -> Input
Utxo.input [Utxo]
resolved
  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 -> [Input] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Input]
actual) [Input]
expected) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
"Unresolved subtransaction spending or reference input"))
  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 [Input]
actual) 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]
actual) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
"Duplicate subtransaction resolved input"))

operationsFromFields :: Fields.Fields -> [Operation]
operationsFromFields :: Fields -> [Operation]
operationsFromFields Fields
fields =
  (Output -> Operation) -> [Output] -> [Operation]
forall a b. (a -> b) -> [a] -> [b]
map Output -> Operation
Pay (Fields -> [Output]
Fields.fieldOutputs Fields
fields)
    [Operation] -> [Operation] -> [Operation]
forall a. Semigroup a => a -> a -> a
<> [AssetId -> Int64 -> Maybe Argument -> Operation
Mint AssetId
asset (Integer -> Int64
forall a. Num a => Integer -> a
fromInteger Integer
amount) Maybe Argument
forall a. Maybe a
Nothing | Just Mint
minted <- [Fields -> Maybe Mint
Fields.fieldMint Fields
fields], (AssetId
asset, Integer
amount) <- Value -> [(AssetId, Integer)]
Value.toList (Mint -> Value
Fields.mintValue Mint
minted)]
    [Operation] -> [Operation] -> [Operation]
forall a. Semigroup a => a -> a -> a
<> [RewardAddress -> Word64 -> Maybe Argument -> Operation
Withdraw RewardAddress
account Word64
amount Maybe Argument
forall a. Maybe a
Nothing | Just Entries RewardAddress Word64
entries <- [Fields -> Maybe (Entries RewardAddress Word64)
Fields.fieldWithdrawals Fields
fields], (RewardAddress
account, Word64
amount) <- Entries RewardAddress Word64 -> [(RewardAddress, Word64)]
forall key value. Entries key value -> [(key, value)]
Fields.entries Entries RewardAddress Word64
entries]
    [Operation] -> [Operation] -> [Operation]
forall a. Semigroup a => a -> a -> a
<> [Certificate -> Maybe Argument -> Operation
Certificate Certificate
cert Maybe Argument
forall a. Maybe a
Nothing | Just Certificates
certificates <- [Fields -> Maybe Certificates
Fields.fieldCertificates Fields
fields], Certificate
cert <- Certificates -> [Certificate]
Certificates.toList Certificates
certificates]
    [Operation] -> [Operation] -> [Operation]
forall a. Semigroup a => a -> a -> a
<> [RewardAddress -> Word64 -> Operation
DirectDeposit RewardAddress
account Word64
amount | Just Entries RewardAddress Word64
entries <- [Fields -> Maybe (Entries RewardAddress Word64)
Fields.fieldDirectDeposits Fields
fields], (RewardAddress
account, Word64
amount) <- Entries RewardAddress Word64 -> [(RewardAddress, Word64)]
forall key value. Entries key value -> [(key, value)]
Fields.entries Entries RewardAddress Word64
entries]
    [Operation] -> [Operation] -> [Operation]
forall a. Semigroup a => a -> a -> a
<> [Word64 -> Operation
Donation Word64
amount | Just Word64
amount <- [Fields -> Maybe Word64
Fields.fieldDonation Fields
fields]]

credentialBytes :: Credential authority -> ByteString
credentialBytes :: forall authority. Credential authority -> ByteString
credentialBytes Credential authority
credential =
  Encoding -> ByteString
C.encode (Encoding -> ByteString) -> Encoding -> ByteString
forall a b. (a -> b) -> a -> b
$
    Word -> Encoding
E.encodeListLen Word
2 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> case Credential authority
credential of
      Credential.KeyCredential KeyHash authority
hash -> Word -> Encoding
E.encodeWord Word
0 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
E.encodeBytes (KeyHash authority -> ByteString
forall purpose. KeyHash purpose -> ByteString
Credential.keyHashBytes KeyHash authority
hash)
      Credential.ScriptCredential ScriptHash
hash -> Word -> Encoding
E.encodeWord Word
1 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> ByteString -> Encoding
E.encodeBytes (ScriptHash -> ByteString
Credential.scriptHashBytes ScriptHash
hash)

intervalBytes :: BalanceInterval -> ByteString
intervalBytes :: BalanceInterval -> ByteString
intervalBytes BalanceInterval
interval = Encoding -> ByteString
C.encode (Encoding -> ByteString) -> Encoding -> ByteString
forall a b. (a -> b) -> a -> b
$ case BalanceInterval
interval of
  ExactBalance Word64
amount -> Word64 -> Encoding
E.encodeWord64 Word64
amount
  BalanceRange Maybe Word64
lower Maybe Word64
upper -> Word -> Encoding
E.encodeListLen Word
2 Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Encoding -> (Word64 -> Encoding) -> Maybe Word64 -> Encoding
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Encoding
E.encodeNull Word64 -> Encoding
E.encodeWord64 Maybe Word64
lower Encoding -> Encoding -> Encoding
forall a. Semigroup a => a -> a -> a
<> Encoding -> (Word64 -> Encoding) -> Maybe Word64 -> Encoding
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Encoding
E.encodeNull Word64 -> Encoding
E.encodeWord64 Maybe Word64
upper

requireTopLevelGuard :: Credential Guard -> Maybe EncodedPlutusData -> Plan
requireTopLevelGuard :: Credential Guard -> Maybe EncodedPlutusData -> Plan
requireTopLevelGuard Credential Guard
credential = Operation -> Plan
one (Operation -> Plan)
-> (Maybe EncodedPlutusData -> Operation)
-> Maybe EncodedPlutusData
-> Plan
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Credential Guard -> Maybe EncodedPlutusData -> Operation
TopLevelGuard Credential Guard
credential

validateTopLevel :: Plan -> Either Error ()
validateTopLevel :: Plan -> Either Error ()
validateTopLevel (Plan Seq Operation
operations Seq DeferredRedeemer
_) = Bool -> Either Error () -> Either Error ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ((Operation -> Bool) -> [Operation] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all Operation -> Bool
permitted (Seq Operation -> [Operation]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq Operation
operations)) (Error -> Either Error ()
forall a b. a -> Either a b
Left (Text -> Error
InvalidTransactionPlan Text
"Parent guard requirements belong to a subtransaction plan"))
  where
    permitted :: Operation -> Bool
permitted TopLevelGuard {} = Bool
False
    permitted Operation
_ = Bool
True

reservedInputs :: Plan -> [Cometa.Transaction.Input.Input]
reservedInputs :: Plan -> [Input]
reservedInputs Plan
plan = ((SubTransaction, [Utxo]) -> [Input])
-> [(SubTransaction, [Utxo])] -> [Input]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (SubTransaction, [Utxo]) -> [Input]
forall {b}. (SubTransaction, b) -> [Input]
references (Plan -> [(SubTransaction, [Utxo])]
subTransactions Plan
plan)
  where
    references :: (SubTransaction, b) -> [Input]
references (SubTransaction
transaction, b
_) = let fields :: Fields
fields = SubTransaction -> Fields
subFields SubTransaction
transaction in 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)

outerResolvedInputs :: Plan -> [Utxo]
outerResolvedInputs :: Plan -> [Utxo]
outerResolvedInputs (Plan Seq Operation
instructions Seq DeferredRedeemer
_) = (Operation -> [Utxo]) -> [Operation] -> [Utxo]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap Operation -> [Utxo]
resolved (Seq Operation -> [Operation]
forall a. Seq a -> [a]
forall (t :: * -> *) a. Foldable t => t a -> [a]
toList Seq Operation
instructions)
  where
    resolved :: Operation -> [Utxo]
resolved (Spend Utxo
input Maybe Argument
_ Maybe EncodedPlutusData
_) = [Utxo
input]
    resolved (Reference Utxo
input) = [Utxo
input]
    resolved Operation
_ = []