{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}

{- |
Module      : Singular.Registry.TxBuilder.Publication
Description : Registry funding, publication and configuration identity
License     : Apache-2.0

Funding selection, reference-script publication and configuration identity
for the registry commands. The publication arithmetic is shared with the
command preview; every input and amount is derived from the supplied view.
-}
module Singular.Registry.TxBuilder.Publication
    ( -- * Submission
      SubmitSigned

      -- * Derived identity
    , registryIdOf
    , witnessScriptOf
    , applicationPins

      -- * Reference outputs
    , publishRefScript
    , publishRefScriptReserving
    , publishRefScriptTx
    , PublicationFundingError (..)
    , selectPublicationInputs
    , firstPublicationChange
    , publicationFee
    , publicationMinChange
    , publicationRefCoin
    , publishStateRef
    , publishStateRefReserving
    , stateRefIn
    , adaOnlyOut
    , selectFunding
    ) where

import Data.ByteString (ByteString)
import Data.ByteString.Short qualified as SBS
import Data.List (sortOn)
import Data.Map.Strict qualified as Map
import Data.Ord (Down (..))
import Data.Sequence.Strict qualified as StrictSeq
import Data.Set qualified as Set
import Lens.Micro ((&), (.~), (^.))

import Cardano.Ledger.Address (Addr)
import Cardano.Ledger.Api.PParams (ppCoinsPerUTxOByteL, ppMaxTxSizeL)
import Cardano.Ledger.Api.Tx (mkBasicTx, txIdTx)
import Cardano.Ledger.Api.Tx.Body
    ( feeTxBodyL
    , inputsTxBodyL
    , mkBasicTxBody
    , outputsTxBodyL
    )
import Cardano.Ledger.Api.Tx.Out
    ( TxOut
    , coinTxOutL
    , getMinCoinTxOut
    , mkBasicTxOut
    , referenceScriptTxOutL
    , valueTxOutL
    )
import Cardano.Ledger.BaseTypes (StrictMaybe (..), TxIx (..))
import Cardano.Ledger.Coin (CoinPerByte (..))
import Cardano.Ledger.Compactible (fromCompact)
import Cardano.Ledger.Core (PParams, Script, hashScript)
import Cardano.Ledger.Mary.Value (MaryValue (..), MultiAsset (..))
import Cardano.Ledger.TxIn (TxIn (..))
import Cardano.Tx.Ledger (ConwayTx)
import PlutusCore.Data qualified as PLC
import Singular.Registry.AssetName (deriveAssetName)
import Singular.Registry.Blueprint.Load (ApplicationCodes (..))
import Singular.Registry.Blueprint.Params
    ( applyBytesParam
    , applyDataParam
    )
import Singular.Registry.Config (CageConfig (..))
import Singular.Registry.Evidence qualified as Cage
import Singular.Registry.Ledger (Coin (..), ConwayEra)
import Singular.Registry.LedgerProvider qualified as Cage
import Singular.Registry.SessionIO qualified as Cage
import Singular.Registry.TxBuilder.Internal.Identity
    ( computeScriptHash
    , mkCageScript
    , scriptFromBytes
    , scriptHashBytes
    )

{- | Sign a built transaction with the payer's key, submit it, and wait
for it. The caller owns its own signing key and its own confirmation
discipline, so it supplies this rather than the module guessing either.
-}
type SubmitSigned = ConwayTx -> IO ConwayTx

{- | The registry id a witness policy is parameterized by: the state
policy plus the token name this cage's seed determined.
-}
registryIdOf :: CageConfig -> ByteString
registryIdOf :: CageConfig -> ByteString
registryIdOf CageConfig
cfg =
    ScriptHash -> ByteString
scriptHashBytes (CageConfig -> ScriptHash
cfgScriptHash CageConfig
cfg) ByteString -> ByteString -> ByteString
forall a. Semigroup a => a -> a -> a
<> OnChainTxOutRef -> ByteString
deriveAssetName (CageConfig -> OnChainTxOutRef
cageSeed CageConfig
cfg)

-- | The witness policy script of one token kind.
witnessScriptOf
    :: CageConfig -> ApplicationCodes -> Integer -> Script ConwayEra
witnessScriptOf :: CageConfig -> ApplicationCodes -> Integer -> Script ConwayEra
witnessScriptOf CageConfig
cfg ApplicationCodes
codes Integer
kind =
    String -> ShortByteString -> Script ConwayEra
scriptFromBytes
        (String
"witness-" String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Integer -> String
forall a. Show a => a -> String
show Integer
kind)
        ( ByteString -> ShortByteString -> ShortByteString
applyBytesParam
            (CageConfig -> ByteString
registryIdOf CageConfig
cfg)
            (Data -> ShortByteString -> ShortByteString
applyDataParam (Integer -> Data
PLC.I Integer
kind) (ApplicationCodes -> ShortByteString
ncWitness ApplicationCodes
codes))
        )

