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

-- | Sub-transaction plans share validated instructions and callback indexing
-- with ordinary plans while exposing only the sub-transaction schema.
module Cometa.Internal.SubTransactionPlan
  ( Plan,
    DeferredRedeemer,
    payTo,
    spend,
    spendWith,
    spendWithDeferredRedeemer,
    referenceInput,
    attachScript,
    mint,
    mintWithRedeemer,
    mintWithDeferredRedeemer,
    metadata,
    attachDatum,
    certificate,
    certificateWithRedeemer,
    certificateWithDeferredRedeemer,
    withdraw,
    withdrawWithRedeemer,
    withdrawWithDeferredRedeemer,
    requireSigner,
    validFrom,
    validUntil,
    requireTopLevelGuard,
    requireGuard,
    guardWithRedeemer,
    directDeposit,
    accountBalance,
    donate,
    propose,
    proposeWithRedeemer,
    proposeWithDeferredRedeemer,
    vote,
    voteWithRedeemer,
    voteWithDeferredRedeemer,
    resolvedInputs,
    toPlan,
  )
where

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

import Cometa.Address.Reward (RewardAddress)
import Cometa.AssetId (AssetId)
import Cometa.AssetName (AssetName)
import Cometa.Certificate (Certificate)
import Cometa.Credential (Credential, Guard, KeyHash, Payment, ScriptHash)
import Cometa.Error (Error)
import Cometa.Governance.Action (Action)
import Cometa.Governance.ActionId (ActionId)
import Cometa.Governance.Anchor (Anchor)
import Cometa.Governance.Voting (Voter, VotingProcedure)
import qualified Cometa.Internal.TransactionPlan as Top
import Cometa.Metadata (Metadatum)
import Cometa.PlutusData (EncodedPlutusData)
import Cometa.PolicyId (PolicyId)
import Cometa.Script (Script)
import Cometa.Transaction (Transaction)
import Cometa.Transaction.Fields (BalanceInterval)
import Cometa.Transaction.Output (Output)
import Cometa.Transaction.Utxo (Utxo)
import qualified Cometa.Transaction.Utxo as Utxo
import Data.Int (Int64)
import qualified Data.Map.Strict as Map
import Data.Word (Word64)

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

-- | Ordered intent instructions. Composition combines mint quantities and
-- validity requirements, preserving outputs and certificate order. Conflicting
-- arguments or snapshots fail when building. Plans contain functions, so their
-- monoid laws concern behavior rather than structural equality.
newtype Plan = Plan Top.Plan

instance Semigroup Plan where
  Plan Plan
left <> :: Plan -> Plan -> Plan
<> Plan Plan
right = Plan -> Plan
Plan (Plan
left Plan -> Plan -> Plan
forall a. Semigroup a => a -> a -> a
<> Plan
right)

instance Monoid Plan where
  mempty :: Plan
mempty = Plan -> Plan
Plan Plan
forall a. Monoid a => a
mempty

-- | Compute an argument once from the local draft: its fee is zero, inputs and
-- redeemer indices are local to the sub-transaction, and resolved spending
-- inputs are in canonical order. Reference inputs are available in the draft
-- body but absent from the supplied spending snapshot. Return an error to abort.
-- The callback must be pure and deterministic. Snapshots are ordinary owned
-- values; no pointer or resource scope escapes the build.
type DeferredRedeemer = Transaction -> [Utxo] -> Either Error EncodedPlutusData

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

-- | Append an output in creation order. Building preserves its exact value.
payTo :: Output -> Plan
payTo :: Output -> Plan
payTo Output
a = Plan -> Plan
Plan (Output -> Plan
Top.payTo Output
a)

-- | Spend exactly this resolved key-controlled output.
spend :: Utxo -> Plan
spend :: Utxo -> Plan
spend Utxo
a = Plan -> Plan
Plan (Utxo -> Plan
Top.spend Utxo
a)

-- | Spend a script output with optional argument and datum witness.
spendWith :: Utxo -> Maybe EncodedPlutusData -> Maybe EncodedPlutusData -> Plan
spendWith :: Utxo -> Maybe EncodedPlutusData -> Maybe EncodedPlutusData -> Plan
spendWith Utxo
a Maybe EncodedPlutusData
b Maybe EncodedPlutusData
c = Plan -> Plan
Plan (Utxo -> Maybe EncodedPlutusData -> Maybe EncodedPlutusData -> Plan
Top.spendWith Utxo
a Maybe EncodedPlutusData
b Maybe EncodedPlutusData
c)

