-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hw1.hs
63 lines (54 loc) · 1.98 KB
/
Hw1.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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
module Week04.Homework where
import Data.Aeson (FromJSON, ToJSON)
import Data.Functor (void)
import Data.Text (Text)
import GHC.Generics (Generic)
import Ledger
import Ledger.Ada as Ada
import Ledger.Constraints as Constraints
import Plutus.Contract as Contract
import Plutus.Trace.Emulator as Emulator
import Wallet.Emulator.Wallet -- Wallet needed
import Data.Text (unpack)
data PayParams = PayParams
{ ppRecipient :: PubKeyHash
, ppLovelace :: Integer
} deriving (Show, Generic, FromJSON, ToJSON)
type PaySchema = Endpoint "pay" PayParams
-- Contract w s e a
payContract :: Contract () PaySchema Text ()
payContract = do
pp <- endpoint @"pay"
let tx = mustPayToPubKey (ppRecipient pp) $ lovelaceValueOf $ ppLovelace pp
void $ submitTx tx
payContract -- recursively calls the contract (endpoint, runs, endpoint)
contractHandler :: Contract () PaySchema () ()
contractHandler = do
Contract.handleError
(\err -> Contract.logError $ "caught: " ++ unpack err)
payContract
contractHandler -- same recursion
payTrace :: Integer -> Integer -> EmulatorTrace ()
payTrace xs ys = do -- "do" notation
h <- activateContractWallet (Wallet 1) contractHandler
let phk2 = pubKeyHash $ walletPubKey $ Wallet 2
callEndpoint @"pay" h $ PayParams
{ ppRecipient = phk2
, ppLovelace = xs
}
void $ Emulator.waitNSlots 1 -- void $ to ignore the result (of waiting)
callEndpoint @"pay" h $ PayParams
{ ppRecipient = phk2
, ppLovelace = ys
}
void $ Emulator.waitNSlots 1
payTest1 :: IO ()
payTest1 = runEmulatorTraceIO $ payTrace 1000000 2000000
payTest2 :: IO ()
payTest2 = runEmulatorTraceIO $ payTrace 1000000000 2000000