Created
July 27, 2021 02:48
-
-
Save franleplant/34ac8e73a825d2036d4228ea2486df08 to your computer and use it in GitHub Desktop.
Plutus pioneer program week04 homework solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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, unpack) | |
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 | |
data PayParams = PayParams | |
{ ppRecipient :: PubKeyHash | |
, ppLovelace :: Integer | |
} deriving (Show, Generic, FromJSON, ToJSON) | |
type PaySchema = Endpoint "pay" PayParams | |
payContract :: Contract () PaySchema Text () | |
payContract = do | |
params <- endpoint @"pay" | |
let recipient = ppRecipient params | |
let amount = lovelaceValueOf $ ppLovelace params | |
let tx = mustPayToPubKey recipient amount | |
Contract.handleError | |
(\err -> Contract.logError $ "caught: " ++ unpack err) | |
$ void $ submitTx tx | |
payContract | |
-- A trace that invokes the pay endpoint of payContract on Wallet 1 twice, each time with Wallet 2 as | |
-- recipient, but with amounts given by the two arguments. There should be a delay of one slot | |
-- after each endpoint call. | |
payTrace :: Integer -> Integer -> EmulatorTrace () | |
payTrace amount1 amount2 = do | |
h1 <- activateContractWallet (Wallet 1) payContract | |
let pkh = pubKeyHash $ walletPubKey $ Wallet 2 | |
callEndpoint @"pay" h1 $ PayParams { ppRecipient = pkh, ppLovelace = amount1 } | |
void $ Emulator.waitNSlots 1 | |
callEndpoint @"pay" h1 $ PayParams { ppRecipient = pkh, ppLovelace = amount2 } | |
payTest1 :: IO () | |
payTest1 = runEmulatorTraceIO $ payTrace 1000000 2000000 | |
payTest2 :: IO () | |
payTest2 = runEmulatorTraceIO $ payTrace 1000000000 2000000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment