-
Notifications
You must be signed in to change notification settings - Fork 44
/
Run.hs
537 lines (500 loc) · 28.3 KB
/
Run.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
-----------------------------------------------------------------------------
--
-- Module : $Headers
-- License : Apache 2.0
--
-- Stability : Experimental
-- Portability : Portable
--
-- | Run Marlowe contracts.
--
-----------------------------------------------------------------------------
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
module Language.Marlowe.CLI.Run (
-- * Computation
initializeTransaction
, initializeTransactionImpl
, prepareTransaction
, prepareTransactionImpl
, makeMarlowe
, runTransaction
-- * Roles
, withdrawFunds
-- * Input
, makeDeposit
, makeChoice
, makeNotification
) where
import Cardano.Api (AddressAny, AddressInEra (..), BabbageEra, CardanoMode, Key (deterministicSigningKeySeedSize),
LocalNodeConnectInfo (localNodeNetworkId), MultiAssetSupportedInEra (MultiAssetInBabbageEra),
NetworkId, QueryInShelleyBasedEra (QueryProtocolParameters, QueryUTxO),
QueryUTxOFilter (QueryUTxOByAddress), Script (..), ScriptDataSupportedInEra (..),
ShelleyBasedEra (ShelleyBasedEraBabbage), SlotNo (..), StakeAddressReference (..), TxId, TxIn,
TxMintValue (TxMintNone), TxOut (..), TxOutDatum (..), TxOutValue (..), UTxO (..),
anyAddressInShelleyBasedEra, calculateMinimumUTxO, getTxId, lovelaceToValue, selectLovelace,
toAddressAny, txOutValueToValue, writeFileTextEnvelope)
import qualified Cardano.Api as Api (Value)
import qualified Cardano.Api as Cardano.Api.TxBody
import Cardano.Api.Shelley (ProtocolParameters, ReferenceScript (ReferenceScriptNone), fromPlutusData)
import Cardano.Ledger.Core (TxBody)
import Control.Monad (forM_, guard, unless, when)
import Control.Monad.Except (MonadError, MonadIO, catchError, liftIO, throwError)
import Data.Bifunctor (bimap)
import Data.Function (on)
import Data.List (groupBy, sortBy)
import qualified Data.Map.Strict as M (toList)
import Data.Maybe (catMaybes, fromMaybe)
import qualified Data.Set as S (singleton)
import GHC.IO.Handle.Types (Handle__)
import Language.Marlowe.CLI.Export (buildDatum, buildRedeemer, buildRoleDatum, buildRoleRedeemer, buildRoleValidator,
buildValidator)
import Language.Marlowe.CLI.IO (decodeFileStrict, liftCli, liftCliIO, maybeWriteJson, readMaybeMetadata, readSigningKey)
import Language.Marlowe.CLI.Merkle (merkleizeInputs, merkleizeMarlowe)
import Language.Marlowe.CLI.Orphans ()
import Language.Marlowe.CLI.Transaction (buildBody, buildPayFromScript, buildPayToScript, hashSigningKey, queryBabbage,
submitBody)
import Language.Marlowe.CLI.Types (CliError (..), DatumInfo (..), MarloweTransaction (..), RedeemerInfo (..),
SomePaymentSigningKey, ValidatorInfo (..))
import Language.Marlowe.Core.V1.Semantics (MarloweParams (rolesCurrency), Payment (..), TransactionInput (..),
TransactionOutput (..), TransactionWarning, computeTransaction)
import Language.Marlowe.Core.V1.Semantics.Types (AccountId, ChoiceId (..), ChoiceName, ChosenNum, Contract, Input (..),
InputContent (..), Party (..), Payee (..), State (accounts),
Token (..))
import Language.Marlowe.Scripts (marloweTxInputFromInput)
import Ledger.Tx.CardanoAPI (toCardanoAddressInEra, toCardanoScriptDataHash, toCardanoValue)
import Network.WebSockets.Connection (ConnectionOptions (connectionCompressionOptions))
import Plutus.V1.Ledger.Ada (adaSymbol, adaToken, fromValue, getAda)
import Plutus.V1.Ledger.Api (Address (..), CostModelParams, Credential (..), Datum (..), POSIXTime, TokenName,
toBuiltinData, toData)
import Plutus.V1.Ledger.SlotConfig (SlotConfig, posixTimeToEnclosingSlot)
import Plutus.V1.Ledger.Value (AssetClass (..), Value (..), assetClassValue)
import qualified PlutusTx.AssocMap as AM (toList)
import Prettyprinter.Extras (Pretty (..))
import System.IO (hPutStrLn, stderr)
-- | Serialise a deposit input to a file.
makeDeposit :: MonadIO m
=> AccountId -- ^ The account for the deposit.
-> Party -- ^ The party making the deposit.
-> Maybe Token -- ^ The token being deposited.
-> Integer -- ^ The amount of the token deposited.
-> Maybe FilePath -- ^ The output JSON file representing the input.
-> m () -- ^ Action to write the input to the file.
makeDeposit accountId party token amount outputFile =
maybeWriteJson outputFile
. NormalInput
$ IDeposit accountId party (fromMaybe (Token adaSymbol adaToken) token) amount
-- | Serialise a choice input to a file.
makeChoice :: MonadIO m
=> ChoiceName -- ^ The name of the choice made.
-> Party -- ^ The party making the choice.
-> ChosenNum -- ^ The number chosen.
-> Maybe FilePath -- ^ The output JSON file representing the input.
-> m () -- ^ Action to write the input to the file.
makeChoice name party chosen outputFile =
maybeWriteJson outputFile
. NormalInput
$ IChoice (ChoiceId name party) chosen
-- | Serialise a notification input to a file.
makeNotification :: MonadIO m
=> Maybe FilePath -- ^ The output JSON file representing the input.
-> m () -- ^ Action to write the input to the file.
makeNotification outputFile =
maybeWriteJson outputFile
$ NormalInput INotify
-- | Create an initial Marlowe transaction.
initializeTransaction :: MonadError CliError m
=> MonadIO m
=> MarloweParams -- ^ The Marlowe contract parameters.
-> SlotConfig -- ^ The POSIXTime-to-slot configuration.
-> CostModelParams -- ^ The cost model parameters.
-> NetworkId -- ^ The network ID.
-> StakeAddressReference -- ^ The stake address.
-> FilePath -- ^ The JSON file containing the contract.
-> FilePath -- ^ The JSON file containing the contract's state.
-> Maybe FilePath -- ^ The output JSON file for the validator information.
-> Bool -- ^ Whether to deeply merkleize the contract.
-> Bool -- ^ Whether to print statistics about the validator.
-> m () -- ^ Action to export the validator information to a file.
initializeTransaction marloweParams slotConfig costModelParams network stake contractFile stateFile outputFile merkleize printStats =
do
contract <- decodeFileStrict contractFile
state <- decodeFileStrict stateFile
marloweTransaction <- initializeTransactionImpl
marloweParams slotConfig costModelParams network stake
contract state
merkleize
printStats
maybeWriteJson outputFile marloweTransaction
-- | Create an initial Marlowe transaction.
initializeTransactionImpl :: MonadError CliError m
=> MonadIO m
=> MarloweParams -- ^ The Marlowe contract parameters.
-> SlotConfig -- ^ The POSIXTime-to-slot configuration.
-> CostModelParams -- ^ The cost model parameters.
-> NetworkId -- ^ The network ID.
-> StakeAddressReference -- ^ The stake address.
-> Contract -- ^ The initial Marlowe contract.
-> State -- ^ The initial Marlowe state.
-> Bool -- ^ Whether to deeply merkleize the contract.
-> Bool -- ^ Whether to print statistics about the validator.
-> m (MarloweTransaction BabbageEra) -- ^ Action to return a MarloweTransaction
initializeTransactionImpl marloweParams mtSlotConfig costModelParams network stake mtContract mtState merkleize printStats =
do
let
mtRoles = rolesCurrency marloweParams
mtValidator <- liftCli $ buildValidator marloweParams costModelParams network stake
mtRoleValidator <- liftCli $ buildRoleValidator mtRoles costModelParams network stake
let
ValidatorInfo{..} = mtValidator :: ValidatorInfo BabbageEra -- FIXME: Generalize eras.
mtContinuations = mempty
mtRange = Nothing
mtInputs = []
mtPayments = []
liftIO
$ when printStats
$ do
hPutStrLn stderr ""
hPutStrLn stderr $ "Validator size: " <> show viSize
hPutStrLn stderr $ "Base-validator cost: " <> show viCost
let marloweTransaction = MarloweTransaction{..}
pure $ if merkleize then merkleizeMarlowe marloweTransaction else marloweTransaction
-- | Prepare the next step in a Marlowe contract.
prepareTransaction :: MonadError CliError m
=> MonadIO m
=> FilePath -- ^ The JSON file with the Marlowe initial state and initial contract.
-> [Input] -- ^ The contract's inputs.
-> POSIXTime -- ^ The first valid time for the transaction.
-> POSIXTime -- ^ The last valid time for the transaction.
-> Maybe FilePath -- ^ The output JSON file with the results of the computation.
-> Bool -- ^ Whether to print statistics about the result.
-> m () -- ^ Action to compute the next step in the contract.
prepareTransaction marloweFile txInputs minimumTime maximumTime outputFile printStats =
do
marloweIn <- decodeFileStrict marloweFile
marloweOut <- prepareTransactionImpl marloweIn txInputs minimumTime maximumTime printStats
maybeWriteJson outputFile marloweOut
-- | Implementation of Prepare function
prepareTransactionImpl :: MonadError CliError m
=> MonadIO m
=> MarloweTransaction BabbageEra -- ^ Marlowe transaction to be prepared.
-> [Input] -- ^ The contract's inputs.
-> POSIXTime -- ^ The first valid time for the transaction.
-> POSIXTime -- ^ The last valid time for the transaction.
-> Bool -- ^ Whether to print statistics about the result.
-> m (MarloweTransaction BabbageEra) -- ^ Action to compute the next step in the contract.
prepareTransactionImpl marloweIn txInputs minimumTime maximumTime printStats =
do
let
txInterval = (minimumTime, maximumTime)
(warnings, marloweOut@MarloweTransaction{..}) <-
makeMarlowe
(marloweIn :: MarloweTransaction BabbageEra) -- FIXME: Generalize eras.
(TransactionInput txInterval txInputs)
liftIO
$ do
when printStats
$ do
hPutStrLn stderr ""
unless (null warnings)
$ do
hPutStrLn stderr "Warnings:"
forM_ warnings
$ hPutStrLn stderr . (" " <>) . show
hPutStrLn stderr $ "Datum size: " <> show (diSize $ buildDatum mtContract mtState)
sequence_
[
do
putStrLn $ "Payment " <> show (i :: Int)
putStrLn $ " Acccount: " <> show accountId
putStrLn $ " Payee: " <> show payee
putStrLn $ " Ada: " <> show (getAda $ fromValue money)
sequence_
[
hPutStrLn stderr $ " " <> show (pretty symbol) <> "." <> show (pretty token) <> ": " <> show amount
|
(symbol, tokenAmounts) <- AM.toList $ getValue money
, symbol /= adaSymbol
, (token, amount) <- AM.toList tokenAmounts
]
|
(i, Payment accountId payee money) <- zip [1..] mtPayments
]
pure marloweOut
-- | Prepare the next step in a Marlowe contract.
makeMarlowe :: MonadError CliError m
=> MarloweTransaction era -- ^ The Marlowe initial state and initial contract.
-> TransactionInput -- ^ The transaction input.
-> m ([TransactionWarning], MarloweTransaction era) -- ^ Action to compute the next step in the contract.
makeMarlowe marloweIn@MarloweTransaction{..} transactionInput =
do
transactionInput'@TransactionInput{..} <-
merkleizeInputs marloweIn transactionInput
`catchError` (const $ pure transactionInput) -- TODO: Consider not catching errors here.
case computeTransaction transactionInput' mtState mtContract of
Error message -> throwError . CliError . show $ message
TransactionOutput{..} -> pure
(
txOutWarnings
, marloweIn
{
mtState = txOutState
, mtContract = txOutContract
, mtRange = Just $ bimap convertSlot convertSlot txInterval
, mtInputs = txInputs
, mtPayments = txOutPayments
}
)
where
convertSlot = SlotNo . fromIntegral . posixTimeToEnclosingSlot mtSlotConfig
-- | Run a Marlowe transaction.
runTransaction :: MonadError CliError m
=> MonadIO m
=> LocalNodeConnectInfo CardanoMode -- ^ The connection info for the local node.
-> Maybe (FilePath, TxIn, TxIn) -- ^ The JSON file with the Marlowe initial state and initial contract, along with the script eUTxO being spent and the collateral, unless the transaction opens the contract.
-> FilePath -- ^ The JSON file with the Marlowe inputs, final state, and final contract.
-> [TxIn] -- ^ The transaction inputs.
-> [(AddressAny, Maybe Datum, Api.Value)] -- ^ The transaction outputs.
-> AddressAny -- ^ The change address.
-> [FilePath] -- ^ The files for required signing keys.
-> Maybe FilePath -- ^ The file containing JSON metadata, if any.
-> FilePath -- ^ The output file for the transaction body.
-> Maybe Int -- ^ Number of seconds to wait for the transaction to be confirmed, if it is to be confirmed.
-> Bool -- ^ Whether to print statistics about the transaction.
-> Bool -- ^ Assertion that the transaction is invalid.
-> m TxId -- ^ Action to build the transaction body.
runTransaction connection marloweInBundle marloweOutFile inputs outputs changeAddress signingKeyFiles metadataFile bodyFile timeout printStats invalid =
do
metadata <- readMaybeMetadata metadataFile
marloweOut <- decodeFileStrict marloweOutFile
signingKeys <- mapM readSigningKey signingKeyFiles
body <- runTransactionImpl
connection
marloweInBundle
marloweOut
inputs
outputs
changeAddress
signingKeys
metadata
timeout
printStats
invalid
liftCliIO
$ writeFileTextEnvelope bodyFile Nothing body
pure
$ getTxId body
-- | Run a Marlowe transaction.
runTransactionImpl :: MonadError CliError m
=> MonadIO m
=> LocalNodeConnectInfo CardanoMode -- ^ The connection info for the local node.
-> Maybe (FilePath, TxIn, TxIn) -- ^ The JSON file with the Marlowe initial state and initial contract, along with the script eUTxO being spent and the collateral, unless the transaction opens the contract.
-> MarloweTransaction BabbageEra -- ^ The JSON file with the Marlowe inputs, final state, and final contract.
-> [TxIn] -- ^ The transaction inputs.
-> [(AddressAny, Maybe Datum, Api.Value)] -- ^ The transaction outputs.
-> AddressAny -- ^ The change address.
-> [Language.Marlowe.CLI.Types.SomePaymentSigningKey] -- ^ The files for required signing keys.
-> Cardano.Api.TxBody.TxMetadataInEra BabbageEra -- ^ The file containing JSON metadata, if any.
-> Maybe Int -- ^ Number of seconds to wait for the transaction to be confirmed, if it is to be confirmed.
-> Bool -- ^ Whether to print statistics about the transaction.
-> Bool -- ^ Assertion that the transaction is invalid.
-> m (TxBody BabbageEra) -- ^ Action to build the transaction body.
runTransactionImpl connection marloweInBundle marloweOut inputs outputs changeAddress signingKeys metadata timeout printStats invalid =
do
protocol <- queryBabbage connection QueryProtocolParameters
(spend, collateral, datumOutputs) <-
case marloweInBundle of
Nothing -> pure ([], Nothing, [])
Just (marloweInFile, spend, collateral) -> do
marloweIn <- decodeFileStrict marloweInFile
let
validatorInfo = mtValidator (marloweIn :: MarloweTransaction BabbageEra) -- FIXME: Generalize eras.
PlutusScript _ validator = viScript validatorInfo
redeemer = riRedeemer $ buildRedeemer (mtInputs marloweOut)
inputDatum = diDatum $ buildDatum (mtContract marloweIn) (mtState marloweIn)
spend' = buildPayFromScript validator inputDatum redeemer spend
-- SCP-3610: Remove when Babbage era features become available and the validator is revised.
merkles =
catMaybes
[
case input of
NormalInput _ -> Nothing
MerkleizedInput _ _ continuation -> Just
(
-- Send the ancillary datum to the change address.
changeAddress
-- Astonishing that this eUTxO can be spent without script or redeemer!
, Just . Datum $ toBuiltinData continuation
-- FIXME: Replace with protocol-dependent min-Ada.
, lovelaceToValue 1_500_000
)
|
input <- mtInputs marloweOut
]
pure ([spend'], Just collateral, merkles)
let
babbageToAddressAny' :: AddressInEra BabbageEra -> AddressAny
babbageToAddressAny' (AddressInEra _ address) = toAddressAny address
network = localNodeNetworkId connection
scriptAddress :: AddressInEra BabbageEra
scriptAddress = viAddress $ mtValidator marloweOut
scriptAddressInBabbage :: AddressInEra BabbageEra
scriptAddressInBabbage = anyAddressInShelleyBasedEra (babbageToAddressAny' scriptAddress)
outputDatum = diDatum $ buildDatum (mtContract marloweOut) (mtState marloweOut)
outputValue <-
mconcat
<$> sequence
[
liftCli . toCardanoValue $ assetClassValue (AssetClass (currency, name)) amount
|
((_, Token currency name), amount) <- AM.toList . accounts $ mtState marloweOut
]
let
continue =
do
guard (outputValue /= mempty)
pure
$ buildPayToScript scriptAddressInBabbage outputValue outputDatum
roleAddress = viAddress $ mtRoleValidator marloweOut :: AddressInEra BabbageEra
payments <-
catMaybes
<$> sequence
[
case payee of
Party (PK pkh) -> do
address <-
liftCli
. toCardanoAddressInEra network
$ Address (PubKeyCredential pkh) Nothing
money' <-
liftCli
$ toCardanoValue money
money'' <- adjustMinimumUTxO protocol address Nothing money'
pure $ Just (babbageToAddressAny' address, Nothing, money'')
Party (Role role) -> do
money' <-
liftCli
$ toCardanoValue money
let
datum = Just . diDatum $ buildRoleDatum role
money'' <- adjustMinimumUTxO protocol roleAddress datum money'
pure $ Just (babbageToAddressAny' roleAddress, datum, money'')
Account _ -> pure Nothing
|
(payee, money) <- bimap head mconcat . unzip
<$> (groupBy ((==) `on` fst) . sortBy (compare `on` fst))
[
(payee, money)
| Payment _ payee money <- mtPayments marloweOut
]
]
let
outputs' = payments <> outputs <> datumOutputs
body <-
buildBody connection
spend continue
[] inputs outputs'
collateral changeAddress
(mtRange marloweOut)
(hashSigningKey <$> signingKeys)
TxMintNone
metadata
printStats
invalid
forM_ timeout
$ if invalid
then const $ throwError "Refusing to submit an invalid transaction: collateral would be lost."
else submitBody connection body signingKeys
pure body
-- | Adjust the lovelace in an output to confirm to the minimum ADA requirement.
adjustMinimumUTxO :: MonadError CliError m
=> ProtocolParameters -- ^ The protocol parameters.
-> AddressInEra BabbageEra -- ^ The output address.
-> Maybe Datum -- ^ The datum, if any.
-> Api.Value -- ^ The output value.
-> m Api.Value -- ^ Action to compute the adjusted value.
adjustMinimumUTxO protocol address datum value =
do
let
txOut =
TxOut
address
(TxOutValue MultiAssetInBabbageEra value)
(maybe TxOutDatumNone (TxOutDatumInTx ScriptDataInBabbageEra . fromPlutusData . toData) datum)
ReferenceScriptNone
minValue <- liftCli $ calculateMinimumUTxO ShelleyBasedEraBabbage txOut protocol
let
minLovelace = selectLovelace minValue
deficit = minLovelace <> negate (minimum[selectLovelace value, minLovelace])
pure
$ value <> lovelaceToValue deficit
-- | Withdraw funds for a specific role from the role address.
withdrawFunds :: MonadError CliError m
=> MonadIO m
=> LocalNodeConnectInfo CardanoMode -- ^ The connection info for the local node.
-> FilePath -- ^ The JSON file with the Marlowe state and contract.
-> TokenName -- ^ The role name for the redemption.
-> TxIn -- ^ The collateral.
-> [TxIn] -- ^ The transaction inputs.
-> [(AddressAny, Maybe Datum, Api.Value)] -- ^ The transaction outputs.
-> AddressAny -- ^ The change address.
-> [FilePath] -- ^ The files for required signing keys.
-> Maybe FilePath -- ^ The file containing JSON metadata, if any.
-> FilePath -- ^ The output file for the transaction body.
-> Maybe Int -- ^ Number of seconds to wait for the transaction to be confirmed, if it is to be confirmed.
-> Bool -- ^ Whether to print statistics about the transaction.
-> Bool -- ^ Assertion that the transaction is invalid.
-> m TxId -- ^ Action to build the transaction body.
withdrawFunds connection marloweOutFile roleName collateral inputs outputs changeAddress signingKeyFiles metadataFile bodyFile timeout printStats invalid =
do
metadata <- readMaybeMetadata metadataFile
marloweOut <- decodeFileStrict marloweOutFile
signingKeys <- mapM readSigningKey signingKeyFiles
roleHash <- liftCli . toCardanoScriptDataHash . diHash $ buildRoleDatum roleName
let
toAddressAny' :: AddressInEra BabbageEra -> AddressAny
toAddressAny' (AddressInEra _ address) = toAddressAny address
validatorInfo = mtRoleValidator marloweOut
PlutusScript _ roleScript = viScript validatorInfo
roleAddress = viAddress validatorInfo :: AddressInEra BabbageEra
roleDatum = diDatum $ buildRoleDatum roleName
roleRedeemer = riRedeemer buildRoleRedeemer
checkRole (TxOut _ _ datum _) =
case datum of
TxOutDatumInline _ _ -> False
TxOutDatumNone -> False
TxOutDatumHash _ datumHash -> datumHash == roleHash
utxos <-
fmap (filter (checkRole . snd) . M.toList . unUTxO)
. queryBabbage connection
. QueryUTxO
. QueryUTxOByAddress
. S.singleton
. toAddressAny'
$ roleAddress
let
spend = buildPayFromScript roleScript roleDatum roleRedeemer . fst <$> utxos
withdrawal = (changeAddress, Nothing, mconcat [txOutValueToValue value | (_, TxOut _ value _ _) <- utxos])
outputs' = withdrawal : outputs
body <-
buildBody connection
spend Nothing
[] inputs outputs'
(Just collateral) changeAddress
(mtRange marloweOut)
(hashSigningKey <$> signingKeys)
TxMintNone
metadata
printStats
invalid
liftCliIO
$ writeFileTextEnvelope bodyFile Nothing body
forM_ timeout
$ if invalid
then const $ throwError "Refusing to submit an invalid transaction: collateral would be lost."
else submitBody connection body signingKeys
pure
$ getTxId body