Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
MosesSupposes committed Mar 18, 2022
2 parents 2fe1480 + 28559d3 commit dc86a1b
Show file tree
Hide file tree
Showing 12 changed files with 1,140 additions and 0 deletions.
14 changes: 14 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,15 @@
- [Part 7 - Property-Based Testing of Plutus Contracts](https://youtu.be/49oAwySp6Ys)
- [Part 8 - Homework](https://youtu.be/u2Plwc3Gkrs)

### [Lecture #9](https://www.youtube.com/playlist?list=PLNEK_Ejlx3x2zSFnzWA4Gbr_AVTz-4rzf)

- [Part 1 - Introduction](https://youtu.be/433VbouC-30)
- [Part 2 - Simon Thompson: Marlowe Overview](https://youtu.be/ce_Yv8BlW7c)
- [Part 3 - Alexander Nemish: Marlowe in Plutus](https://youtu.be/hd-E5DCN8uc)
- [Part 4 - Brian Bush: The Marlowe CLI](https://youtu.be/Vx_ygegrY78)
- [Part 5 - Marlowe Playground Demo](https://youtu.be/l0LXjh8J-go)
- [Part 6 - Homework](https://youtu.be/iYdyUaq_enA)

## Code Examples

- Lecture #1: [English Auction](code/week01)
Expand All @@ -86,6 +95,7 @@
- Lecture #6: [Deployment](code/week06)
- Lecture #7: [State Machines](code/week07)
- Lecture #8: [Testing](code/week08)
- Lecture #9: [Marlowe](code/week09)

## Exercises

Expand Down Expand Up @@ -141,6 +151,10 @@
- Add a new operation close to the TokenSale-contract that allows the seller to close the contract and retrieve all remaining funds.
- Modify the tests accordingly.

- Week #9m

- Modify the example Marlowe contract, so that Charlie must put down twice the deposit in the very beginning, which gets split between Alice and Bob if Charlie refuses to make his choice.

## Some Plutus Modules

- `Ledger.Scripts`, contains functions related to untyped Plutus scripts.
Expand Down
3 changes: 3 additions & 0 deletions code/week08/plutus-pioneer-program-week08.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ library
, Week08.QuickCheck
, Week08.TokenSale
, Week08.TokenSaleFixed
, Week08.TokenSaleWithClose
build-depends: aeson
, ansi-terminal
, base ^>=4.14.1.0
Expand All @@ -40,7 +41,9 @@ test-suite plutus-pioneer-program-week08-tests
main-is: Spec.hs
hs-source-dirs: test
other-modules: Spec.Model
, Spec.ModelWithClose
, Spec.Trace
, Spec.TraceWithClose
default-language: Haskell2010
ghc-options: -Wall -fobject-code -fno-ignore-interface-pragmas -fno-omit-interface-pragmas
build-depends: base ^>=4.14.1.0
Expand Down
184 changes: 184 additions & 0 deletions code/week08/src/Week08/TokenSaleWithClose.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,184 @@
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}

module Week08.TokenSaleWithClose
( TokenSale (..)
, TSRedeemer (..)
, TSStartSchema
, TSUseSchema
, startEndpoint
, useEndpoints
, useEndpoints'
) where

import Control.Monad hiding (fmap)
import Data.Aeson (FromJSON, ToJSON)
import Data.Monoid (Last (..))
import Data.Text (Text, pack)
import GHC.Generics (Generic)
import Plutus.Contract as Contract
import Plutus.Contract.StateMachine
import qualified PlutusTx
import PlutusTx.Prelude hiding (Semigroup(..), check, unless)
import Ledger hiding (singleton)
import Ledger.Ada as Ada
import Ledger.Constraints as Constraints
import qualified Ledger.Typed.Scripts as Scripts
import Ledger.Value
import Prelude (Semigroup (..), Show (..))
import qualified Prelude

data TokenSale = TokenSale
{ tsSeller :: !PaymentPubKeyHash
, tsToken :: !AssetClass
, tsTT :: !ThreadToken
} deriving (Show, Generic, FromJSON, ToJSON, Prelude.Eq)

PlutusTx.makeLift ''TokenSale

data TSRedeemer =
SetPrice Integer
| AddTokens Integer
| BuyTokens Integer
| Withdraw Integer Integer
| Close
deriving (Show, Prelude.Eq)

PlutusTx.unstableMakeIsData ''TSRedeemer

{-# INLINABLE lovelaces #-}
lovelaces :: Value -> Integer
lovelaces = Ada.getLovelace . Ada.fromValue

{-# INLINABLE transition #-}
transition :: TokenSale -> State (Maybe Integer) -> TSRedeemer -> Maybe (TxConstraints Void Void, State (Maybe Integer))
transition ts s r = case (stateValue s, stateData s, r) of
(v, Just _, SetPrice p) | p >= 0 -> Just ( Constraints.mustBeSignedBy (tsSeller ts)
, State (Just p) v
)
(v, Just p, AddTokens n) | n > 0 -> Just ( mempty
, State (Just p) $
v <>
assetClassValue (tsToken ts) n
)
(v, Just p, BuyTokens n) | n > 0 -> Just ( mempty
, State (Just p) $
v <>
assetClassValue (tsToken ts) (negate n) <>
lovelaceValueOf (n * p)
)
(v, Just p, Withdraw n l) | n >= 0 && l >= 0 &&
v `geq` (w <> toValue minAdaTxOut) -> Just ( Constraints.mustBeSignedBy (tsSeller ts)
, State (Just p) $
v <>
negate w
)
where
w = assetClassValue (tsToken ts) n <>
lovelaceValueOf l
(_, Just _, Close) -> Just ( Constraints.mustBeSignedBy (tsSeller ts)
, State Nothing mempty
)
_ -> Nothing

{-# INLINABLE tsStateMachine #-}
tsStateMachine :: TokenSale -> StateMachine (Maybe Integer) TSRedeemer
tsStateMachine ts = mkStateMachine (Just $ tsTT ts) (transition ts) isNothing

{-# INLINABLE mkTSValidator #-}
mkTSValidator :: TokenSale -> Maybe Integer -> TSRedeemer -> ScriptContext -> Bool
mkTSValidator = mkValidator . tsStateMachine

type TS = StateMachine (Maybe Integer) TSRedeemer

tsTypedValidator :: TokenSale -> Scripts.TypedValidator TS
tsTypedValidator ts = Scripts.mkTypedValidator @TS
($$(PlutusTx.compile [|| mkTSValidator ||]) `PlutusTx.applyCode` PlutusTx.liftCode ts)
$$(PlutusTx.compile [|| wrap ||])
where
wrap = Scripts.wrapValidator @(Maybe Integer) @TSRedeemer

tsValidator :: TokenSale -> Validator
tsValidator = Scripts.validatorScript . tsTypedValidator

tsAddress :: TokenSale -> Ledger.Address
tsAddress = scriptAddress . tsValidator

tsClient :: TokenSale -> StateMachineClient (Maybe Integer) TSRedeemer
tsClient ts = mkStateMachineClient $ StateMachineInstance (tsStateMachine ts) (tsTypedValidator ts)

mapErrorSM :: Contract w s SMContractError a -> Contract w s Text a
mapErrorSM = mapError $ pack . show

startTS :: AssetClass -> Contract (Last TokenSale) s Text ()
startTS token = do
pkh <- Contract.ownPaymentPubKeyHash
tt <- mapErrorSM getThreadToken
let ts = TokenSale
{ tsSeller = pkh
, tsToken = token
, tsTT = tt
}
client = tsClient ts
void $ mapErrorSM $ runInitialise client (Just 0) mempty
tell $ Last $ Just ts
logInfo $ "started token sale " ++ show ts

setPrice :: TokenSale -> Integer -> Contract w s Text ()
setPrice ts p = void $ mapErrorSM $ runStep (tsClient ts) $ SetPrice p

addTokens :: TokenSale -> Integer -> Contract w s Text ()
addTokens ts n = void (mapErrorSM $ runStep (tsClient ts) $ AddTokens n)

buyTokens :: TokenSale -> Integer -> Contract w s Text ()
buyTokens ts n = void $ mapErrorSM $ runStep (tsClient ts) $ BuyTokens n

withdraw :: TokenSale -> Integer -> Integer -> Contract w s Text ()
withdraw ts n l = void $ mapErrorSM $ runStep (tsClient ts) $ Withdraw n l

close :: TokenSale -> Contract w s Text ()
close ts = void $ mapErrorSM $ runStep (tsClient ts) Close

type TSStartSchema =
Endpoint "start" (CurrencySymbol, TokenName)
type TSUseSchema =
Endpoint "set price" Integer
.\/ Endpoint "add tokens" Integer
.\/ Endpoint "buy tokens" Integer
.\/ Endpoint "withdraw" (Integer, Integer)
.\/ Endpoint "close" ()

startEndpoint :: Contract (Last TokenSale) TSStartSchema Text ()
startEndpoint = forever
$ handleError logError
$ awaitPromise
$ endpoint @"start" $ startTS . AssetClass

useEndpoints' :: ( HasEndpoint "set price" Integer s
, HasEndpoint "add tokens" Integer s
, HasEndpoint "buy tokens" Integer s
, HasEndpoint "withdraw" (Integer, Integer) s
, HasEndpoint "close" () s
)
=> TokenSale
-> Promise () s Text ()
useEndpoints' ts = setPrice' `select` addTokens' `select` buyTokens' `select` withdraw' `select` close'
where
setPrice' = endpoint @"set price" $ \p -> handleError logError (setPrice ts p)
addTokens' = endpoint @"add tokens" $ \n -> handleError logError (addTokens ts n)
buyTokens' = endpoint @"buy tokens" $ \n -> handleError logError (buyTokens ts n)
withdraw' = endpoint @"withdraw" $ \(n, l) -> handleError logError (withdraw ts n l)
close' = endpoint @"close" $ \() -> handleError logError (close ts)

useEndpoints :: TokenSale -> Contract () TSUseSchema Text ()
useEndpoints = forever . awaitPromise . useEndpoints'
4 changes: 4 additions & 0 deletions code/week08/test/Spec.hs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ module Main
) where

import qualified Spec.Model
import qualified Spec.ModelWithClose
import qualified Spec.Trace
import qualified Spec.TraceWithClose
import Test.Tasty

main :: IO ()
Expand All @@ -12,5 +14,7 @@ main = defaultMain tests
tests :: TestTree
tests = testGroup "token sale"
[ Spec.Trace.tests
, Spec.TraceWithClose.tests
, Spec.Model.tests
, Spec.ModelWithClose.tests
]
Loading

0 comments on commit dc86a1b

Please sign in to comment.