Skip to content
This repository was archived by the owner on Dec 2, 2024. It is now read-only.

Commit 7f2d304

Browse files
sjoerdvisscherzliu41berewtEvgenii Akentevkoslambrou
authored
PLT-774: Collateral output (#740)
* Update the contributing guide (#729) * next-node is the new merge (ends PLT-558) (#745) * SCP-3855: update node dep (#449) * Update Cardano node et al. dependencies for the Vasil HF * The Cardano node version will only work on a network with the Vasil release. * Solve some compile issues * wip: recovering instances for types from plutus-ledger-api * wip * plutus-ledger compiles * plutus-ledger-constraints compiles * Fixed warnings in Ledger.Tx.CardanoAPI for fields introduced by the Babbage era. Also adapted hashing functions for PlutusV1 scripts to work on PlutusV2 * Fixed warnings in Ledger.Tx.CardanoAPITemp and added implementation to undefined value * plutus-contract compiles * Added alonzoGenesisDefaults implementation (copied from cardano-node because it was deleted over there) to Ledger.Validation * plutus-chain-index-core compiles * Fixed compilation errors in playground-common and plutus-contract * Fix compile errors in plutus-example * Fix compile errors in plutus-pab * Fix compile errors in plutus-playground-server * WIP on plutus-use-cases * Split Tx.Orphans into multiple Orphans * Fix compilation errors on plutus-use-cases * fix compilation issues * Update nix * fix formatting * Remove wrongly commited files * Update purescript modules * Commented test on plutus-ledger temporarely until cardano-node is updated * Update cardano-wallet with fixes for haddock * Fix plutus-playground-client purescript imports * Fix warnings in plutus-example * Fix plutus-uniswap cabal * Try to turn-off haddock for cardano-wallet * [plutus-contract]: fix golden tests and commented test until cardano-node is updated * Add cardano-cli/.../genesis.alonzo.spec.json to fix plutus-example * Fix comment link to PR * Comment out the test properly * Update scripts/protocol-parameters with fresh plutusV1 cost parameters Co-authored-by: Konstantinos Lambrou-Latreille <konstantinos.lambrou@iohk.io> * [chain-index]: export all servant client functions (#492) * Fix playground client * Fix streaming * Fix purescript * Create separate directories for v1 and v2 plutus scripts (#486) * Reorganize the plutus-example library to distinguish clearly between V1 and V2 scripts. * plutus-example reorganization create v2 example script * Modify the ScriptContextChecker module to be more generic * Propagate the changes to the plutus-example apps and tests * Update required-redeemer.plutus to also check for an inline datum of 42 and to check for an inline datum of 42 in the reference inputs * Add PlutusV2 minting and staking scripts (#528) * [chain-index]: add inline datums support and update cardano-node (#488) * PLT-484 Upgraded cardano-node version to the official 1.35.0 release. (#551) * Also upgraded cardano-wallet, plutus et al. versions that work with v1.35.0 of the node. * Updated golden tests in plutus-use-cases and plutus-contract * Updated version of components to 1.0.0 with cardano-node (#560) * Updated the cardano-node bundled with plutus-apps to v1.35.0 * Updated version of all components in their respective cabal files to 1.0.0 * Update cardano-node dependency to 1.35.1 * Updated cardano-wallet, plutus and cardano-ledger to match the node version. * Add script equivalence context test for the V2 context. (#588) * Remove withIsCardanoEra workaround. (#607) * BlockInMode now carries a IsCardanoEra constraint * Increase the delay of awaiting in plutus-pab-executables tests (#565) Set slot's length to 1s for awaiting tx/out status tests to make them stable * [PLT-81] plutus-chain-index: support inline scripts when querying TxOut of a TxOutRef (#613) * Make plutus-ledger-api version explicit in Ledger.Tx * Make pattern match explicit * Reorder ScriptChainIndexTxOut fields To highlight they are the same as PublicKeyChainIndexTxOut. * Add datum to both branches of ChainIndexTxOut - Unfortunately we need to rename the fields because they have now different types. - In the PublicKeyChainIndexTxOut case, the output datum is optional and we can use plutus-ledger-api OutputDatum type. - In the ScriptChainIndexTxOut case, the output datum is required, nothing changes here but the name. * Add ReferenceScript to ChainIndexTxOut * Remove old comment * Rename _ciTxOutDatumPublicKey and _ciTxOutDatumScript into _ciTxOutPublicKeyDatum and _ciTxOutScriptDatum * Introduce fromReferenceScript * Add comments to ChainIndexTxOut * Add minting context equivalent test plutus script (#631) * Add missing record field `localTxMonitoringClient` (#617) * PLT-568: Switch to Babbage era (#614) * Make Babbage the default era for the emulator * Clean up * Accept changes in test output * Workaround for parseBabbageEraInCardanoModeTx * Fix minAda calculation * [next-node]: Bump wallet, plutus, ledger, node (#616) * Bump cardano-node to 1.35.2 and rest of dependencies based on cardano-wallet * Use '[TxIn]' instead of 'Set TxIn' in 'data Tx' (#623) * [plutus-ledger]: Use '[TxIn]' instead of 'Set TxIn' in 'data Tx'. * Add a property test to check Ord instances of TxIn. * Sort the inputs in fromOnChainTx * Sort the inputs in `Emulator.Wallet` * Fix the review notes and the problem with getInput in StateMachine tests * PLT-445 Add `mustReferencePubKeyOutput` in constraints library (#640) * PLT-445 Add mustReferencePubKeyOutput in constraints library * Added the mustReferencePubKeyOutput constraint in plutus-ledger-constraints * Added a test case for the mustReferencePubKeyOutput * Refactored Ledger.Tx.CardanoAPI to work with PlutusV2 alongside PlutusV1 scripts in the tx inputs. * Use existing unitRedeemer * Move TxIn and TxInType to Ledger.Tx * Add plutus version to ConsumeScriptAddress constructor * Add costModelParams for PlutusScriptV2 * Fix error codes. * Renamed mkTxInfo to mkPV1TxInfo, added test for plutus-tx-constraints without implementation and commented for now the off-chain validation in Ledger.Index * Implement reference inputs in makeTransactionBody' * Fixed failing test cases for Ledger.Constraints.mustReferencePubKeyOutput * Add MustUseOutputAsCollateral * Fix V2 tests. But issues with V1 tests. * Disable tests * WIP * Remove unused code * PR feedback * Remove unused code. * Clean up * Added additional info in TODO * Add Arbitrary instances * Convert plutus-ledger-constraint tests to PV2 * Fixed test in plutus-ledger-constraints * Fixed PS generator error in playground * Fix build * Fix PS * Fix PS * More support of plutus version in constraints libs * Default to PlutusV1 for now Co-authored-by: Sjoerd Visscher <sjoerd.visscher@tweag.io> Co-authored-by: Sjoerd Visscher <sjoerd.visscher@iohk.io> * Update cardano-node to 1.35.3-rc1 with deps (#647) * Upgraded to a cardano-wallet compatible with node 1.35.3-rc1 (#657) * Reorganized dependencies based on cardano-wallet's cabal.project * Added the new 'protocolParamUTxOCostPerByte' in 'Ledger.Params' which replaces 'protocolParamUTxOCostPerWord' * Fixed the `Plutus.Contract.Wallet.mkMintingRedeemers` which triggered an error if the redeemers in the tx contained spending redeemers. * Simplify MustReferencePubKeyOutput to MustReferenceOutput (#661) * Replace LedgerPlutusVersion with Language type (#662) * PLT-494: PlutusV2 TypedValidators (#666) * Move common code to Plutus.Script.Utils.Typed * Enable V2 TypedValidators * Enable and fix reference output tests * Update cardano-node 1.35.3-rc1 -> 1.35.3 (#669) * PLT-448: inline scripts in constraint libraries (#678) * Add inline script support to plutus-tx-constraints. * Add mustOutputInlineValidator and mustOutputInlineMintingPolicy * Add documentation * Check there's no inline script in V1 * Fix wrong minAdaTxOut use * Update renderGuess.txt * Naming * PLT-738: Include plutus language versions with scripts (#681) * Store Plutus language versions in chain-index * Introduce Versioned scripts Remove openapi3 as a dependency of plutus-script-utils * Add hashing for versioned scripts * PLT-454: mustUseOutputAsCollateral (#690) * Finish mustUseOutputAsCollateral implementation * Add testcase * Add documentation * Add missing fields to Ledger.Tx.Internal.Tx (#468) Add missing fields to Ledger.Tx.Internal.Tx. * Add certificates and withdrawals to Tx. * Move script witnesses to txScripts. * Modify TxIn type, rename to TxInput. * Put redeemers together with minting scripts. * Translate withdrawals in toCardanoTxBody. * Export redeemers for signing with wallet. * Add tests for mustIncludeDatum tx constraint (#700) * Add tests for mustIncludeDatum tx constraint (3 failing tests need fix) * run checks * Add tests for MustPayToPubKeyAddress tx constraint (#701) * Add tests for mustSpendScriptOutput and mustSpendScriptOutputWithMatchingDatumAndValue tx constraints (#706) * Add tests for mustSpendScriptOutput and mustSpendScriptOutputWithMatchingDatumAndValue tx constraints * Fixed the 'Ledger.Constraints.OffChain.typedValidatorLookups' lookup function so that it adds the validator inside the 'TypedValidator' in the 'slOtherScripts' lookup value. Co-authored-by: Konstantinos Lambrou-Latreille <konstantinos.lambrou@iohk.io> * plutus-contract emulator: Change the tx output representation of EmulatorTx to use Cardano.Api.TxOut (#698) * First draft done for plutus-ledger * plutus-ledger-constraints use Cardano.Tx * use C.Tx in plutus-tx-constraints * plutus-chain-index uses C.TxOut * Forgot to add file * Fixing my mess with CardanoAPI * encoding via plutus.TxOut (can't work, no NetworkId) * Fix code for the use cases * Fix a bug in balanceTx * Fix 0 ada outputs error * Dirty fix for the uniswap check * Use Cardano.Tx txId * fix uniswap test * Fix double satisfaction * Fix Marconi * Add TxOut typeclasses * Remove unused imports * Fix failing tests * Clean import * Fix pab * Fix golden values * Fix golden test * Fix more plutus packages * Rmove useless param from ChainIndex.Lib * Fik playground * Remove commented code * Include several fixes following Konstantinos' review * Add a Pretty TxOut and clean uniswap * Remove useless stuff in playground * error in generators display the original cause * Fix imports * prettier pretty * Fix golden tests * Fix uniswap * Fix golden tests * Restore deleted constraints * Integrate more Sjoerd's comments * Add tests for mustPayToOtherScript tx constraint (#710) * Add tests for mustPayToOtherScript tx constraint and 2 more for mustPayToPubKeyAddress * Fix failing test and reference two PLT tickets * Refactored MustMint tests to use minting policies and added tests for token burning (#719) * MustSpendScriptOutput and MustSpendScriptOutputWithMatchingDatumAndValue check the redeemer's presence (#723) * Add inline datum supports for mustPayToPubKey and mustPayToOtherScript (#721) * Incremental change for datum * Work but no inlining * First working inline datum with V2 * Add tests for inline datum * add smart constructors for inline datum * fix PAB * fixing tx-constraints * clean up tests * Address some of Konstantinos' comments * Separate test group for plutus v2 * Refactor tests in MustPayToPubKeyAddress to ease version handling * Code clean up * Code clean up * Fix unused imports * Add a way to switch to cardano constraints in MustPayToOtherAddress tests * more clean up * PR feedbacks * Remove dead code * Add refactoring for MustPayToOtherScript tests * typo * clean test suites * Clean up imports * Fix some false-positives MustSpendScriptOutput tests using versioned minting policies (#725) * Fix some false-positives MustSpendScriptOutput tests and refactor to use minting policies * Use Versioned MintingPolicy and add tests for V2 scripts for MustSpendScriptOutput * Further refactoring * Improve onchain check for MustSpendScriptOutput and MustSpendScriptOutputWithMatchingDatumAndValue constraints * tidy up onchain check * PLT-448: must spend script output with reference (#716) * Add ownAddress (singular) * Support reference scripts in TxIn * Add mustSpendScriptOutputWithReference * Test using reference scripts * Fix merge issues * Direct conversion from ChainIndexTxOut to the new TxOut * Push Versioned inside Either * Accept test outputs * Fix reference script support in ledger-constraints * Fix comments * Add ownAddress (singular) * Support reference scripts in TxIn * Add mustSpendScriptOutputWithReference * Test using reference scripts * Fix merge issues * Direct conversion from ChainIndexTxOut to the new TxOut * Push Versioned inside Either * Accept test outputs * Fix reference script support in ledger-constraints * Fix comments * PR feedback * More PR feedback * Fix merge issues * PLT-807 Change behavior of MustPayToPubKeyAddress and MustPayToOtherScript w.r.t datum in transaction body (#705) * Changed `MustPayToPubKeyAddress` and `MustPayToOtherScript` so that the user needs to explicitly specify if he wants: * the datum to only be included as a hash in the transaction output * the datum to be included as a hash in the transaction output as well as in the transaction body * the datum to be inlined in the transaction output * Changed the name of the constraint `MustIncludeDatum` to `MustIncludeDatumInTx` and `MustHashDatum` to `MustIncludeDatumInTxWithHash`. These constraint don't modify the transaction anymore, but simply check that the datum is part of the transaction body. * Added a note on the 'Plutus.Contract.Oracle' module explaining why it doesn't work in it's current form. * Commented out failing test cases in `plutus-use-cases` that use the 'Plutus.Contract.Oracle' module. * PLT-511: collateral output in chain index (#730) * Add collateral output support to chain index * Generate invalid transactions in tests too * PR feedback * PLT-990 Removed Plutus.Contract.Wallet.finalize as we instead set the validity range of a transaction directly in `plutus-ledger-constraints` (since we now have access to the `SlotConfig`) (#741) * Update the contributing guide (#729) Co-authored-by: Evgenii Akentev <i@ak3n.com> Co-authored-by: Konstantinos Lambrou-Latreille <konstantinos.lambrou@iohk.io> Co-authored-by: Jordan Millar <jordan.millar@iohk.io> Co-authored-by: Andrea Bedini <andrea@andreabedini.com> Co-authored-by: Markus Läll <markus.lall@iohk.io> Co-authored-by: Sjoerd Visscher <sjoerd.visscher@tweag.io> Co-authored-by: Sjoerd Visscher <sjoerd.visscher@iohk.io> Co-authored-by: Jamie Bertram <jamie.bertram@tweag.io> Co-authored-by: Karol Ochman-Milarski <46135727+zmrocze@users.noreply.github.com> Co-authored-by: James <74595920+james-iohk@users.noreply.github.com> Co-authored-by: Ziyang Liu <unsafeFixIO@gmail.com> * Revert "next-node is the new merge (ends PLT-558) (#745)" (#746) This reverts commit dc3f549. * chore(deps): bump nixbuild/nix-quick-install-action from 17 to 18 (#743) Bumps [nixbuild/nix-quick-install-action](https://github.com/nixbuild/nix-quick-install-action) from 17 to 18. - [Release notes](https://github.com/nixbuild/nix-quick-install-action/releases) - [Changelog](https://github.com/nixbuild/nix-quick-install-action/blob/master/RELEASE) - [Commits](nixbuild/nix-quick-install-action@v17...v18) --- updated-dependencies: - dependency-name: nixbuild/nix-quick-install-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] <support@github.com> Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Add proper ToJSON instance for unit test results (#744) * Add collateral output fields * Add collateral balancing tests Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Ziyang Liu <unsafeFixIO@gmail.com> Co-authored-by: Nicolas B <nicolas.biri@iohk.io> Co-authored-by: Evgenii Akentev <i@ak3n.com> Co-authored-by: Konstantinos Lambrou-Latreille <konstantinos.lambrou@iohk.io> Co-authored-by: Jordan Millar <jordan.millar@iohk.io> Co-authored-by: Andrea Bedini <andrea@andreabedini.com> Co-authored-by: Markus Läll <markus.lall@iohk.io> Co-authored-by: Jamie Bertram <jamie.bertram@tweag.io> Co-authored-by: Karol Ochman-Milarski <46135727+zmrocze@users.noreply.github.com> Co-authored-by: James <74595920+james-iohk@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Ulf Norell <ulf.norell@gmail.com>
1 parent d4255f0 commit 7f2d304

File tree

28 files changed

+469
-349
lines changed

28 files changed

+469
-349
lines changed

.github/workflows/test.yml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ jobs:
99
runs-on: ${{ matrix.os }}
1010
steps:
1111
- uses: actions/checkout@v3
12-
- uses: nixbuild/nix-quick-install-action@v17
12+
- uses: nixbuild/nix-quick-install-action@v18
1313
- run: nix-instantiate release.nix --arg supportedSystems '[ builtins.currentSystem ]' --restrict-eval -I . --allowed-uris 'https://github.com/NixOS/nixpkgs https://github.com/input-output-hk https://github.com/NixOS/nixpkgs-channels' --option trusted-public-keys "hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= iohk.cachix.org-1:DpRUyj7h7V830dp/i6Nti+NEO2/nhblbov/8MW7Rqoo= cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=" --option substituters "https://hydra.iohk.io https://iohk.cachix.org https://cache.nixos.org/" --show-trace
1414
nix-tests:
1515
strategy:
@@ -18,7 +18,7 @@ jobs:
1818
runs-on: ${{ matrix.os }}
1919
steps:
2020
- uses: actions/checkout@v3
21-
- uses: nixbuild/nix-quick-install-action@v17
21+
- uses: nixbuild/nix-quick-install-action@v18
2222
- run: nix-build -A tests.nixpkgsFmt -A tests.cabalFmt -A tests.purs-tidy -A tests.pngOptimization -A tests.shellcheck -A tests.stylishHaskell --arg supportedSystems '[ builtins.currentSystem ]' --restrict-eval -I . --allowed-uris 'https://github.com/NixOS/nixpkgs https://github.com/input-output-hk https://github.com/NixOS/nixpkgs-channels' --option trusted-public-keys "hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= iohk.cachix.org-1:DpRUyj7h7V830dp/i6Nti+NEO2/nhblbov/8MW7Rqoo= cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=" --option substituters "https://hydra.iohk.io https://iohk.cachix.org https://cache.nixos.org/"
2323
check-for-updates:
2424
strategy:
@@ -27,7 +27,7 @@ jobs:
2727
runs-on: ${{ matrix.os }}
2828
steps:
2929
- uses: actions/checkout@v3
30-
- uses: nixbuild/nix-quick-install-action@v17
30+
- uses: nixbuild/nix-quick-install-action@v18
3131
- run: |
3232
nix --extra-experimental-features 'nix-command flakes' --extra-experimental-features flakes flake lock --option trusted-public-keys "hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= iohk.cachix.org-1:DpRUyj7h7V830dp/i6Nti+NEO2/nhblbov/8MW7Rqoo= cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=" --option substituters "https://hydra.iohk.io https://iohk.cachix.org https://cache.nixos.org/"
3333
nix-shell --extra-experimental-features 'nix-command flakes' --command "cd plutus-playground-client && (update-client-deps || update-client-deps)" --option trusted-public-keys "hydra.iohk.io:f/Ea+s+dFdN+3Y/G+FDgSq+a5NEWhJGzdjvKNGv0/EQ= iohk.cachix.org-1:DpRUyj7h7V830dp/i6Nti+NEO2/nhblbov/8MW7Rqoo= cache.nixos.org-1:6NCHdD59X431o0gWypbMrAURkbJ16ZPMQFGspcDShjY=" --option substituters "https://hydra.iohk.io https://iohk.cachix.org https://cache.nixos.org/" # Double-call to work around bug in spago2nix on first fetch

doc/adr/0005-pab-indexing-solution-integration.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ contract in `plutus-use-cases`).
4444
-- Step 3
4545
let refs = Map.keys
4646
$ Map.filter ((==) address . txOutAddress)
47-
$ getCardanoTxUnspentOutputsTx ledgerTx
47+
$ getCardanoTxProducedOutputs ledgerTx
4848
case refs of
4949
[] -> throwing _ScriptOutputMissing pk
5050
[outRef] -> do

plutus-chain-index-core/src/Plutus/ChainIndex/Tx.hs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,11 +110,11 @@ fromOnChainTx = \case
110110
ctx
111111
Invalid ctx ->
112112
onCardanoTx
113-
(\case tx@Tx{txCollateral, txValidRange, txData, txScripts} ->
113+
(\case tx@Tx{txCollateralInputs, txReturnCollateral, txValidRange, txData, txScripts} ->
114114
ChainIndexTx
115115
{ _citxTxId = txId tx
116-
, _citxInputs = map (fillTxInputWitnesses tx) txCollateral
117-
, _citxOutputs = InvalidTx Nothing -- TODO: update when `Tx` supports collateral output
116+
, _citxInputs = map (fillTxInputWitnesses tx) txCollateralInputs
117+
, _citxOutputs = InvalidTx $ fmap (fromCardanoTxOut . getTxOut) txReturnCollateral
118118
, _citxValidRange = txValidRange
119119
, _citxData = txData
120120
, _citxRedeemers = calculateRedeemerPointers tx

plutus-chain-index-core/src/Plutus/ChainIndex/TxIdState.hs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ import Data.FingerTree ((|>))
2121
import Data.FingerTree qualified as FT
2222
import Data.Map qualified as Map
2323
import Data.Monoid (Last (..), Sum (..))
24-
import Ledger (OnChainTx, TxId, eitherTx)
24+
import Ledger (OnChainTx, TxId, onChainTxIsValid)
2525
import Plutus.ChainIndex.Tx (ChainIndexTx (..), citxTxId, validityFromChainIndex)
2626
import Plutus.ChainIndex.Types (BlockNumber (..), Depth (..), Point (..), RollbackState (..), Tip (..),
2727
TxConfirmedState (..), TxIdState (..), TxStatus, TxStatusFailure (..), TxValidity (..))
@@ -31,7 +31,7 @@ import Plutus.ChainIndex.UtxoState (RollbackFailed (..), RollbackResult (..), Ut
3131
-- | The 'TxStatus' of a transaction right after it was added to the chain
3232
initialStatus :: OnChainTx -> TxStatus
3333
initialStatus tx =
34-
TentativelyConfirmed 0 (eitherTx (const TxInvalid) (const TxValid) tx) ()
34+
TentativelyConfirmed 0 (if onChainTxIsValid tx then TxValid else TxInvalid) ()
3535

3636
-- | Increase the depth of a tentatively confirmed transaction
3737
increaseDepth :: TxStatus -> TxStatus

plutus-contract-certification/src/Plutus/Contract/Test/Certification/Run.hs

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@ import System.Random.SplitMix
5858
import Test.QuickCheck as QC
5959
import Test.QuickCheck.Property
6060
import Test.QuickCheck.Random as QC
61-
import Test.Tasty as Tasty
62-
import Test.Tasty.Runners as Tasty
61+
import Test.Tasty qualified as Tasty
62+
import Test.Tasty.Runners qualified as Tasty
6363
import Text.Read hiding (lift)
6464

6565
newtype JSONShowRead a = JSONShowRead a
@@ -90,7 +90,24 @@ instance FromJSON SomeException where
9090
str <- parseJSON v
9191
return $ SomeException (ErrorCall str)
9292

93-
deriving via (JSONShowRead Tasty.Result) instance ToJSON Tasty.Result
93+
data TastyResult = Result
94+
{ resultOutcome :: Tasty.Outcome
95+
, resultDescription :: String
96+
, resultShortDescription :: String
97+
, resultTime :: Tasty.Time
98+
}
99+
deriving (Generic, ToJSON)
100+
101+
deriving instance Generic Tasty.FailureReason
102+
deriving instance ToJSON Tasty.FailureReason
103+
deriving instance ToJSON Tasty.Outcome
104+
105+
instance ToJSON Tasty.Result where
106+
toJSON r = toJSON $ Result { resultOutcome = Tasty.resultOutcome r
107+
, resultDescription = Tasty.resultDescription r
108+
, resultShortDescription = Tasty.resultShortDescription r
109+
, resultTime = Tasty.resultTime r
110+
}
94111

95112
data CertificationReport m = CertificationReport {
96113
_certRes_standardPropertyResult :: QC.Result,
@@ -208,10 +225,10 @@ checkNoLockedFundsLight opts prf =
208225
mkQCArgs :: CertificationOptions -> Args
209226
mkQCArgs CertificationOptions{..} = stdArgs { chatty = certOptOutput , maxSuccess = certOptNumTests }
210227

211-
runUnitTests :: (CoverageRef -> TestTree) -> CertMonad [Tasty.Result]
228+
runUnitTests :: (CoverageRef -> Tasty.TestTree) -> CertMonad [Tasty.Result]
212229
runUnitTests t = liftIORep $ do
213230
ref <- newCoverageRef
214-
res <- launchTestTree mempty (t ref) $ \ status -> do
231+
res <- Tasty.launchTestTree mempty (t ref) $ \ status -> do
215232
rs <- atomically $ mapM waitForDone (IntMap.elems status)
216233
return $ \ _ -> return rs
217234
cov <- readCoverageRef ref
@@ -220,8 +237,8 @@ runUnitTests t = liftIORep $ do
220237
waitForDone tv = do
221238
s <- readTVar tv
222239
case s of
223-
Done r -> return r
224-
_ -> retry
240+
Tasty.Done r -> return r
241+
_ -> retry
225242

226243
checkDerived :: forall d m c. (c m => ContractModel (d m))
227244
=> Maybe (Instance c m)

plutus-contract/src/Wallet/Emulator/Chain.hs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ import Data.Monoid (Ap (Ap))
3131
import Data.Traversable (for)
3232
import GHC.Generics (Generic)
3333
import Ledger (Block, Blockchain, CardanoTx (..), OnChainTx (..), Params (..), Slot (..), TxId, TxIn (txInRef), Value,
34-
eitherTx, getCardanoTxCollateralInputs, getCardanoTxFee, getCardanoTxId, getCardanoTxValidityRange,
35-
txOutValue)
34+
getCardanoTxCollateralInputs, getCardanoTxFee, getCardanoTxId, getCardanoTxTotalCollateral,
35+
getCardanoTxValidityRange, txOutValue, unOnChain)
3636
import Ledger.Index qualified as Index
3737
import Ledger.Interval qualified as Interval
3838
import Ledger.Validation qualified as Validation
@@ -166,8 +166,10 @@ validateBlock params slot@(Slot s) idx txns =
166166
in ValidatedBlock block events idx'
167167

168168
getCollateral :: Index.UtxoIndex -> CardanoTx -> Value
169-
getCollateral idx tx = fromRight (getCardanoTxFee tx) $
170-
alaf Ap foldMap (fmap txOutValue . (`Index.lookup` idx) . txInRef) (getCardanoTxCollateralInputs tx)
169+
getCollateral idx tx = case getCardanoTxTotalCollateral tx of
170+
Just v -> v
171+
Nothing -> fromRight (getCardanoTxFee tx) $
172+
alaf Ap foldMap (fmap txOutValue . (`Index.lookup` idx) . txInRef) (getCardanoTxCollateralInputs tx)
171173

172174
-- | Check whether the given transaction can be validated in the given slot.
173175
canValidateNow :: Slot -> CardanoTx -> Bool
@@ -204,7 +206,7 @@ addBlock blk st =
204206
st & chainNewestFirst %~ (blk :)
205207
-- The block update may contain txs that are not in this client's
206208
-- `txPool` which will get ignored
207-
& txPool %~ (\\ map (eitherTx id id) blk)
209+
& txPool %~ (\\ map unOnChain blk)
208210

209211
addTxToPool :: CardanoTx -> TxPool -> TxPool
210212
addTxToPool = (:)

plutus-contract/src/Wallet/Emulator/MultiAgent.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ emulatorStateInitialDist networkId mp = do
308308
where
309309
-- See [Creating wallets with multiple outputs]
310310
mkOutputs (key, vl) = mkOutput key <$> splitInto10 vl
311-
splitInto10 vl = replicate (fromIntegral count) (Ada.toValue (ada `div` count)) ++ remainder
311+
splitInto10 vl = if count <= 1 then [vl] else replicate (fromIntegral count) (Ada.toValue (ada `div` count)) ++ remainder
312312
where
313313
ada = if Value.isAdaOnlyValue vl then Ada.fromValue vl else Ada.fromValue vl - minAdaTxOut
314314
-- Make sure we don't make the outputs too small

plutus-contract/src/Wallet/Emulator/Wallet.hs

Lines changed: 55 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ module Wallet.Emulator.Wallet where
2525

2626
import Cardano.Api.Shelley (makeSignedTransaction, protocolParamCollateralPercent)
2727
import Cardano.Wallet.Primitive.Types qualified as Cardano.Wallet
28-
import Control.Lens (makeLenses, makePrisms, over, view, (&), (.~), (^.))
28+
import Control.Lens (makeLenses, makePrisms, over, view, (&), (.~), (?~), (^.))
2929
import Control.Monad (foldM, (<=<))
3030
import Control.Monad.Freer (Eff, Member, Members, interpret, type (~>))
3131
import Control.Monad.Freer.Error (Error, runError, throwError)
@@ -37,7 +37,7 @@ import Data.Aeson qualified as Aeson
3737
import Data.Bifunctor (bimap, first, second)
3838
import Data.Data (Data)
3939
import Data.Default (Default (def))
40-
import Data.Foldable (Foldable (fold), find, foldl')
40+
import Data.Foldable (Foldable (fold), find, foldl', toList)
4141
import Data.List (sort, sortOn, (\\))
4242
import Data.Map qualified as Map
4343
import Data.Maybe (catMaybes, fromMaybe, isNothing, listToMaybe)
@@ -424,65 +424,75 @@ handleBalanceTx ::
424424
-> UnbalancedTx
425425
-> Eff effs Tx
426426
handleBalanceTx utxo utx = do
427-
params@Params { pProtocolParams } <- WAPI.getClientParams
427+
Params { pProtocolParams } <- WAPI.getClientParams
428428
let filteredUnbalancedTxTx = removeEmptyOutputs (view U.tx utx)
429429
let txInputs = Tx.txInputs filteredUnbalancedTxTx
430430
ownAddr <- gets ownAddress
431431
inputValues <- traverse lookupValue (Tx.txInputs filteredUnbalancedTxTx)
432-
collateral <- traverse lookupValue (Tx.txCollateral filteredUnbalancedTxTx)
433432
let fees = txFee filteredUnbalancedTxTx
434433
left = txMint filteredUnbalancedTxTx <> fold inputValues
435434
right = fees <> foldMap Tx.txOutValue (filteredUnbalancedTxTx ^. Tx.outputs)
436-
collFees = Ada.toValue $ (Ada.fromValue fees * maybe 100 fromIntegral (protocolParamCollateralPercent pProtocolParams)) `Ada.divide` 100
437-
remainingCollFees = collFees PlutusTx.- fold collateral
438435
balance = left PlutusTx.- right
439436
-- filter out inputs from utxo that are already in unBalancedTx
440437
inputsOutRefs = map Tx.txInputRef txInputs
441438
filteredUtxo = flip Map.filterWithKey utxo $ \txOutRef _ ->
442439
txOutRef `notElem` inputsOutRefs
443440
outRefsWithValue = second (view Ledger.ciTxOutValue) <$> Map.toList filteredUtxo
444441

445-
((neg, newTxIns), (pos, newTxOuts)) <- calculateTxChanges params ownAddr outRefsWithValue $ Value.split balance
446-
447-
tx' <- if Value.isZero pos
448-
then do
449-
logDebug NoOutputsAdded
450-
pure filteredUnbalancedTxTx
451-
else do
452-
logDebug $ AddingPublicKeyOutputFor pos
453-
pure $ filteredUnbalancedTxTx & over Tx.outputs (++ newTxOuts)
454-
455-
tx'' <- if Value.isZero neg
456-
then do
457-
logDebug NoInputsAdded
458-
pure tx'
459-
else do
460-
logDebug $ AddingInputsFor neg
461-
pure $ tx' & over Tx.inputs (sort . (++) (fmap Tx.pubKeyTxInput newTxIns))
462-
463-
if remainingCollFees `Value.leq` PlutusTx.zero
464-
then do
465-
logDebug NoCollateralInputsAdded
466-
pure tx''
467-
else do
468-
logDebug $ AddingCollateralInputsFor remainingCollFees
469-
addCollateral utxo remainingCollFees tx''
442+
((neg, newTxIns), (pos, mNewTxOut)) <- calculateTxChanges ownAddr outRefsWithValue $ Value.split balance
443+
444+
txWithOutputsAdded <- if Value.isZero pos
445+
then do
446+
logDebug NoOutputsAdded
447+
pure filteredUnbalancedTxTx
448+
else do
449+
logDebug $ AddingPublicKeyOutputFor pos
450+
pure $ filteredUnbalancedTxTx & over Tx.outputs (++ toList mNewTxOut)
451+
452+
txWithinputsAdded <- if Value.isZero neg
453+
then do
454+
logDebug NoInputsAdded
455+
pure txWithOutputsAdded
456+
else do
457+
logDebug $ AddingInputsFor neg
458+
pure $ txWithOutputsAdded & over Tx.inputs (sort . (++) (fmap Tx.pubKeyTxInput newTxIns))
459+
460+
collateral <- traverse lookupValue (Tx.txCollateralInputs txWithinputsAdded)
461+
462+
let collAddr = maybe ownAddr Ledger.txOutAddress $ Tx.txReturnCollateral txWithinputsAdded
463+
collateralPercent = maybe 100 fromIntegral (protocolParamCollateralPercent pProtocolParams)
464+
collFees = Ada.toValue $ (Ada.fromValue fees * collateralPercent + 99 {- make sure to round up -}) `Ada.divide` 100
465+
collBalance = fold collateral PlutusTx.- collFees
466+
467+
((negColl, newTxInsColl), (_, mNewTxOutColl)) <- calculateTxChanges collAddr outRefsWithValue $ Value.split collBalance
468+
469+
txWithCollateralInputs <- if Value.isZero negColl
470+
then do
471+
logDebug NoCollateralInputsAdded
472+
pure txWithinputsAdded
473+
else do
474+
logDebug $ AddingCollateralInputsFor negColl
475+
pure $ txWithinputsAdded & over Tx.collateralInputs (sort . (++) (fmap Tx.pubKeyTxInput newTxInsColl))
476+
477+
pure $ txWithCollateralInputs & Tx.totalCollateral ?~ collFees & Tx.returnCollateral .~ mNewTxOutColl
470478

471479
type PubKeyTxIn = TxOutRef
472480

473-
calculateTxChanges
474-
:: ( Member (Error WAPI.WalletAPIError) effs
475-
)
476-
=> Params
477-
-> Address -- ^ The address for the change output
481+
calculateTxChanges ::
482+
( Member (Error WAPI.WalletAPIError) effs
483+
, Member NodeClientEffect effs
484+
, Member (State WalletState) effs
485+
)
486+
=> Address -- ^ The address for the change output
478487
-> [(TxOutRef, Value)] -- ^ The current wallet's unspent transaction outputs.
479488
-> (Value, Value) -- ^ The unbalanced tx's negative and positive balance.
480-
-> Eff effs ((Value, [PubKeyTxIn]), (Value, [TxOut]))
481-
calculateTxChanges params addr utxos (neg, pos) = do
489+
-> Eff effs ((Value, [PubKeyTxIn]), (Value, Maybe TxOut))
490+
calculateTxChanges addr utxos (neg, pos) = do
482491
-- Calculate the change output with minimal ada
483-
(newNeg, newPos, extraTxOuts) <- if Value.isZero pos
484-
then pure (neg, pos, [])
492+
(newNeg, newPos, mExtraTxOut) <- if Value.isZero pos
493+
then pure (neg, pos, Nothing)
485494
else do
495+
params <- WAPI.getClientParams
486496
txOut <- either
487497
(throwError . WAPI.ToCardanoError)
488498
(pure . TxOut)
@@ -492,7 +502,7 @@ calculateTxChanges params addr utxos (neg, pos) = do
492502
$ U.adjustTxOut params txOut
493503
let missingValue = Ada.toValue (fold missing)
494504
-- Add the missing ada to both sides to keep the balance.
495-
pure (neg <> missingValue, pos <> missingValue, [extraTxOut])
505+
pure (neg <> missingValue, pos <> missingValue, Just extraTxOut)
496506

497507
-- Calculate the extra inputs needed
498508
(spend, change) <- if Value.isZero newNeg
@@ -502,30 +512,16 @@ calculateTxChanges params addr utxos (neg, pos) = do
502512
if Value.isZero change
503513
then do
504514
-- No change, so the new inputs and outputs have balanced the transaction
505-
pure ((newNeg, fst <$> spend), (newPos, extraTxOuts))
506-
else if null extraTxOuts
515+
pure ((newNeg, fst <$> spend), (newPos, mExtraTxOut))
516+
else if null mExtraTxOut
507517
-- We have change so we need an extra output, if we didn't have that yet,
508518
-- first make one with an estimated minimal amount of ada
509519
-- which then will calculate a more exact set of inputs
510-
then calculateTxChanges params addr utxos (neg <> Ada.toValue Ledger.minAdaTxOut, Ada.toValue Ledger.minAdaTxOut)
520+
then calculateTxChanges addr utxos (neg <> Ada.toValue Ledger.minAdaTxOut, Ada.toValue Ledger.minAdaTxOut)
511521
-- Else recalculate with the change added to both sides
512522
-- Ideally this creates the same inputs and outputs and then the change will be zero
513523
-- But possibly the minimal Ada increases and then we also want to compute a new set of inputs
514-
else calculateTxChanges params addr utxos (newNeg <> change, newPos <> change)
515-
516-
addCollateral
517-
:: ( Member (Error WAPI.WalletAPIError) effs
518-
)
519-
=> Map.Map TxOutRef ChainIndexTxOut -- ^ The current wallet's unspent transaction outputs.
520-
-> Value
521-
-> Tx
522-
-> Eff effs Tx
523-
addCollateral mp vl tx = do
524-
(spend, _) <- selectCoin (filter (Value.isAdaOnlyValue . snd) (second (view Ledger.ciTxOutValue) <$> Map.toList mp)) vl
525-
let addTxCollateral =
526-
let ins = Tx.pubKeyTxInput . fst <$> spend
527-
in over Tx.collateralInputs (sort . (++) ins)
528-
pure $ tx & addTxCollateral
524+
else calculateTxChanges addr utxos (newNeg <> change, newPos <> change)
529525

530526
-- | Given a set of @a@s with coin values, and a target value, select a number
531527
-- of @a@ such that their total value is greater than or equal to the target.

plutus-contract/src/Wallet/Graph.hs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ txnFlows keys bc = catMaybes (utxoLinks ++ foldMap extract bc')
108108

109109
extract :: (UtxoLocation, OnChainTx) -> [Maybe FlowLink]
110110
extract (loc, tx) =
111-
let targetRef = mkRef $ eitherTx getCardanoTxId getCardanoTxId tx in
111+
let targetRef = mkRef $ getCardanoTxId $ unOnChain tx in
112112
fmap (flow (Just loc) targetRef . txInRef) (consumableInputs tx)
113113
-- make a flow for a TxOutRef
114114

0 commit comments

Comments
 (0)