diff --git a/mlabs/.gitignore b/mlabs/.gitignore index c33954f53..fa050c17c 100644 --- a/mlabs/.gitignore +++ b/mlabs/.gitignore @@ -1 +1,3 @@ dist-newstyle/ +.stack-work/ +stack.yaml.lock diff --git a/mlabs/LICENSE b/mlabs/LICENSE new file mode 100644 index 000000000..261eeb9e9 --- /dev/null +++ b/mlabs/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/mlabs/Makefile b/mlabs/Makefile index bdd0712c0..9ae6f7c82 100644 --- a/mlabs/Makefile +++ b/mlabs/Makefile @@ -2,17 +2,17 @@ hoogle: requires_nix_shell hoogle server --local --port 8008 -build: requires_nix_shell - cabal build all +build: + stack build --ghc-options="-Wall" -repl: requires_nix_shell - cabal new-repl +repl: + stack ghci -test: requires_nix_shell - cabal test all +test: + stack test all -watch: requires_nix_shell - ghcid "-c cabal new-repl" +watch: + stack build --file-watch --ghc-options="-Wall" # Target to use as dependency to fail if not inside nix-shell requires_nix_shell: diff --git a/mlabs/app/Main.hs b/mlabs/app/Main.hs index 65ae4a05d..a7f65cb1c 100644 --- a/mlabs/app/Main.hs +++ b/mlabs/app/Main.hs @@ -1,4 +1,6 @@ module Main where +import Prelude + main :: IO () main = putStrLn "Hello, Haskell!" diff --git a/mlabs/mlabs-plutus-use-cases.cabal b/mlabs/mlabs-plutus-use-cases.cabal index 91fbc3061..5b0eb0bc2 100644 --- a/mlabs/mlabs-plutus-use-cases.cabal +++ b/mlabs/mlabs-plutus-use-cases.cabal @@ -2,7 +2,7 @@ cabal-version: >=1.10 -- Initial package description 'mlabs-plutus-use-cases.cabal' generated by 'cabal init'. -- For further documentation, see http://haskell.org/cabal/users-guide/ -name: mlabs-plutus-use-caases +name: mlabs-plutus-use-cases version: 0.1.0.0 -- synopsis: -- description: @@ -29,8 +29,10 @@ library , plutus-contract , plutus-ledger , plutus-tx + , plutus-ledger-api , plutus-tx-plugin , plutus-pab + , plutus-use-cases , prettyprinter , lens , text @@ -38,15 +40,20 @@ library default-language: Haskell2010 hs-source-dirs: src/ exposed-modules: - Mlabs.Lending + Mlabs.Lending + Mlabs.Lending.Coin + Mlabs.Lending.Utils default-extensions: ExplicitForAll FlexibleContexts ScopedTypeVariables + DerivingStrategies DeriveAnyClass DeriveGeneric StandaloneDeriving DeriveLift GeneralizedNewtypeDeriving DeriveFunctor DeriveFoldable DeriveTraversable + LambdaCase MonoLocalBinds MultiParamTypeClasses + NoImplicitPrelude RecordWildCards OverloadedStrings TypeFamilies @@ -54,10 +61,10 @@ library TemplateHaskell DataKinds TypeOperators + TypeApplications executable mlabs-plutus-use-caases - main-is: Main.hs - hs-source-dirs: app/ + main-is: app/Main.hs -- other-modules: -- other-extensions: build-depends: base >=4.14 && <4.15 @@ -84,12 +91,25 @@ Test-suite mlabs-plutus-use-cases-tests Default-Language: Haskell2010 Build-Depends: base >=4.9 && <5 , mlabs-plutus-use-cases - , text + , containers + , playground-common + , plutus-core + , plutus-contract + , plutus-ledger + , plutus-tx + , plutus-ledger-api + , plutus-tx-plugin + , plutus-pab + , plutus-use-cases + , plutus-contract + , prettyprinter , tasty , tasty-hunit + , text hs-source-dirs: test Main-is: Main.hs Other-modules: Test.Lending + , Test.Utils default-extensions: RecordWildCards OverloadedStrings diff --git a/mlabs/src/Mlabs/Lending.hs b/mlabs/src/Mlabs/Lending.hs index 1690b5510..3da50256d 100644 --- a/mlabs/src/Mlabs/Lending.hs +++ b/mlabs/src/Mlabs/Lending.hs @@ -1,60 +1,331 @@ +{-# OPTIONS_GHC -fno-specialize #-} +{-# OPTIONS_GHC -fno-strictness #-} +-- | Lending exchange platform (Lendex for short) is a tool for +-- user to provide lending funds. +-- +-- There are three roles of users: +-- +-- * **admin** - can initialise whole platform and close it. +-- +-- * **lender user** can create new tokens on the platform and provide funds with it. +-- +-- * **borrower user** can borrow funds. module Mlabs.Lending where --- import qualified PlutusTx.Prelude as Plutus +import PlutusTx.Prelude hiding (Semigroup(..), unless) +import qualified PlutusTx.Prelude as Plutus -import Data.Aeson +import Control.Monad (forever, void) + +import Data.Monoid (Last(..)) + +import Data.Aeson (FromJSON, ToJSON) import Data.Text (Text) import GHC.Generics (Generic) import Ledger hiding (singleton) --- import Ledger.Constraints as Constraints --- import Ledger.Constraints.OnChain as Constraints --- import Ledger.Constraints.TxConstraints as Constraints +import Ledger.Constraints as Constraints +import Ledger.Constraints.OnChain as Constraints +import Ledger.Constraints.TxConstraints as Constraints import Plutus.Contract +import qualified Plutus.Contracts.Currency as Currency import qualified PlutusTx import qualified Ledger.Typed.Scripts as Scripts - import Playground.Contract (ToSchema) +import qualified Prelude +import Prelude (Semigroup(..)) +import qualified Data.Map as Map +import Text.Printf (printf) +import qualified Plutus.Trace as Trace +import Plutus.Contract.Trace (Wallet) +import Plutus.Trace (EmulatorTrace) +import Mlabs.Lending.Coin +import Mlabs.Lending.Utils -newtype Pool = Pool - { poolCurrency :: CurrencySymbol - } - deriving (Show) -PlutusTx.unstableMakeIsData ''Pool +import qualified Data.Text as T + +-- | Constants for thread of lendex state and pool state. +lendexTokenName, poolStateTokenName :: TokenName +lendexTokenName = "Lendex" +poolStateTokenName = "Pool State" + +newtype Lendex = Lendex + { lxCoin :: Coin + } deriving stock (Show, Generic) + deriving anyclass (ToJSON, FromJSON, ToSchema) + deriving newtype (Prelude.Eq, Prelude.Ord) +PlutusTx.makeLift ''Lendex + +-- | Available actions data Action - = Create Pool + = Create Coin + -- ^ Create new coin for lending | Close + -- $ close the exchange deriving (Show) PlutusTx.unstableMakeIsData ''Action +PlutusTx.makeLift ''Action -data LendingDatum = LendingDatum - { ldCurrency :: CurrencySymbol - } +type LendingPool = [Coin] + +-- | Lending datum +data LendingDatum + = Factory [Coin] + -- ^ Global state to watch for coins that were created. + -- For every new coin we check against this state + -- weather it is new and have not been already created. + | Pool Coin + -- ^ single coint to lend funds. + deriving stock Show PlutusTx.unstableMakeIsData ''LendingDatum +PlutusTx.makeLift ''LendingDatum +-- | Parameters for create endpoint data CreateParams = CreateParams - { cpCurrency :: CurrencySymbol + { cpCoin :: Coin + -- ^ coin for which we create lending capabilities. } deriving (Show, Generic, ToJSON, FromJSON, ToSchema) -create :: HasBlockchainActions s => CreateParams -> Contract w s Text () -create _ = do - return () +{-# INLINABLE mkValidator #-} +-- | On-chain script validator +mkValidator :: Lendex -> Coin -> LendingDatum -> Action -> ScriptContext -> Bool +mkValidator lx c dat act ctx = case (dat, act) of + (Factory cs, Create pool) -> validateCreate lx c cs pool ctx + (_, Close ) -> validateClose lx c dat ctx + _ -> False + +{-# INLINABLE validateCreate #-} +-- | It validates create-case +validateCreate :: Lendex -> Coin -> [Coin] -> Coin -> ScriptContext -> Bool +validateCreate Lendex{..} poolCoin coins newCoin ctx = + lendexCoinPresent + && newCoinIsAdded + && poolStateCoinForged + && keepsLedexCoin + && keepsPoolStateCoin + where + lendexCoinPresent = + Plutus.traceIfFalse "Lendex coin not present" $ + hasCoinValue (valueWithin $ findOwnInput' ctx) lxCoin + + newCoinIsAdded = + Plutus.traceIfFalse "New coin is added to pool" $ + all (/= newCoin) coins + + poolStateCoinForged = + Plutus.traceIfFalse "Pool state coin not forged" $ + hasCoinValue forged poolCoin + + keepsLedexCoin = keepsCoin (Factory $ newCoin : coins) lxCoin + keepsPoolStateCoin = keepsCoin (Pool newCoin) poolCoin + + keepsCoin st c = Constraints.checkOwnOutputConstraint ctx (OutputConstraint st $ coin c 1) + + forged :: Value + forged = txInfoForge $ scriptContextTxInfo ctx + +{-# INLINABLE validateClose #-} +-- | It validates the closing of the whole lending system +validateClose :: Lendex -> Coin -> LendingDatum -> ScriptContext -> Bool +validateClose _ _ _ _ = True + +{-# INLINABLE validateLiquidityForging #-} +-- | It validates the forging of new coin for lending purposes +validateLiquidityForging :: Lendex -> TokenName -> ScriptContext -> Bool +validateLiquidityForging us tn ctx = case [ i + | i <- txInfoInputs $ scriptContextTxInfo ctx + , let v = valueWithin i + , hasCoinValue v usC || + hasCoinValue v lpC + ] of + [_] -> True + [_, _] -> True + _ -> Plutus.traceError "pool state forging without Lendex input" + where + usC, lpC :: Coin + usC = lxCoin us + lpC = mkCoin (ownCurrencySymbol ctx) tn + +-- | Instance of validation script for lending exchange +lendexInstance :: Lendex -> Scripts.ScriptInstance Lending +lendexInstance lx = Scripts.validator @Lending + ($$(PlutusTx.compile [|| mkValidator ||]) + `PlutusTx.applyCode` PlutusTx.liftCode lx + `PlutusTx.applyCode` PlutusTx.liftCode c) + $$(PlutusTx.compile [|| wrap ||]) + where + c :: Coin + c = poolStateCoin lx + + wrap = Scripts.wrapValidator @LendingDatum @Action + +-- | Validator +lendexScript :: Lendex -> Validator +lendexScript = Scripts.validatorScript . lendexInstance +-- | Validator script address +lendexAddress :: Lendex -> Ledger.Address +lendexAddress = Ledger.scriptAddress . lendexScript + +-- | Wrapper to create lendex state coin out of @CurrencySymbol@. +lendex :: CurrencySymbol -> Lendex +lendex cs = Lendex $ mkCoin cs lendexTokenName + +-- | Constructor for pool state coin. +-- It relies on script for new coin forgery validation. +poolStateCoin :: Lendex -> Coin +poolStateCoin = flip mkCoin poolStateTokenName . liquidityCurrency + +-- | pool state forgery validator +liquidityPolicy :: Lendex -> MonetaryPolicy +liquidityPolicy lx = mkMonetaryPolicyScript $ + $$(PlutusTx.compile [|| \u t -> Scripts.wrapMonetaryPolicy (validateLiquidityForging u t) ||]) + `PlutusTx.applyCode` PlutusTx.liftCode lx + `PlutusTx.applyCode` PlutusTx.liftCode poolStateTokenName + +-- | @CurrencySumbol@ for the lendex. We use it for pool state. +-- They share common @CurrencySymbol@ +liquidityCurrency :: Lendex -> CurrencySymbol +liquidityCurrency = scriptCurrencySymbol . liquidityPolicy + +-- | Provides TxOut that contains lendex script. +findLendexInstance :: Lendex -> Coin -> (LendingDatum -> Maybe a) -> App (TxOutRef, TxOutTx, a) +findLendexInstance us c f = do + let addr = lendexAddress us + logInfo @String $ printf "looking for Lendex instance at address %s containing coin %s " (show addr) (show c) + utxos <- utxoAt addr + go [x | x@(_, o) <- Map.toList utxos, coinValueOf (txOutValue $ txOutTxOut o) c == 1] + where + go [] = throwError "Lendex instance not found" + go ((oref, o) : xs) = do + d <- getLendexDatum o + case f d of + Nothing -> go xs + Just a -> do + logInfo @String $ printf "found Lendex instance with datum: %s" (show d) + return (oref, o, a) + +-- | Provides TXOut that contains global state of lendex. +-- It provides the list of coins that are part of the exchange so far. +findLendexFactory :: Lendex -> App (TxOutRef, TxOutTx, [Coin]) +findLendexFactory lx@Lendex{..} = findLendexInstance lx lxCoin $ \case + Factory lps -> Just lps + Pool _ -> Nothing + +-- | Reads lendex datum for the @TxOut@. +getLendexDatum :: TxOutTx -> App LendingDatum +getLendexDatum o = case txOutDatumHash $ txOutTxOut o of + Nothing -> throwError "datumHash not found" + Just h -> case Map.lookup h $ txData $ txOutTxTx o of + Nothing -> throwError "datum not found" + Just (Datum e) -> case PlutusTx.fromData e of + Nothing -> throwError "datum has wrong type" + Just d -> return d + +-- | Creates a Lendex "factory". This factory will keep track of the existing +-- liquidity pools and enforce that there will be at most one liquidity pool +-- for any pair of tokens at any given time. +start :: HasBlockchainActions s => Contract w s Text Lendex +start = do + pkh <- pubKeyHash <$> ownPubKey + cs <- fmap Currency.currencySymbol $ + mapError (T.pack . show @Currency.CurrencyError) $ + Currency.forgeContract pkh [(lendexTokenName, 1)] + let c = mkCoin cs lendexTokenName + us = lendex cs + inst = lendexInstance us + tx = mustPayToTheScript (Factory []) $ coin c 1 + ledgerTx <- submitTxConstraints inst tx + void $ awaitTxConfirmed $ txId ledgerTx + + logInfo @String $ printf "started Uniswap %s at address %s" (show us) (show $ lendexAddress us) + return us + +-- | Creates a liquidity pool for a given coin. +-- We have no coins at the start +create :: Lendex -> CreateParams -> App () +create lx CreateParams{..} = do + (oref, o, lps) <- findLendexFactory lx + let lp = cpCoin + usInst = lendexInstance lx + usScript = lendexScript lx + usDat1 = Factory $ lp : lps + usDat2 = Pool lp + psC = poolStateCoin lx + usVal = coin (lxCoin lx) 1 + lpVal = coin cpCoin 0 + + lookups = Constraints.scriptInstanceLookups usInst + <> Constraints.otherScript usScript + <> Constraints.monetaryPolicy (liquidityPolicy lx) + <> Constraints.unspentOutputs (Map.singleton oref o) + + tx = Constraints.mustPayToTheScript usDat1 usVal + <> Constraints.mustPayToTheScript usDat2 lpVal + <> Constraints.mustForgeValue (coin psC 1) + <> Constraints.mustSpendScriptOutput oref (Redeemer $ PlutusTx.toData $ Create lp) + + ledgerTx <- submitTxConstraintsWith lookups tx + void $ awaitTxConfirmed $ txId ledgerTx + + logInfo $ "created liquidity pool: " ++ show lp + +-- Type to tag Redeemer and Datum for our lending platform data Lending instance Scripts.ScriptType Lending where type RedeemerType Lending = Action type DatumType Lending = LendingDatum +-- | Schema for the super user who can initiate the whole lendex platform. +type LendingOwnerSchema = + BlockchainActions + .\/ Endpoint "start" () + +-- | Schema for lender. type LendingSchema = BlockchainActions - .\/ Endpoint "create" () + .\/ Endpoint "create" CreateParams -- create new coin to lend funds + +type App a = Contract () LendingSchema Text a +type OwnerApp a = Contract () LendingOwnerSchema Text a + +-- | Endpoints for admin of the platform. Admin can initialise the lending platform. +ownerEndpoint :: Contract (Last Lendex) LendingOwnerSchema Text () +ownerEndpoint = forever start' + where + start' = + endpoint @"start" >>= \() -> do + lx <- start + tell $ Last $ Just lx + +-- | Endpoints for lender +userEndpoints :: Lendex -> App () +userEndpoints lx = forever create' + where + create' = endpoint @"create" >>= create lx + +----------------------------------------------- +-- call endpoints (for testing) --- endpoints :: Contract w LendingSchema Void () --- endpoints = forever endpoints +-- | Calls init lendex platform for a given wallet. +-- Produces tag of the platform that contains coin by which we track +-- state of the platform. +callStart :: Wallet -> EmulatorTrace (Maybe Lendex) +callStart w = do + hdl <- Trace.activateContractWallet w ownerEndpoint + void $ Trace.callEndpoint @"start" hdl () + void $ Trace.waitNSlots 10 + Last res <- Trace.observableState hdl + return res +-- | Lendeer calls create coin endpoint. Coin for @CreateParams@ is used for lending purposes. +callCreate :: Lendex -> Wallet -> CreateParams -> EmulatorTrace () +callCreate lx w cp = do + hdl <- Trace.activateContractWallet w (userEndpoints lx) + void $ Trace.callEndpoint @"create" hdl cp diff --git a/mlabs/src/Mlabs/Lending/Coin.hs b/mlabs/src/Mlabs/Lending/Coin.hs new file mode 100644 index 000000000..6ef15781d --- /dev/null +++ b/mlabs/src/Mlabs/Lending/Coin.hs @@ -0,0 +1,31 @@ +{-# options_ghc -fno-warn-orphans #-} +{-# OPTIONS_GHC -fno-specialize #-} +{-# OPTIONS_GHC -fno-specialize #-} +module Mlabs.Lending.Coin where + +import PlutusTx.Prelude (Integer, Bool, Eq(..)) + +import Ledger hiding (singleton) +import Ledger.Value (AssetClass (..), assetClassValue, assetClassValueOf, assetClass) +import Playground.Contract (ToSchema) + +type Coin = AssetClass +deriving anyclass instance ToSchema AssetClass + +{-# INLINABLE coin #-} +coin :: AssetClass -> Integer -> Value +coin = assetClassValue + +{-# INLINABLE coinValueOf #-} +coinValueOf :: Value -> AssetClass -> Integer +coinValueOf = assetClassValueOf + +{-# INLINABLE mkCoin #-} +mkCoin:: CurrencySymbol -> TokenName -> AssetClass +mkCoin = assetClass + +{-# INLINABLE hasCoinValue #-} +-- | We check that value for coin is present and equals to 1. +-- It serves as a marker of coin presence. +hasCoinValue :: Value -> Coin -> Bool +hasCoinValue val c = coinValueOf val c == 1 diff --git a/mlabs/src/Mlabs/Lending/Utils.hs b/mlabs/src/Mlabs/Lending/Utils.hs new file mode 100644 index 000000000..fed9b9d10 --- /dev/null +++ b/mlabs/src/Mlabs/Lending/Utils.hs @@ -0,0 +1,17 @@ +{-# OPTIONS_GHC -fno-specialize #-} +{-# OPTIONS_GHC -fno-specialize #-} +module Mlabs.Lending.Utils where + +import PlutusTx.Prelude ((.), error) +import qualified PlutusTx.Prelude as Plutus +import Ledger hiding (singleton) + +{-# INLINABLE valueWithin #-} +valueWithin :: TxInInfo -> Value +valueWithin = txOutValue . txInInfoResolved + +{-# INLINABLE findOwnInput' #-} +findOwnInput' :: ScriptContext -> TxInInfo +findOwnInput' ctx = Plutus.fromMaybe (error ()) (findOwnInput ctx) + + diff --git a/mlabs/stack.yaml b/mlabs/stack.yaml new file mode 100644 index 000000000..54531da22 --- /dev/null +++ b/mlabs/stack.yaml @@ -0,0 +1,131 @@ +resolver: lts-17.2 + +nix: + packages: + - cacert # Fixes "SSL certificate problem: unable to get local issuer certificate" + - zlib + +packages: +- . + +extra-deps: +- git: https://github.com/input-output-hk/plutus.git + commit: 62be7a2d6dff285ad72d5bc6f5f11991ffae888b + subdirs: + - playground-common + - plutus-core + - plutus-contract + - plutus-ledger + - plutus-tx + - plutus-tx-plugin + - prettyprinter-configurable + - plutus-ledger-api + - plutus-pab + - plutus-use-cases + - freer-extras + - quickcheck-dynamic +# Flat compression +- pure-zlib-0.6.7@sha256:5a1cdf87bf3079b7d3abace1f94eeb3c597c687a38a08ee2908783e609271467,3487 +# FEAT/NEAT and deps +- lazy-search-0.1.2.0 +- size-based-0.1.2.0 +- testing-feat-1.1.0.0 +- Stream-0.4.7.2@sha256:ed78165aa34c4e23dc53c9072f8715d414a585037f2145ea0eb2b38300354c53,1009 +- lazysmallcheck-0.6@sha256:dac7a1e4877681f1260309e863e896674dd6efc1159897b7945893e693f2a6bc,1696 +# Other missing packages +- aws-lambda-haskell-runtime-3.0.3 +- aws-lambda-haskell-runtime-wai-1.0.2@sha256:5ce655247461b562c8048011ddc022130135a03417def8203aad92366cc979ab,1965 +- composition-prelude-3.0.0.2 +- constraints-extras-0.3.0.2 +- dependent-map-0.4.0.0 +- dependent-sum-0.6.2.0 +- dependent-sum-template-0.1.0.3 +- eventful-memory-0.2.0 +- barbies-2.0.2.0 +- nothunks-0.1.2 +- indexed-traversable-instances-0.1 +- base16-bytestring-1.0.1.0 +# A revision was added to keep the bounds down, we don't actually want this! +# we work around the newer persistent-template by adding flags below +- eventful-sql-common-0.2.0@rev:0 +- eventful-sqlite-0.2.0 +- monoidal-containers-0.6.0.1 +- recursion-schemes-5.1.3 +- row-types-0.4.0.0 +- time-out-0.2@sha256:b9a6b4dee64f030ecb2a25dca0faff39b3cb3b5fefbb8af3cdec4142bfd291f2 +- time-interval-0.1.1@sha256:7bfd3601853d1af7caa18248ec10b01701d035ac274a93bb4670fea52a14d4e8 +- time-units-1.0.0@sha256:27cf54091c4a0ca73d504fc11d5c31ab4041d17404fe3499945e2055697746c1 +- servant-websockets-2.0.0 +- servant-subscriber-0.7.0.0 +- safe-exceptions-checked-0.1.0 +- async-timer-0.1.4.1 +- sbv-8.9 +- wl-pprint-1.2.1@sha256:aea676cff4a062d7d912149d270e33f5bb0c01b68a9db46ff13b438141ff4b7c +- witherable-0.4.1 +- canonical-json-0.6.0.0@sha256:9021f435ccb884a3b4c55bcc6b50eb19d5fc3cc3f29d5fcbdef016f5bbae23a2,3488 +- statistics-linreg-0.3@sha256:95c6efe6c7f6b26bc6e9ada90ab2d18216371cf59a6ef2b517b4a6fd35d9a76f,2544 +# cabal.project is the source of truth for these pins, they are explained there +# and need to be kept in sync. +- git: https://github.com/shmish111/purescript-bridge.git + commit: 6a92d7853ea514be8b70bab5e72077bf5a510596 +- git: https://github.com/eskimor/servant-purescript.git + commit: 6454d5bcb9aa2a5d6e3a3dc935423b67b6f3993c +- git: https://github.com/input-output-hk/cardano-crypto.git + commit: f73079303f663e028288f9f4a9e08bcca39a923e +- git: https://github.com/michaelpj/unlit.git + commit: 9ca1112093c5ffd356fc99c7dafa080e686dd748 +- git: https://github.com/input-output-hk/ouroboros-network + commit: 6cb9052bde39472a0555d19ade8a42da63d3e904 + subdirs: + - typed-protocols + - typed-protocols-examples + - ouroboros-network + - ouroboros-network-framework + - io-sim + - io-sim-classes + - network-mux + - Win32-network +- git: https://github.com/input-output-hk/cardano-prelude + commit: ee4e7b547a991876e6b05ba542f4e62909f4a571 + subdirs: + - cardano-prelude + - cardano-prelude-test +- git: https://github.com/input-output-hk/cardano-base + commit: 4251c0bb6e4f443f00231d28f5f70d42876da055 + subdirs: + - binary + - cardano-crypto-class + - cardano-crypto-tests + - cardano-crypto-praos + - slotting +- git: https://github.com/input-output-hk/cardano-ledger-specs + commit: 097890495cbb0e8b62106bcd090a5721c3f4b36f + subdirs: + - byron/chain/executable-spec + - byron/crypto + - byron/crypto/test + - byron/ledger/executable-spec + - byron/ledger/impl + - byron/ledger/impl/test + - semantics/executable-spec + - semantics/small-steps-test + - shelley/chain-and-ledger/dependencies/non-integer + - shelley/chain-and-ledger/executable-spec + - shelley-ma/impl +- git: https://github.com/input-output-hk/iohk-monitoring-framework + commit: a89c38ed5825ba17ca79fddb85651007753d699d + subdirs: + - contra-tracer + - iohk-monitoring + - tracer-transformers + - plugins/backend-ekg +allow-newer: true + +extra-package-dbs: [] + + + +ghc-options: + # Newer versions of persistent-template require some extra language extensions. Fortunately + # we can hack around this here rather than having to fork eventful & co (for now) + eventful-sql-common: "-XDerivingStrategies -XStandaloneDeriving -XUndecidableInstances -XDataKinds -XFlexibleInstances -XMultiParamTypeClasses" diff --git a/mlabs/test/Main.hs b/mlabs/test/Main.hs index d82a4bd93..de8687357 100644 --- a/mlabs/test/Main.hs +++ b/mlabs/test/Main.hs @@ -1,4 +1,8 @@ module Main where +import Test.Tasty +import qualified Test.Lending as Lending + main :: IO () -main = return () +main = defaultMain Lending.tests + diff --git a/mlabs/test/Test/Lending.hs b/mlabs/test/Test/Lending.hs index 7af7be059..2f8dedb7f 100644 --- a/mlabs/test/Test/Lending.hs +++ b/mlabs/test/Test/Lending.hs @@ -1,7 +1,75 @@ +-- | Test suite for lending exchange module Test.Lending( - test + tests ) where -test :: Bool -test = True +import Prelude + +import Test.Tasty +import Test.Tasty.HUnit + +import qualified Plutus.V1.Ledger.Ada as Ada +import qualified Plutus.V1.Ledger.Value as Ledger +import qualified Data.Map as M +import qualified PlutusTx.AssocMap as PM + +import Plutus.Contract.Test hiding (tx) +import qualified Plutus.Trace.Emulator as Trace + +import qualified Mlabs.Lending as L +import qualified Mlabs.Lending.Coin as L + +import Test.Utils + +-- | Test suite for lending exchange +tests :: TestTree +tests = testGroup "Lending" + [ testCreate + ] + +-- | Tests for creation of the coin and exchange platform. +testCreate :: TestTree +testCreate = testCase "Create lending pool" $ testNoErrors initConfig createScript + +------------------------------------------------------------------------------------ + +-- | Script that creates lendex and one coin for lending. +createScript :: Trace.EmulatorTrace () +createScript = do + mTheLendex <- L.callStart w1 + next + case mTheLendex of + Just theLendex -> do + L.callCreate theLendex w1 $ L.CreateParams + { cpCoin = L.mkCoin currency token + } + next + Nothing -> throwError "No lendex was created" + where + currency = Ledger.currencySymbol "T" + token = Ledger.tokenName "token" + +------------------------------------------------------------------------------------ +-- init blockchain state + +-- | Wallets that are used for testing. +w1, w2, w3, w4 :: Wallet +w1 = Wallet 1 +w2 = Wallet 2 +w3 = Wallet 3 +w4 = Wallet 4 + +-- | Initial config +initConfig :: Trace.EmulatorConfig +initConfig = cfg + where + cfg = Trace.EmulatorConfig $ Left $ M.fromList + [ (w1, v1) + , (w2, v1) + , (w3, v1) + , (w4, v1) + ] + + v1 = val 1000 + val x = Ledger.Value $ PM.fromList [ (Ada.adaSymbol, PM.singleton Ada.adaToken x) ] diff --git a/mlabs/test/Test/Utils.hs b/mlabs/test/Test/Utils.hs new file mode 100644 index 000000000..899ca195f --- /dev/null +++ b/mlabs/test/Test/Utils.hs @@ -0,0 +1,32 @@ +module Test.Utils( + throwError + , next + , wait + , testNoErrors +) where + + +import Data.Functor (void) +import Test.Tasty.HUnit (assertFailure) + +import qualified Plutus.Trace.Emulator as Trace + +-- | Throws error to emulator trace. +throwError :: String -> Trace.EmulatorTrace a +throwError msg = Trace.throwError (Trace.GenericError msg) + +-- | Wait for one slot. +next :: Trace.EmulatorTrace () +next = void Trace.nextSlot + +-- | Wait given amount of slots. +wait :: Integer -> Trace.EmulatorTrace () +wait = void . Trace.waitNSlots . fromInteger + +-- | Check that there are no errors during execution of the script. +testNoErrors :: Trace.EmulatorConfig -> Trace.EmulatorTrace () -> IO () +testNoErrors cfg trace = case err of + Just e -> assertFailure $ show e + Nothing -> pure () + where + err = (\(_, merr, _) -> merr) $ Trace.runEmulatorTrace cfg trace