-- | Spend a script output with a local deferred argument and optional datum witness. Register each input once.
spendWithDeferredRedeemer :: Utxo -> DeferredRedeemer -> Maybe EncodedPlutusData -> Plan
spendWithDeferredRedeemer :: Utxo -> DeferredRedeemer -> Maybe EncodedPlutusData -> Plan
spendWithDeferredRedeemer Utxo
a DeferredRedeemer
b Maybe EncodedPlutusData
c = Plan -> Plan
Plan (Utxo -> DeferredRedeemer -> Maybe EncodedPlutusData -> Plan
Top.spendWithDeferredRedeemer Utxo
a DeferredRedeemer
b Maybe EncodedPlutusData
c)

-- | Make a resolved reference output available without spending it.
referenceInput :: Utxo -> Plan
referenceInput :: Utxo -> Plan
referenceInput Utxo
a = Plan -> Plan
Plan (Utxo -> Plan
Top.referenceInput Utxo
a)

-- | Attach a native or compiled Plutus script. Executed sub-level scripts require V4.
-- Repeated attachments with the same language and script bytes contribute one
-- witness, ordered by the first attachment.
attachScript :: Script -> Plan
attachScript :: Script -> Plan
attachScript Script
a = Plan -> Plan
Plan (Script -> Plan
Top.attachScript Script
a)

-- | Mint or burn a native asset. Ada and combined quantity overflow fail at build.
mint :: AssetId -> Int64 -> Plan
mint :: AssetId -> Int64 -> Plan
mint AssetId
a Int64
b = Plan -> Plan
Plan (AssetId -> Int64 -> Plan
Top.mint AssetId
a Int64
b)

-- | Mint or burn a Plutus-policy asset with an immediate argument.
mintWithRedeemer :: AssetId -> Int64 -> EncodedPlutusData -> Plan
mintWithRedeemer :: AssetId -> Int64 -> EncodedPlutusData -> Plan
mintWithRedeemer AssetId
a Int64
b EncodedPlutusData
c = Plan -> Plan
Plan (AssetId -> Int64 -> EncodedPlutusData -> Plan
Top.mintWithRedeemer AssetId
a Int64
b EncodedPlutusData
c)

-- | Mint or burn a group of names under one policy with one local deferred argument. Repeated names combine and zero totals disappear. Register each policy once.
mintWithDeferredRedeemer :: PolicyId -> [(AssetName, Int64)] -> DeferredRedeemer -> Plan
mintWithDeferredRedeemer :: PolicyId -> [(AssetName, Int64)] -> DeferredRedeemer -> Plan
mintWithDeferredRedeemer PolicyId
a [(AssetName, Int64)]
b DeferredRedeemer
c = Plan -> Plan
Plan (PolicyId -> [(AssetName, Int64)] -> DeferredRedeemer -> Plan
Top.mintWithDeferredRedeemer PolicyId
a [(AssetName, Int64)]
b DeferredRedeemer
c)

-- | Attach a metadata label; conflicting values fail at build.
metadata :: Word64 -> Metadatum -> Plan
metadata :: Word64 -> Metadatum -> Plan
metadata Word64
a Metadatum
b = Plan -> Plan
Plan (Word64 -> Metadatum -> Plan
Top.metadata Word64
a Metadatum
b)

-- | Attach an exact datum witness. Repeated exact CBOR encodings contribute one
-- witness, including data supplied to spending inputs, in first occurrence order.
-- Different encodings remain distinct because their hashes differ.
attachDatum :: EncodedPlutusData -> Plan
attachDatum :: EncodedPlutusData -> Plan
attachDatum EncodedPlutusData
a = Plan -> Plan
Plan (EncodedPlutusData -> Plan
Top.attachDatum EncodedPlutusData
a)

-- | Append a typed certificate without a script argument.
certificate :: Certificate -> Plan
certificate :: Certificate -> Plan
certificate Certificate
a = Plan -> Plan
Plan (Certificate -> Plan
Top.certificate Certificate
a)

-- | Append a typed certificate authorized by an immediate argument.
certificateWithRedeemer :: Certificate -> EncodedPlutusData -> Plan
certificateWithRedeemer :: Certificate -> EncodedPlutusData -> Plan
certificateWithRedeemer Certificate
a EncodedPlutusData
b = Plan -> Plan
Plan (Certificate -> EncodedPlutusData -> Plan
Top.certificateWithRedeemer Certificate
a EncodedPlutusData
b)

-- | Append a typed certificate authorized by a local deferred argument.
certificateWithDeferredRedeemer :: Certificate -> DeferredRedeemer -> Plan
certificateWithDeferredRedeemer :: Certificate -> DeferredRedeemer -> Plan
certificateWithDeferredRedeemer Certificate
a DeferredRedeemer
b = Plan -> Plan
Plan (Certificate -> DeferredRedeemer -> Plan
Top.certificateWithDeferredRedeemer Certificate
a DeferredRedeemer
b)