{- | The two pins a registry identity carries (#157 genesis-policy-pins), derived
from the supplied application and token-policy code: the application validator
for the approval, and @witness(1, registry)@ for the active token.

The registry id the witness policies are parameterized by depends on the
state script hash and the boot seed, so this takes them directly rather
than a configuration that does not exist yet.
-}
applicationPins
    :: ApplicationCodes
    -> ByteString
    -- ^ The registry id: state script hash then boot token name
    -> (SBS.ShortByteString, SBS.ShortByteString)
    -- ^ Application, active
applicationPins :: ApplicationCodes
-> ByteString -> (ShortByteString, ShortByteString)
applicationPins ApplicationCodes
codes ByteString
registryId =
    ( ShortByteString -> ShortByteString
pinOf (ApplicationCodes -> ShortByteString
ncApplication ApplicationCodes
codes)
    , Integer -> ShortByteString
witnessPin Integer
1
    )
  where
    pinOf :: ShortByteString -> ShortByteString
pinOf = ByteString -> ShortByteString
SBS.toShort (ByteString -> ShortByteString)
-> (ShortByteString -> ByteString)
-> ShortByteString
-> ShortByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ScriptHash -> ByteString
scriptHashBytes (ScriptHash -> ByteString)
-> (ShortByteString -> ScriptHash) -> ShortByteString -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ShortByteString -> ScriptHash
computeScriptHash
    witnessPin :: Integer -> ShortByteString
witnessPin Integer
kind =
        ShortByteString -> ShortByteString
pinOf
            ( ByteString -> ShortByteString -> ShortByteString
applyBytesParam
                ByteString
registryId
                (Data -> ShortByteString -> ShortByteString
applyDataParam (Integer -> Data
PLC.I Integer
kind) (ApplicationCodes -> ShortByteString
ncWitness ApplicationCodes
codes))
            )

{- | Can this output fund a transaction? It must hold ada and nothing
else, because it doubles as collateral, and it must not be one of the
published reference outputs, because a transaction may not both spend an
output and reference it.
-}
adaOnlyOut :: TxOut ConwayEra -> Bool
adaOnlyOut :: TxOut ConwayEra -> Bool
adaOnlyOut TxOut ConwayEra
out =
    (case TxOut ConwayEra
BabbageTxOut ConwayEra
out BabbageTxOut ConwayEra
-> Getting MaryValue (BabbageTxOut ConwayEra) MaryValue
-> MaryValue
forall s a. s -> Getting a s a -> a
^. Getting MaryValue (BabbageTxOut ConwayEra) MaryValue
(Value ConwayEra -> Const MaryValue (Value ConwayEra))
-> TxOut ConwayEra -> Const MaryValue (TxOut ConwayEra)
forall era. EraTxOut era => Lens' (TxOut era) (Value era)
Lens' (TxOut ConwayEra) (Value ConwayEra)
valueTxOutL of MaryValue Coin
_ (MultiAsset Map PolicyID (Map AssetName Integer)
m) -> Map PolicyID (Map AssetName Integer) -> Bool
forall k a. Map k a -> Bool
Map.null Map PolicyID (Map AssetName Integer)
m)
        Bool -> Bool -> Bool
&& ( case TxOut ConwayEra
BabbageTxOut ConwayEra
out BabbageTxOut ConwayEra
-> Getting
     (StrictMaybe (Script ConwayEra))
     (BabbageTxOut ConwayEra)
     (StrictMaybe (Script ConwayEra))
-> StrictMaybe (Script ConwayEra)
forall s a. s -> Getting a s a -> a
^. (StrictMaybe (Script ConwayEra)
 -> Const
      (StrictMaybe (Script ConwayEra)) (StrictMaybe (Script ConwayEra)))
-> TxOut ConwayEra
-> Const (StrictMaybe (Script ConwayEra)) (TxOut ConwayEra)
Getting
  (StrictMaybe (Script ConwayEra))
  (BabbageTxOut ConwayEra)
  (StrictMaybe (Script ConwayEra))
forall era.
BabbageEraTxOut era =>
Lens' (TxOut era) (StrictMaybe (Script era))
Lens' (TxOut ConwayEra) (StrictMaybe (Script ConwayEra))
referenceScriptTxOutL of
                StrictMaybe (Script ConwayEra)
SNothing -> Bool
True
                SJust Script ConwayEra
_ -> Bool
False
           )

{- | The wallet output a transaction is funded and collateralised from: the
one the caller chose, which must be an ada-only output of the wallet, or else
the largest ada-only output. A caller that chose none still gets the output
least likely to leave the change under its minimum.
-}
selectFunding
    :: Maybe TxIn
    -> [(TxIn, TxOut ConwayEra)]
    -> Either String (TxIn, TxOut ConwayEra)
selectFunding :: Maybe TxIn
-> [(TxIn, TxOut ConwayEra)]
-> Either String (TxIn, TxOut ConwayEra)
selectFunding Maybe TxIn
chosen [(TxIn, TxOut ConwayEra)]
utxos = case Maybe TxIn
chosen of
    Maybe TxIn
Nothing -> case ((TxIn, BabbageTxOut ConwayEra) -> Down Coin)
-> [(TxIn, BabbageTxOut ConwayEra)]
-> [(TxIn, BabbageTxOut ConwayEra)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Coin -> Down Coin
forall a. a -> Down a
Down (Coin -> Down Coin)
-> ((TxIn, BabbageTxOut ConwayEra) -> Coin)
-> (TxIn, BabbageTxOut ConwayEra)
-> Down Coin
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (BabbageTxOut ConwayEra
-> Getting Coin (BabbageTxOut ConwayEra) Coin -> Coin
forall s a. s -> Getting a s a -> a
^. (Coin -> Const Coin Coin)
-> TxOut ConwayEra -> Const Coin (TxOut ConwayEra)
Getting Coin (BabbageTxOut ConwayEra) Coin
forall era. (HasCallStack, EraTxOut era) => Lens' (TxOut era) Coin
Lens' (TxOut ConwayEra) Coin
coinTxOutL) (BabbageTxOut ConwayEra -> Coin)
-> ((TxIn, BabbageTxOut ConwayEra) -> BabbageTxOut ConwayEra)
-> (TxIn, BabbageTxOut ConwayEra)
-> Coin
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TxIn, BabbageTxOut ConwayEra) -> BabbageTxOut ConwayEra
forall a b. (a, b) -> b
snd) [(TxIn, BabbageTxOut ConwayEra)]
usable of
        [] -> String -> Either String (TxIn, BabbageTxOut ConwayEra)
forall a b. a -> Either a b
Left String
"the payer wallet has no ada-only output"
        ((TxIn, BabbageTxOut ConwayEra)
u : [(TxIn, BabbageTxOut ConwayEra)]
_) -> (TxIn, BabbageTxOut ConwayEra)
-> Either String (TxIn, BabbageTxOut ConwayEra)
forall a b. b -> Either a b
Right (TxIn, BabbageTxOut ConwayEra)
u
    Just TxIn
wanted -> case [(TxIn, BabbageTxOut ConwayEra)
u | u :: (TxIn, BabbageTxOut ConwayEra)
u@(TxIn
i, BabbageTxOut ConwayEra
_) <- [(TxIn, BabbageTxOut ConwayEra)]
usable, TxIn
i TxIn -> TxIn -> Bool
forall a. Eq a => a -> a -> Bool
== TxIn
wanted] of
        ((TxIn, BabbageTxOut ConwayEra)
u : [(TxIn, BabbageTxOut ConwayEra)]
_) -> (TxIn, BabbageTxOut ConwayEra)
-> Either String (TxIn, BabbageTxOut ConwayEra)
forall a b. b -> Either a b
Right (TxIn, BabbageTxOut ConwayEra)
u
        [] ->
            String -> Either String (TxIn, BabbageTxOut ConwayEra)
forall a b. a -> Either a b
Left
                String
"the chosen funding output is not an ada-only output of the payer"
  where
    usable :: [(TxIn, BabbageTxOut ConwayEra)]
usable = ((TxIn, BabbageTxOut ConwayEra) -> Bool)
-> [(TxIn, BabbageTxOut ConwayEra)]
-> [(TxIn, BabbageTxOut ConwayEra)]
forall a. (a -> Bool) -> [a] -> [a]
filter (TxOut ConwayEra -> Bool
BabbageTxOut ConwayEra -> Bool
adaOnlyOut (BabbageTxOut ConwayEra -> Bool)
-> ((TxIn, BabbageTxOut ConwayEra) -> BabbageTxOut ConwayEra)
-> (TxIn, BabbageTxOut ConwayEra)
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TxIn, BabbageTxOut ConwayEra) -> BabbageTxOut ConwayEra
forall a b. (a, b) -> b
snd) [(TxIn, TxOut ConwayEra)]
[(TxIn, BabbageTxOut ConwayEra)]
utxos

{- | The flat fee a publication pays, and the change it must leave strictly
above. One owner (#406): the builder and the whole-run judgement share
these with the pure selection below, never a second copy.
-}
publicationFee :: Integer
publicationFee :: Integer
publicationFee = Integer
1_000_000

publicationMinChange :: Integer
publicationMinChange :: Integer
publicationMinChange = Integer
1_000_000

{- | The reference output a publication creates at the payer's address:
the ledger minimum for the script plus one million lovelace. One owner:
both the selection and the whole-run need share it.
-}
publicationRefCoin
    :: PParams ConwayEra -> Addr -> Script ConwayEra -> Integer
publicationRefCoin :: PParams ConwayEra -> Addr -> Script ConwayEra -> Integer
publicationRefCoin PParams ConwayEra
pp Addr
payerAddr Script ConwayEra
script =
    let probe :: TxOut ConwayEra
probe =
            Addr -> Value ConwayEra -> TxOut ConwayEra
forall era.
(EraTxOut era, HasCallStack) =>
Addr -> Value era -> TxOut era
mkBasicTxOut Addr
payerAddr (Coin -> MultiAsset -> MaryValue
MaryValue (Integer -> Coin
Coin Integer
0) MultiAsset
forall a. Monoid a => a
mempty)
                TxOut ConwayEra
-> (TxOut ConwayEra -> TxOut ConwayEra) -> TxOut ConwayEra
forall a b. a -> (a -> b) -> b
& (StrictMaybe (Script ConwayEra)
 -> Identity (StrictMaybe (Script ConwayEra)))
-> TxOut ConwayEra -> Identity (TxOut ConwayEra)
forall era.
BabbageEraTxOut era =>
Lens' (TxOut era) (StrictMaybe (Script era))
Lens' (TxOut ConwayEra) (StrictMaybe (Script ConwayEra))
referenceScriptTxOutL ((StrictMaybe (Script ConwayEra)
  -> Identity (StrictMaybe (Script ConwayEra)))
 -> TxOut ConwayEra -> Identity (TxOut ConwayEra))
-> StrictMaybe (Script ConwayEra)
-> TxOut ConwayEra
-> TxOut ConwayEra
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Script ConwayEra -> StrictMaybe (Script ConwayEra)
forall a. a -> StrictMaybe a
SJust Script ConwayEra
script
        Coin Integer
minCoin = PParams ConwayEra -> TxOut ConwayEra -> Coin
forall era. EraTxOut era => PParams era -> TxOut era -> Coin
getMinCoinTxOut PParams ConwayEra
pp TxOut ConwayEra
BabbageTxOut ConwayEra
probe
    in  Integer
minCoin Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
1_000_000

{- | Why one publication cannot be funded: too little in total, or a
covering prefix too large for the protocol maximum transaction size.
-}
data PublicationFundingError
    = PublicationShortfall
        { PublicationFundingError -> Integer
pfeNeeded :: Integer
        , PublicationFundingError -> Integer
pfeHeld :: Integer
        , PublicationFundingError -> Integer
pfeLargest :: Integer
        }
    | PublicationOversize
        { PublicationFundingError -> Integer
pfeSize :: Integer
        , PublicationFundingError -> Integer
pfeLimit :: Integer
        }
    deriving stock (PublicationFundingError -> PublicationFundingError -> Bool
(PublicationFundingError -> PublicationFundingError -> Bool)
-> (PublicationFundingError -> PublicationFundingError -> Bool)
-> Eq PublicationFundingError
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: PublicationFundingError -> PublicationFundingError -> Bool
== :: PublicationFundingError -> PublicationFundingError -> Bool
$c/= :: PublicationFundingError -> PublicationFundingError -> Bool
/= :: PublicationFundingError -> PublicationFundingError -> Bool
Eq, Int -> PublicationFundingError -> String -> String
[PublicationFundingError] -> String -> String
PublicationFundingError -> String
(Int -> PublicationFundingError -> String -> String)
-> (PublicationFundingError -> String)
-> ([PublicationFundingError] -> String -> String)
-> Show PublicationFundingError
forall a.
(Int -> a -> String -> String)
-> (a -> String) -> ([a] -> String -> String) -> Show a
$cshowsPrec :: Int -> PublicationFundingError -> String -> String
showsPrec :: Int -> PublicationFundingError -> String -> String
$cshow :: PublicationFundingError -> String
show :: PublicationFundingError -> String
$cshowList :: [PublicationFundingError] -> String -> String
showList :: [PublicationFundingError] -> String -> String
Show)

{- | One owner of the publication arithmetic (#406): the shortest
largest-first prefix of the permitted outputs whose total covers the
reference output plus the fee plus a change strictly above the minimum,
with the inputs, the reference output and the change; or the shortfall
it names (needed total, held total, largest output). A covering prefix
whose transaction would exceed the protocol maximum size is refused up
front, naming size and limit, so a wallet of many dust outputs never
reaches submission.

The permitted outputs are ada-only with no reference script, the seed
withheld before the boot. A covering output spends exactly one input
and it is the largest; otherwise no output that is not needed is spent.
-}
selectPublicationInputs
    :: PParams ConwayEra
    -> Addr
    -> Script ConwayEra
    -> [(k, TxOut ConwayEra)]
    -> Either
        PublicationFundingError
        ([(k, TxOut ConwayEra)], TxOut ConwayEra, Integer)
selectPublicationInputs :: forall k.
PParams ConwayEra
-> Addr
-> Script ConwayEra
-> [(k, TxOut ConwayEra)]
-> Either
     PublicationFundingError
     ([(k, TxOut ConwayEra)], TxOut ConwayEra, Integer)
selectPublicationInputs PParams ConwayEra
pp Addr
payerAddr Script ConwayEra
script [(k, TxOut ConwayEra)]
permitted = do
    let ordered :: [(k, TxOut ConwayEra)]
ordered = ((k, TxOut ConwayEra) -> Down Coin)
-> [(k, TxOut ConwayEra)] -> [(k, TxOut ConwayEra)]
forall b a. Ord b => (a -> b) -> [a] -> [a]
sortOn (Coin -> Down Coin
forall a. a -> Down a
Down (Coin -> Down Coin)
-> ((k, TxOut ConwayEra) -> Coin)
-> (k, TxOut ConwayEra)
-> Down Coin
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (TxOut ConwayEra
-> ((Coin -> Const Coin Coin)
    -> TxOut ConwayEra -> Const Coin (TxOut ConwayEra))
-> Coin
forall s a. s -> Getting a s a -> a
^. (Coin -> Const Coin Coin)
-> TxOut ConwayEra -> Const Coin (TxOut ConwayEra)
forall era. (HasCallStack, EraTxOut era) => Lens' (TxOut era) Coin
Lens' (TxOut ConwayEra) Coin
coinTxOutL) (TxOut ConwayEra -> Coin)
-> ((k, TxOut ConwayEra) -> TxOut ConwayEra)
-> (k, TxOut ConwayEra)
-> Coin
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (k, TxOut ConwayEra) -> TxOut ConwayEra
forall a b. (a, b) -> b
snd) [(k, TxOut ConwayEra)]
permitted
        coins :: [Integer]
coins = [Integer
c | (k
_, BabbageTxOut ConwayEra
o) <- [(k, BabbageTxOut ConwayEra)]
ordered, let Coin Integer
c = BabbageTxOut ConwayEra
o BabbageTxOut ConwayEra
-> Getting Coin (BabbageTxOut ConwayEra) Coin -> Coin
forall s a. s -> Getting a s a -> a
^. (Coin -> Const Coin Coin)
-> TxOut ConwayEra -> Const Coin (TxOut ConwayEra)
Getting Coin (BabbageTxOut ConwayEra) Coin
forall era. (HasCallStack, EraTxOut era) => Lens' (TxOut era) Coin
Lens' (TxOut ConwayEra) Coin
coinTxOutL]
        held :: Integer
held = [Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Integer]
coins
        largest :: Integer
largest = case [Integer]
coins of
            [] -> Integer
0
            (Integer
c : [Integer]
_) -> Integer
c
        refCoin :: Integer
refCoin = PParams ConwayEra -> Addr -> Script ConwayEra -> Integer
publicationRefCoin PParams ConwayEra
pp Addr
payerAddr Script ConwayEra
script
        needed :: Integer
needed = Integer
refCoin Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
publicationFee Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
publicationMinChange
        refOut :: TxOut ConwayEra
refOut =
            Addr -> Value ConwayEra -> TxOut ConwayEra
forall era.
(EraTxOut era, HasCallStack) =>
Addr -> Value era -> TxOut era
mkBasicTxOut Addr
payerAddr (Coin -> MultiAsset -> MaryValue
MaryValue (Integer -> Coin
Coin Integer
refCoin) MultiAsset
forall a. Monoid a => a
mempty)
                TxOut ConwayEra
-> (TxOut ConwayEra -> TxOut ConwayEra) -> TxOut ConwayEra
forall a b. a -> (a -> b) -> b
& (StrictMaybe (Script ConwayEra)
 -> Identity (StrictMaybe (Script ConwayEra)))
-> TxOut ConwayEra -> Identity (TxOut ConwayEra)
forall era.
BabbageEraTxOut era =>
Lens' (TxOut era) (StrictMaybe (Script era))
Lens' (TxOut ConwayEra) (StrictMaybe (Script ConwayEra))
referenceScriptTxOutL ((StrictMaybe (Script ConwayEra)
  -> Identity (StrictMaybe (Script ConwayEra)))
 -> TxOut ConwayEra -> Identity (TxOut ConwayEra))
-> StrictMaybe (Script ConwayEra)
-> TxOut ConwayEra
-> TxOut ConwayEra
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Script ConwayEra -> StrictMaybe (Script ConwayEra)
forall a. a -> StrictMaybe a
SJust Script ConwayEra
script
        covering :: Maybe [(k, TxOut ConwayEra)]
covering = Integer
-> [(k, TxOut ConwayEra)]
-> Integer
-> Maybe [(k, TxOut ConwayEra)]
forall {era} {a}.
(Assert
   (OrdCond
      (CmpNat (ProtVerLow era) (ProtVerHigh era)) 'True 'True 'False)
   (TypeError ...),
 Assert
   (OrdCond (CmpNat 0 (ProtVerLow era)) 'True 'True 'False)
   (TypeError ...),
 Assert
   (OrdCond (CmpNat 0 (ProtVerHigh era)) 'True 'True 'False)
   (TypeError ...),
 EraTxOut era) =>
Integer -> [(a, TxOut era)] -> Integer -> Maybe [(a, TxOut era)]
takeCovering Integer
needed [(k, TxOut ConwayEra)]
[(k, BabbageTxOut ConwayEra)]
ordered Integer
0
    prefix <- case Maybe [(k, BabbageTxOut ConwayEra)]
covering of
        Maybe [(k, BabbageTxOut ConwayEra)]
Nothing -> PublicationFundingError
-> Either PublicationFundingError [(k, BabbageTxOut ConwayEra)]
forall a b. a -> Either a b
Left (Integer -> Integer -> Integer -> PublicationFundingError
PublicationShortfall Integer
needed Integer
held Integer
largest)
        Just [(k, BabbageTxOut ConwayEra)]
chosen -> [(k, BabbageTxOut ConwayEra)]
-> Either PublicationFundingError [(k, BabbageTxOut ConwayEra)]
forall a. a -> Either PublicationFundingError a
forall (f :: * -> *) a. Applicative f => a -> f a
pure [(k, BabbageTxOut ConwayEra)]
chosen
    let total = [Integer] -> Integer
forall a. Num a => [a] -> a
forall (t :: * -> *) a. (Foldable t, Num a) => t a -> a
sum [Integer
c | (k
_, BabbageTxOut ConwayEra
o) <- [(k, BabbageTxOut ConwayEra)]
prefix, let Coin Integer
c = BabbageTxOut ConwayEra
o BabbageTxOut ConwayEra
-> Getting Coin (BabbageTxOut ConwayEra) Coin -> Coin
forall s a. s -> Getting a s a -> a
^. (Coin -> Const Coin Coin)
-> TxOut ConwayEra -> Const Coin (TxOut ConwayEra)
Getting Coin (BabbageTxOut ConwayEra) Coin
forall era. (HasCallStack, EraTxOut era) => Lens' (TxOut era) Coin
Lens' (TxOut ConwayEra) Coin
coinTxOutL]
        change = Integer
total Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
publicationFee Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
refCoin
        CoinPerByte compactPerByte = pp ^. ppCoinsPerUTxOByteL
        Coin perByte = fromCompact compactPerByte
        limit = Word32 -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral (PParams ConwayEra
pp PParams ConwayEra
-> Getting Word32 (PParams ConwayEra) Word32 -> Word32
forall s a. s -> Getting a s a -> a
^. Getting Word32 (PParams ConwayEra) Word32
forall era. EraPParams era => Lens' (PParams era) Word32
Lens' (PParams ConwayEra) Word32
ppMaxTxSizeL)
        size =
            if Integer
perByte Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
<= Integer
0
                then Integer
0
                else (Integer
refCoin Integer -> Integer -> Integer
forall a. Integral a => a -> a -> a
`div` Integer
perByte) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Int -> Integer
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([(k, BabbageTxOut ConwayEra)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [(k, BabbageTxOut ConwayEra)]
prefix) Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
* Integer
40 Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
300
    if limit > 0 && size > limit
        then Left (PublicationOversize size limit)
        else pure (prefix, refOut, change)
  where
    takeCovering :: Integer -> [(a, TxOut era)] -> Integer -> Maybe [(a, TxOut era)]
takeCovering Integer
_ [] Integer
_ = Maybe [(a, TxOut era)]
forall a. Maybe a
Nothing
    takeCovering Integer
need ((a
k, TxOut era
o) : [(a, TxOut era)]
rest) Integer
acc =
        let Coin Integer
c = TxOut era
o TxOut era -> Getting Coin (TxOut era) Coin -> Coin
forall s a. s -> Getting a s a -> a
^. Getting Coin (TxOut era) Coin
forall era. (HasCallStack, EraTxOut era) => Lens' (TxOut era) Coin
Lens' (TxOut era) Coin
coinTxOutL
            acc' :: Integer
acc' = Integer
acc Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
+ Integer
c
        in  if Integer
acc' Integer -> Integer -> Bool
forall a. Ord a => a -> a -> Bool
> Integer
need
                then [(a, TxOut era)] -> Maybe [(a, TxOut era)]
forall a. a -> Maybe a
Just [(a
k, TxOut era
o)]
                else case Integer -> [(a, TxOut era)] -> Integer -> Maybe [(a, TxOut era)]
takeCovering Integer
need [(a, TxOut era)]
rest Integer
acc' of
                    Maybe [(a, TxOut era)]
Nothing -> Maybe [(a, TxOut era)]
forall a. Maybe a
Nothing
                    Just [(a, TxOut era)]
chosen -> [(a, TxOut era)] -> Maybe [(a, TxOut era)]
forall a. a -> Maybe a
Just ((a
k, TxOut era
o) (a, TxOut era) -> [(a, TxOut era)] -> [(a, TxOut era)]
forall a. a -> [a] -> [a]
: [(a, TxOut era)]
chosen)

{- | The change output a first publication makes from the whole wallet, and
the seed it becomes (#406 slice 2): the shortest largest-first prefix of
all the ada-only outputs (nothing withheld) funds the state publication,
its change at index 1 is the chained seed. The body is exactly the one
'publishRefScriptTx' builds from the same view (flat fee, no validity
interval), so the transaction id — and the token it derives — is the same
in preview and in create. The arithmetic is 'selectPublicationInputs''s;
this accessor adds only the body and its id.
-}
firstPublicationChange
    :: PParams ConwayEra
    -> Addr
    -> Script ConwayEra
    -> [(TxIn, TxOut ConwayEra)]
    -> Either
        PublicationFundingError
        (TxIn, ConwayTx, TxOut ConwayEra, [(TxIn, TxOut ConwayEra)], Integer)
firstPublicationChange :: PParams ConwayEra
-> Addr
-> Script ConwayEra
-> [(TxIn, TxOut ConwayEra)]
-> Either
     PublicationFundingError
     (TxIn, ConwayTx, TxOut ConwayEra, [(TxIn, TxOut ConwayEra)],
      Integer)
firstPublicationChange PParams ConwayEra
pp Addr
payerAddr Script ConwayEra
script [(TxIn, TxOut ConwayEra)]
wallet = do
    let permitted :: [(TxIn, BabbageTxOut ConwayEra)]
permitted = [(TxIn, BabbageTxOut ConwayEra)
u | u :: (TxIn, BabbageTxOut ConwayEra)
u@(TxIn
_, BabbageTxOut ConwayEra
o) <- [(TxIn, TxOut ConwayEra)]
[(TxIn, BabbageTxOut ConwayEra)]
wallet, TxOut ConwayEra -> Bool
adaOnlyOut TxOut ConwayEra
BabbageTxOut ConwayEra
o]
    (funds, refOut, changeCoin) <-
        PParams ConwayEra
-> Addr
-> Script ConwayEra
-> [(TxIn, TxOut ConwayEra)]
-> Either
     PublicationFundingError
     ([(TxIn, TxOut ConwayEra)], TxOut ConwayEra, Integer)
forall k.
PParams ConwayEra
-> Addr
-> Script ConwayEra
-> [(k, TxOut ConwayEra)]
-> Either
     PublicationFundingError
     ([(k, TxOut ConwayEra)], TxOut ConwayEra, Integer)
selectPublicationInputs PParams ConwayEra
pp Addr
payerAddr Script ConwayEra
script [(TxIn, TxOut ConwayEra)]
[(TxIn, BabbageTxOut ConwayEra)]
permitted
    let changeOut = Addr -> Value ConwayEra -> TxOut ConwayEra
forall era.
(EraTxOut era, HasCallStack) =>
Addr -> Value era -> TxOut era
mkBasicTxOut Addr
payerAddr (Coin -> MultiAsset -> MaryValue
MaryValue (Integer -> Coin
Coin Integer
changeCoin) MultiAsset
forall a. Monoid a => a
mempty)
        body =
            TxBody TopTx ConwayEra
forall era (l :: TxLevel).
(EraTxBody era, Typeable l) =>
TxBody l era
forall (l :: TxLevel). Typeable l => TxBody l ConwayEra
mkBasicTxBody
                TxBody TopTx ConwayEra
-> (TxBody TopTx ConwayEra -> TxBody TopTx ConwayEra)
-> TxBody TopTx ConwayEra
forall a b. a -> (a -> b) -> b
& (Set TxIn -> Identity (Set TxIn))
-> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra)
forall era (l :: TxLevel).
EraTxBody era =>
Lens' (TxBody l era) (Set TxIn)
forall (l :: TxLevel). Lens' (TxBody l ConwayEra) (Set TxIn)
inputsTxBodyL ((Set TxIn -> Identity (Set TxIn))
 -> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra))
-> Set TxIn -> TxBody TopTx ConwayEra -> TxBody TopTx ConwayEra
forall s t a b. ASetter s t a b -> b -> s -> t
.~ [TxIn] -> Set TxIn
forall a. Ord a => [a] -> Set a
Set.fromList (((TxIn, BabbageTxOut ConwayEra) -> TxIn)
-> [(TxIn, BabbageTxOut ConwayEra)] -> [TxIn]
forall a b. (a -> b) -> [a] -> [b]
map (TxIn, BabbageTxOut ConwayEra) -> TxIn
forall a b. (a, b) -> a
fst [(TxIn, BabbageTxOut ConwayEra)]
funds)
                TxBody TopTx ConwayEra
-> (TxBody TopTx ConwayEra -> TxBody TopTx ConwayEra)
-> TxBody TopTx ConwayEra
forall a b. a -> (a -> b) -> b
& (StrictSeq (TxOut ConwayEra)
 -> Identity (StrictSeq (TxOut ConwayEra)))
-> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra)
forall era (l :: TxLevel).
EraTxBody era =>
Lens' (TxBody l era) (StrictSeq (TxOut era))
forall (l :: TxLevel).
Lens' (TxBody l ConwayEra) (StrictSeq (TxOut ConwayEra))
outputsTxBodyL
                    ((StrictSeq (TxOut ConwayEra)
  -> Identity (StrictSeq (TxOut ConwayEra)))
 -> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra))
-> StrictSeq (TxOut ConwayEra)
-> TxBody TopTx ConwayEra
-> TxBody TopTx ConwayEra
forall s t a b. ASetter s t a b -> b -> s -> t
.~ [TxOut ConwayEra] -> StrictSeq (TxOut ConwayEra)
forall a. [a] -> StrictSeq a
StrictSeq.fromList [TxOut ConwayEra
refOut, TxOut ConwayEra
changeOut]
                TxBody TopTx ConwayEra
-> (TxBody TopTx ConwayEra -> TxBody TopTx ConwayEra)
-> TxBody TopTx ConwayEra
forall a b. a -> (a -> b) -> b
& (Coin -> Identity Coin)
-> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra)
forall era. EraTxBody era => Lens' (TxBody TopTx era) Coin
Lens' (TxBody TopTx ConwayEra) Coin
feeTxBodyL ((Coin -> Identity Coin)
 -> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra))
-> Coin -> TxBody TopTx ConwayEra -> TxBody TopTx ConwayEra
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Integer -> Coin
Coin Integer
publicationFee
        tx = TxBody TopTx ConwayEra -> ConwayTx
forall era (l :: TxLevel). EraTx era => TxBody l era -> Tx l era
forall (l :: TxLevel). TxBody l ConwayEra -> Tx l ConwayEra
mkBasicTx TxBody TopTx ConwayEra
body
        seed = TxId -> TxIx -> TxIn
TxIn (ConwayTx -> TxId
forall era (l :: TxLevel). EraTx era => Tx l era -> TxId
txIdTx ConwayTx
tx) (Word16 -> TxIx
TxIx Word16
1)
    pure (seed, tx, refOut, funds, changeCoin)

-- | Publish one script as a reference output at the payer's own address.
publishRefScript
    :: (Cage.Network, Cage.LedgerProvider Cage.NoWitness IO)
    -> SubmitSigned
    -> Addr
    -> Script ConwayEra
    -> IO (TxIn, TxOut ConwayEra)
publishRefScript :: (Network, LedgerProvider NoWitness IO)
-> SubmitSigned
-> Addr
-> Script ConwayEra
-> IO (TxIn, TxOut ConwayEra)
publishRefScript = Set TxIn
-> (Network, LedgerProvider NoWitness IO)
-> SubmitSigned
-> Addr
-> Script ConwayEra
-> IO (TxIn, TxOut ConwayEra)
publishRefScriptReserving Set TxIn
forall a. Set a
Set.empty

{- | 'publishRefScript', never spending a reserved output (#299): a caller
that has chosen the seed of a later boot keeps it unspent while it
publishes. The largest ada-only output that is not reserved funds it.
-}
publishRefScriptReserving
    :: Set.Set TxIn
    -> (Cage.Network, Cage.LedgerProvider Cage.NoWitness IO)
    -> SubmitSigned
    -> Addr
    -> Script ConwayEra
    -> IO (TxIn, TxOut ConwayEra)
publishRefScriptReserving :: Set TxIn
-> (Network, LedgerProvider NoWitness IO)
-> SubmitSigned
-> Addr
-> Script ConwayEra
-> IO (TxIn, TxOut ConwayEra)
publishRefScriptReserving Set TxIn
reserved (Network, LedgerProvider NoWitness IO)
prov SubmitSigned
submit Addr
payerAddr Script ConwayEra
script = do
    (unsigned, refOut) <-
        (Network, LedgerProvider NoWitness IO)
-> (Session NoWitness IO -> IO (ConwayTx, BabbageTxOut ConwayEra))
-> IO (ConwayTx, BabbageTxOut ConwayEra)
forall w a.
(Network, LedgerProvider w IO) -> (Session w IO -> IO a) -> IO a
Cage.withLatest (Network, LedgerProvider NoWitness IO)
prov ((Session NoWitness IO -> IO (ConwayTx, BabbageTxOut ConwayEra))
 -> IO (ConwayTx, BabbageTxOut ConwayEra))
-> (Session NoWitness IO -> IO (ConwayTx, BabbageTxOut ConwayEra))
-> IO (ConwayTx, BabbageTxOut ConwayEra)
forall a b. (a -> b) -> a -> b
$ \Session NoWitness IO
v -> Set TxIn
-> Session NoWitness IO
-> Addr
-> Script ConwayEra
-> IO (ConwayTx, TxOut ConwayEra)
publishRefScriptTx Set TxIn
reserved Session NoWitness IO
v Addr
payerAddr Script ConwayEra
script
    signed <- submit unsigned
    pure (TxIn (txIdTx signed) (TxIx 0), refOut)

{- | The unsigned publication of one reference script, funded by the
shortest largest-first prefix of the ada-only outputs outside the
reservation, and the reference output it creates.
-}
publishRefScriptTx
    :: Set.Set TxIn
    -> Cage.Session Cage.NoWitness IO
    -> Addr
    -> Script ConwayEra
    -> IO (ConwayTx, TxOut ConwayEra)
publishRefScriptTx :: Set TxIn
-> Session NoWitness IO
-> Addr
-> Script ConwayEra
-> IO (ConwayTx, TxOut ConwayEra)
publishRefScriptTx Set TxIn
reserved Session NoWitness IO
v Addr
payerAddr Script ConwayEra
script = do
    pp <- Session NoWitness IO -> IO (PParams ConwayEra)
forall w. Session w IO -> IO (PParams ConwayEra)
Cage.parameters Session NoWitness IO
v
    utxos <- Cage.outputsAt v payerAddr
    let permitted =
            ((TxIn, BabbageTxOut ConwayEra) -> Bool)
-> [(TxIn, BabbageTxOut ConwayEra)]
-> [(TxIn, BabbageTxOut ConwayEra)]
forall a. (a -> Bool) -> [a] -> [a]
filter (\(TxIn
i, BabbageTxOut ConwayEra
o) -> TxOut ConwayEra -> Bool
adaOnlyOut TxOut ConwayEra
BabbageTxOut ConwayEra
o Bool -> Bool -> Bool
&& TxIn -> Set TxIn -> Bool
forall a. Ord a => a -> Set a -> Bool
Set.notMember TxIn
i Set TxIn
reserved) [(TxIn, BabbageTxOut ConwayEra)]
utxos
    (funds, refOut, changeCoin) <- case selectPublicationInputs pp payerAddr script permitted of
        Left (PublicationShortfall Integer
needed Integer
held Integer
largest) ->
            if [(TxIn, BabbageTxOut ConwayEra)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [(TxIn, BabbageTxOut ConwayEra)]
permitted
                then String
-> IO
     ([(TxIn, BabbageTxOut ConwayEra)], BabbageTxOut ConwayEra, Integer)
forall a. HasCallStack => String -> a
error String
"publishRefScript: the payer wallet has no ada-only output"
                else
                    String
-> IO
     ([(TxIn, BabbageTxOut ConwayEra)], BabbageTxOut ConwayEra, Integer)
forall a. HasCallStack => String -> a
error
                        ( String
"publishRefScript: the funding outputs hold "
                            String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Integer -> String
forall a. Show a => a -> String
show Integer
held
                            String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
", which does not cover a reference output of "
                            String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Integer -> String
forall a. Show a => a -> String
show (Integer
needed Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
publicationFee Integer -> Integer -> Integer
forall a. Num a => a -> a -> a
- Integer
publicationMinChange)
                            String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" plus fees; largest holds "
                            String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Integer -> String
forall a. Show a => a -> String
show Integer
largest
                        )
        Left (PublicationOversize Integer
size Integer
limit) ->
            String
-> IO
     ([(TxIn, BabbageTxOut ConwayEra)], BabbageTxOut ConwayEra, Integer)
forall a. HasCallStack => String -> a
error
                ( String
"publishRefScript: the funding transaction would be "
                    String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Integer -> String
forall a. Show a => a -> String
show Integer
size
                    String -> String -> String
forall a. Semigroup a => a -> a -> a
<> String
" bytes, over the protocol maximum "
                    String -> String -> String
forall a. Semigroup a => a -> a -> a
<> Integer -> String
forall a. Show a => a -> String
show Integer
limit
                )
        Right ([(TxIn, TxOut ConwayEra)], TxOut ConwayEra, Integer)
chosen -> ([(TxIn, BabbageTxOut ConwayEra)], BabbageTxOut ConwayEra, Integer)
-> IO
     ([(TxIn, BabbageTxOut ConwayEra)], BabbageTxOut ConwayEra, Integer)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ([(TxIn, TxOut ConwayEra)], TxOut ConwayEra, Integer)
([(TxIn, BabbageTxOut ConwayEra)], BabbageTxOut ConwayEra, Integer)
chosen
    let body =
            TxBody TopTx ConwayEra
forall era (l :: TxLevel).
(EraTxBody era, Typeable l) =>
TxBody l era
forall (l :: TxLevel). Typeable l => TxBody l ConwayEra
mkBasicTxBody
                TxBody TopTx ConwayEra
-> (TxBody TopTx ConwayEra -> TxBody TopTx ConwayEra)
-> TxBody TopTx ConwayEra
forall a b. a -> (a -> b) -> b
& (Set TxIn -> Identity (Set TxIn))
-> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra)
forall era (l :: TxLevel).
EraTxBody era =>
Lens' (TxBody l era) (Set TxIn)
forall (l :: TxLevel). Lens' (TxBody l ConwayEra) (Set TxIn)
inputsTxBodyL ((Set TxIn -> Identity (Set TxIn))
 -> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra))
-> Set TxIn -> TxBody TopTx ConwayEra -> TxBody TopTx ConwayEra
forall s t a b. ASetter s t a b -> b -> s -> t
.~ [TxIn] -> Set TxIn
forall a. Ord a => [a] -> Set a
Set.fromList (((TxIn, BabbageTxOut ConwayEra) -> TxIn)
-> [(TxIn, BabbageTxOut ConwayEra)] -> [TxIn]
forall a b. (a -> b) -> [a] -> [b]
map (TxIn, BabbageTxOut ConwayEra) -> TxIn
forall a b. (a, b) -> a
fst [(TxIn, BabbageTxOut ConwayEra)]
funds)
                TxBody TopTx ConwayEra
-> (TxBody TopTx ConwayEra -> TxBody TopTx ConwayEra)
-> TxBody TopTx ConwayEra
forall a b. a -> (a -> b) -> b
& (StrictSeq (TxOut ConwayEra)
 -> Identity (StrictSeq (TxOut ConwayEra)))
-> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra)
(StrictSeq (TxOut ConwayEra)
 -> Identity (StrictSeq (BabbageTxOut ConwayEra)))
-> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra)
forall era (l :: TxLevel).
EraTxBody era =>
Lens' (TxBody l era) (StrictSeq (TxOut era))
forall (l :: TxLevel).
Lens' (TxBody l ConwayEra) (StrictSeq (TxOut ConwayEra))
outputsTxBodyL
                    ((StrictSeq (TxOut ConwayEra)
  -> Identity (StrictSeq (BabbageTxOut ConwayEra)))
 -> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra))
-> StrictSeq (BabbageTxOut ConwayEra)
-> TxBody TopTx ConwayEra
-> TxBody TopTx ConwayEra
forall s t a b. ASetter s t a b -> b -> s -> t
.~ [BabbageTxOut ConwayEra] -> StrictSeq (BabbageTxOut ConwayEra)
forall a. [a] -> StrictSeq a
StrictSeq.fromList
                        [ BabbageTxOut ConwayEra
refOut
                        , Addr -> Value ConwayEra -> TxOut ConwayEra
forall era.
(EraTxOut era, HasCallStack) =>
Addr -> Value era -> TxOut era
mkBasicTxOut Addr
payerAddr (Coin -> MultiAsset -> MaryValue
MaryValue (Integer -> Coin
Coin Integer
changeCoin) MultiAsset
forall a. Monoid a => a
mempty)
                        ]
                TxBody TopTx ConwayEra