-- | Withdraw rewards from a key-controlled account. Amounts must fit signed 64-bit.
withdraw :: RewardAddress -> Word64 -> Plan
withdraw :: RewardAddress -> Word64 -> Plan
withdraw RewardAddress
a Word64
b = Plan -> Plan
Plan (RewardAddress -> Word64 -> Plan
Top.withdraw RewardAddress
a Word64
b)

-- | Withdraw rewards with an immediate Plutus argument.
withdrawWithRedeemer :: RewardAddress -> Word64 -> EncodedPlutusData -> Plan
withdrawWithRedeemer :: RewardAddress -> Word64 -> EncodedPlutusData -> Plan
withdrawWithRedeemer RewardAddress
a Word64
b EncodedPlutusData
c = Plan -> Plan
Plan (RewardAddress -> Word64 -> EncodedPlutusData -> Plan
Top.withdrawWithRedeemer RewardAddress
a Word64
b EncodedPlutusData
c)

-- | Withdraw rewards with a local deferred argument. Register each account once.
withdrawWithDeferredRedeemer :: RewardAddress -> Word64 -> DeferredRedeemer -> Plan
withdrawWithDeferredRedeemer :: RewardAddress -> Word64 -> DeferredRedeemer -> Plan
withdrawWithDeferredRedeemer RewardAddress
a Word64
b DeferredRedeemer
c = Plan -> Plan
Plan (RewardAddress -> Word64 -> DeferredRedeemer -> Plan
Top.withdrawWithDeferredRedeemer RewardAddress
a Word64
b DeferredRedeemer
c)

-- | Require a payment key hash as a local guard.
requireSigner :: KeyHash Payment -> Plan
requireSigner :: KeyHash Payment -> Plan
requireSigner KeyHash Payment
a = Plan -> Plan
Plan (KeyHash Payment -> Plan
Top.requireSigner KeyHash Payment
a)

-- | Inclusive lower validity slot; composition takes the greatest lower bound.
validFrom :: Word64 -> Plan
validFrom :: Word64 -> Plan
validFrom Word64
a = Plan -> Plan
Plan (Word64 -> Plan
Top.validFrom Word64
a)

-- | Exclusive upper validity slot; composition takes the least upper bound.
validUntil :: Word64 -> Plan
validUntil :: Word64 -> Plan
validUntil Word64
a = Plan -> Plan
Plan (Word64 -> Plan
Top.validUntil Word64
a)

-- | Unique spending and reference snapshots in ascending input-reference order.
-- Conflicting original snapshots are rejected when building.
-- Supply this result alongside a successfully built intent when attaching it
-- to an outer plan.
resolvedInputs :: Plan -> [Utxo]
resolvedInputs :: Plan -> [Utxo]
resolvedInputs (Plan Plan
plan) = 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]
Top.resolvedInputs Plan
plan])

-- | Internal reuse of common validation, serialization and rooted callbacks.
toPlan :: Plan -> Top.Plan
toPlan :: Plan -> Plan
toPlan (Plan Plan
plan) = Plan
plan

-- | Require a key or native-script guard. Use guardWithRedeemer for Plutus guards.
requireGuard :: Credential Guard -> Plan
requireGuard :: Credential Guard -> Plan
requireGuard Credential Guard
credential = Plan -> Plan
Plan (Credential Guard -> Plan
Top.requireGuard Credential Guard
credential)

-- | Require a local Plutus guard with its immediate argument.
guardWithRedeemer :: ScriptHash -> EncodedPlutusData -> Plan
guardWithRedeemer :: ScriptHash -> EncodedPlutusData -> Plan
guardWithRedeemer ScriptHash
hash EncodedPlutusData
argument = Plan -> Plan
Plan (ScriptHash -> EncodedPlutusData -> Plan
Top.guardWithRedeemer ScriptHash
hash EncodedPlutusData
argument)

-- | Deposit lovelace directly into a reward account. Repeated amounts combine.
directDeposit :: RewardAddress -> Word64 -> Plan
directDeposit :: RewardAddress -> Word64 -> Plan
directDeposit RewardAddress
account Word64
amount = Plan -> Plan
Plan (RewardAddress -> Word64 -> Plan
Top.directDeposit RewardAddress
account Word64
amount)

-- | Require a reward-account balance interval for this intent.
accountBalance :: RewardAddress -> BalanceInterval -> Plan
accountBalance :: RewardAddress -> BalanceInterval -> Plan
accountBalance RewardAddress
account BalanceInterval
interval = Plan -> Plan
Plan (RewardAddress -> BalanceInterval -> Plan
Top.accountBalance RewardAddress
account BalanceInterval
interval)

-- | Donate lovelace to the treasury; repeated donations combine.
donate :: Word64 -> Plan
 Word64
amount = Plan -> Plan
Plan (Word64 -> Plan
Top.donate Word64
amount)

-- | Append a governance proposal, using the configured governance deposit.
-- Parameter changes and treasury withdrawals naming a guardrails policy use
-- the unit argument @Constr 0 []@ and require a supplied Plutus V4 script.
-- Actions without a policy do not create a proposing redeemer.
propose :: RewardAddress -> Action -> Anchor -> Plan
propose :: RewardAddress -> Action -> Anchor -> Plan
propose RewardAddress
account Action
action Anchor
anchor = Plan -> Plan
Plan (RewardAddress -> Action -> Anchor -> Plan
Top.propose RewardAddress
account Action
action Anchor
anchor)

-- | Append a proposal with a guardrails argument. The action must name a policy;
-- the configured protocol snapshot supplies its deposit. Attach the script or
-- resolve its reference input separately. Duplicate proposals fail at build.
proposeWithRedeemer :: RewardAddress -> Action -> Anchor -> EncodedPlutusData -> Plan
proposeWithRedeemer :: RewardAddress -> Action -> Anchor -> EncodedPlutusData -> Plan
proposeWithRedeemer RewardAddress
account Action
action Anchor
anchor EncodedPlutusData
argument = Plan -> Plan
Plan (RewardAddress -> Action -> Anchor -> EncodedPlutusData -> Plan
Top.proposeWithRedeemer RewardAddress
account Action
action Anchor
anchor EncodedPlutusData
argument)

-- | Compute a proposal's guardrails argument from the local draft. Proposal
-- indices and resolved inputs belong to this subtransaction. The action must
-- name a policy; duplicate proposals fail at build.
proposeWithDeferredRedeemer :: RewardAddress -> Action -> Anchor -> DeferredRedeemer -> Plan
proposeWithDeferredRedeemer :: RewardAddress -> Action -> Anchor -> DeferredRedeemer -> Plan
proposeWithDeferredRedeemer RewardAddress
account Action
action Anchor
anchor DeferredRedeemer
callback = Plan -> Plan
Plan (RewardAddress -> Action -> Anchor -> DeferredRedeemer -> Plan
Top.proposeWithDeferredRedeemer RewardAddress
account Action
action Anchor
anchor DeferredRedeemer
callback)

-- | Cast a key-authorized governance vote.
vote :: Voter -> ActionId -> VotingProcedure -> Plan
vote :: Voter -> ActionId -> VotingProcedure -> Plan
vote Voter
voter ActionId
action VotingProcedure
procedure = Plan -> Plan
Plan (Voter -> ActionId -> VotingProcedure -> Plan
Top.vote Voter
voter ActionId
action VotingProcedure
procedure)

-- | Cast several votes under one voter with one immediate argument.
voteWithRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> EncodedPlutusData -> Plan
voteWithRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> EncodedPlutusData -> Plan
voteWithRedeemer Voter
voter [(ActionId, VotingProcedure)]
votes EncodedPlutusData
argument = Plan -> Plan
Plan (Voter -> [(ActionId, VotingProcedure)] -> EncodedPlutusData -> Plan
Top.voteWithRedeemer Voter
voter [(ActionId, VotingProcedure)]
votes EncodedPlutusData
argument)

-- | Cast several votes under one voter with one local deferred argument. Register each voter once; empty groups do not invoke the callback.
voteWithDeferredRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> DeferredRedeemer -> Plan
voteWithDeferredRedeemer :: Voter -> [(ActionId, VotingProcedure)] -> DeferredRedeemer -> Plan
voteWithDeferredRedeemer Voter
voter [(ActionId, VotingProcedure)]
votes DeferredRedeemer
callback = Plan -> Plan
Plan (Voter -> [(ActionId, VotingProcedure)] -> DeferredRedeemer -> Plan
Top.voteWithDeferredRedeemer Voter
voter [(ActionId, VotingProcedure)]
votes DeferredRedeemer
callback)

-- | Require an outer guard and optional datum for this intent. This records a
-- requirement; the enclosing transaction must satisfy it when assembled.
requireTopLevelGuard :: Credential Guard -> Maybe EncodedPlutusData -> Plan
requireTopLevelGuard :: Credential Guard -> Maybe EncodedPlutusData -> Plan
requireTopLevelGuard Credential Guard
credential Maybe EncodedPlutusData
datum = Plan -> Plan
Plan (Credential Guard -> Maybe EncodedPlutusData -> Plan
Top.requireTopLevelGuard Credential Guard
credential Maybe EncodedPlutusData
datum)