-> (TxBody TopTx ConwayEra -> TxBody TopTx ConwayEra)
-> TxBody TopTx ConwayEra
forall a b. a -> (a -> b) -> b
& (Coin -> Identity Coin)
-> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra)
forall era. EraTxBody era => Lens' (TxBody TopTx era) Coin
Lens' (TxBody TopTx ConwayEra) Coin
feeTxBodyL ((Coin -> Identity Coin)
 -> TxBody TopTx ConwayEra -> Identity (TxBody TopTx ConwayEra))
-> Coin -> TxBody TopTx ConwayEra -> TxBody TopTx ConwayEra
forall s t a b. ASetter s t a b -> b -> s -> t
.~ Integer -> Coin
Coin Integer
publicationFee
    pure (mkBasicTx body, refOut)

{- | Publish the state validator as a reference output, once, before any
boot (#177).

A registry boots only by reference: the boot resolves the state
validator through a publication in the payer's wallet and is refused
`StateValidatorNotPublished` without one, because that validator is
fifteen kilobytes against a sixteen-kilobyte transaction cap. A session
calls this before its first boot.

Idempotent by discovery: a wallet that already holds the publication
gets it back rather than a second one, so a harness that boots several
cages publishes once.
-}
publishStateRef
    :: CageConfig
    -> (Cage.Network, Cage.LedgerProvider Cage.NoWitness IO)
    -> SubmitSigned
    -> Addr
    -> IO (TxIn, TxOut ConwayEra)
publishStateRef :: CageConfig
-> (Network, LedgerProvider NoWitness IO)
-> SubmitSigned
-> Addr
-> IO (TxIn, TxOut ConwayEra)
publishStateRef = Set TxIn
-> CageConfig
-> (Network, LedgerProvider NoWitness IO)
-> SubmitSigned
-> Addr
-> IO (TxIn, TxOut ConwayEra)
publishStateRefReserving Set TxIn
forall a. Set a
Set.empty

{- | 'publishStateRef', never spending a reserved output (#299): an
existing publication is returned as before, and a new one is funded
outside the reservation.
-}
publishStateRefReserving
    :: Set.Set TxIn
    -> CageConfig
    -> (Cage.Network, Cage.LedgerProvider Cage.NoWitness IO)
    -> SubmitSigned
    -> Addr
    -> IO (TxIn, TxOut ConwayEra)
publishStateRefReserving :: Set TxIn
-> CageConfig
-> (Network, LedgerProvider NoWitness IO)
-> SubmitSigned
-> Addr
-> IO (TxIn, TxOut ConwayEra)
publishStateRefReserving Set TxIn
reserved CageConfig
cfg (Network, LedgerProvider NoWitness IO)
prov SubmitSigned
submit Addr
payerAddr = do
    let script :: Script ConwayEra
script = CageConfig -> Script ConwayEra
mkCageScript CageConfig
cfg
    utxos <- (Network, LedgerProvider NoWitness IO)
-> (Session NoWitness IO -> IO [(TxIn, TxOut ConwayEra)])
-> IO [(TxIn, TxOut ConwayEra)]
forall w a.
(Network, LedgerProvider w IO) -> (Session w IO -> IO a) -> IO a
Cage.withLatest (Network, LedgerProvider NoWitness IO)
prov (Session NoWitness IO -> Addr -> IO [(TxIn, TxOut ConwayEra)]
forall w. Session w IO -> Addr -> IO [(TxIn, TxOut ConwayEra)]
`Cage.outputsAt` Addr
payerAddr)
    case stateRefIn cfg utxos of
        Just (TxIn, TxOut ConwayEra)
u -> (TxIn, BabbageTxOut ConwayEra) -> IO (TxIn, BabbageTxOut ConwayEra)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (TxIn, TxOut ConwayEra)
(TxIn, BabbageTxOut ConwayEra)
u
        Maybe (TxIn, TxOut ConwayEra)
Nothing -> Set TxIn
-> (Network, LedgerProvider NoWitness IO)
-> SubmitSigned
-> Addr
-> Script ConwayEra
-> IO (TxIn, TxOut ConwayEra)
publishRefScriptReserving Set TxIn
reserved (Network, LedgerProvider NoWitness IO)
prov SubmitSigned
submit Addr
payerAddr AlonzoScript ConwayEra
Script ConwayEra
script

-- | An output among these that publishes this cage's state validator.
stateRefIn
    :: CageConfig
    -> [(TxIn, TxOut ConwayEra)]
    -> Maybe (TxIn, TxOut ConwayEra)
stateRefIn :: CageConfig
-> [(TxIn, TxOut ConwayEra)] -> Maybe (TxIn, TxOut ConwayEra)
stateRefIn CageConfig
cfg [(TxIn, TxOut ConwayEra)]
utxos =
    case [ (TxIn, BabbageTxOut ConwayEra)
u
         | u :: (TxIn, BabbageTxOut ConwayEra)
u@(TxIn
_, BabbageTxOut ConwayEra
out) <- [(TxIn, TxOut ConwayEra)]
[(TxIn, BabbageTxOut ConwayEra)]
utxos
         , SJust Script ConwayEra
s <- [BabbageTxOut ConwayEra
out BabbageTxOut ConwayEra
-> Getting
     (StrictMaybe (Script ConwayEra))
     (BabbageTxOut ConwayEra)
     (StrictMaybe (Script ConwayEra))
-> StrictMaybe (Script ConwayEra)
forall s a. s -> Getting a s a -> a
^. (StrictMaybe (Script ConwayEra)
 -> Const
      (StrictMaybe (Script ConwayEra)) (StrictMaybe (Script ConwayEra)))
-> TxOut ConwayEra
-> Const (StrictMaybe (Script ConwayEra)) (TxOut ConwayEra)
Getting
  (StrictMaybe (Script ConwayEra))
  (BabbageTxOut ConwayEra)
  (StrictMaybe (Script ConwayEra))
forall era.
BabbageEraTxOut era =>
Lens' (TxOut era) (StrictMaybe (Script era))
Lens' (TxOut ConwayEra) (StrictMaybe (Script ConwayEra))
referenceScriptTxOutL]
         , Script ConwayEra -> ScriptHash
forall era. EraScript era => Script era -> ScriptHash
hashScript Script ConwayEra
s ScriptHash -> ScriptHash -> Bool
forall a. Eq a => a -> a -> Bool
== Script ConwayEra -> ScriptHash
forall era. EraScript era => Script era -> ScriptHash
hashScript (CageConfig -> Script ConwayEra
mkCageScript CageConfig
cfg)
         ] of
        ((TxIn, BabbageTxOut ConwayEra)
u : [(TxIn, BabbageTxOut ConwayEra)]
_) -> (TxIn, BabbageTxOut ConwayEra)
-> Maybe (TxIn, BabbageTxOut ConwayEra)
forall a. a -> Maybe a
Just (TxIn, BabbageTxOut ConwayEra)
u
        [] -> Maybe (TxIn, TxOut ConwayEra)
Maybe (TxIn, BabbageTxOut ConwayEra)
forall a. Maybe a
Nothing