Skip to content

Instantly share code, notes, and snippets.

@robertwb
Last active March 27, 2021 07:05
Show Gist options
  • Save robertwb/616fc37929d96ca526fb60053531b76f to your computer and use it in GitHub Desktop.
Save robertwb/616fc37929d96ca526fb60053531b76f to your computer and use it in GitHub Desktop.
Plutus Playground Smart Contract
-- A game with two players. Player 1 thinks of a secret word
-- and uses its hash, and the game validator script, to lock
-- some funds (the prize) in a pay-to-script transaction output.
-- Player 2 guesses the word by attempting to spend the transaction
-- output. If the guess is correct, the validator script releases the funds.
-- If it isn't, the funds stay locked.
import Control.Monad (void)
import qualified Data.ByteString.Char8 as C
import Language.Plutus.Contract
import qualified Language.PlutusTx as PlutusTx
import Language.PlutusTx.Prelude hiding (pure, (<$>))
import Ledger (Address, Validator, ValidatorCtx, Value, scriptAddress)
import qualified Ledger.Constraints as Constraints
import qualified Ledger.Typed.Scripts as Scripts
import Playground.Contract
import qualified Prelude
------------------------------------------------------------
data Liveness = Alive | Dead
newtype HashedString = HashedString ByteString deriving newtype PlutusTx.IsData
PlutusTx.makeLift ''HashedString
newtype ClearString = ClearString ByteString deriving newtype PlutusTx.IsData
PlutusTx.makeLift ''ClearString
newtype Product = Product Integer deriving newtype PlutusTx.IsData
PlutusTx.makeLift ''Product
-- newtype Factors = Factors Integer Integer deriving newtype PlutusTx.IsData
data Factors =
Factors
{ factor1d :: Integer
, factor2d :: Integer
}
deriving stock (Show, Generic)
PlutusTx.makeIsData ''Factors
PlutusTx.makeLift ''Factors
type GameSchema =
BlockchainActions
.\/ Endpoint "lock" LockParams
.\/ Endpoint "guess" GuessParams
data Game
instance Scripts.ScriptType Game where
type instance RedeemerType Game = Factors
type instance DatumType Game = Product
gameInstance :: Scripts.ScriptInstance Game
gameInstance = Scripts.validator @Game
$$(PlutusTx.compile [|| validateGuess2 ||])
$$(PlutusTx.compile [|| wrap ||]) where
wrap = Scripts.wrapValidator @Product @Factors
-- create a data script for the guessing game by hashing the string
-- and lifting the hash to its on-chain representation
hashString :: String -> HashedString
hashString = HashedString . sha2_256 . C.pack
-- create a redeemer script for the guessing game by lifting the
-- string to its on-chain representation
clearString :: String -> ClearString
clearString = ClearString . C.pack
-- | The validation function (Datum -> Redeemer -> ValidatorCtx -> Bool)
validateGuess :: HashedString -> ClearString -> ValidatorCtx -> Bool
validateGuess (HashedString actual) (ClearString guess') _ = actual == sha2_256 guess'
validateGuess2 :: Product -> Factors -> ValidatorCtx -> Bool
validateGuess2 (Product product) (Factors factor1 factor2) _ =
factor1 > 1 && factor2 > 1 && factor1 * factor2 == product
&& (product `modulo` factor1) == 0
-- && (product `mod` factor) == 0
-- && (remainder < 1) && (remainder > (-1))
-- | The validator script of the game.
gameValidator :: Validator
gameValidator = Scripts.validatorScript gameInstance
-- | The address of the game (the hash of its validator script)
gameAddress :: Address
gameAddress = Ledger.scriptAddress gameValidator
-- | Parameters for the "lock" endpoint
data LockParams = LockParams
{ product :: Integer
, amount :: Value
}
deriving stock (Prelude.Eq, Prelude.Show, Generic)
deriving anyclass (FromJSON, ToJSON, IotsType, ToSchema, ToArgument)
-- | Parameters for the "guess" endpoint
data GuessParams = GuessParams
{ factor1 :: Integer, factor2 :: Integer
}
deriving stock (Prelude.Eq, Prelude.Show, Generic)
deriving anyclass (FromJSON, ToJSON, IotsType, ToSchema, ToArgument)
-- | The "lock" contract endpoint. See note [Contract endpoints]
lock :: AsContractError e => Contract GameSchema e Liveness
lock = do
LockParams secret amt <- endpoint @"lock" @LockParams
let tx = Constraints.mustPayToTheScript (Product secret) amt
void (submitTxConstraints gameInstance tx)
return Alive
-- | The "guess" contract endpoint. See note [Contract endpoints]
guess :: AsContractError e => Contract GameSchema e Liveness
guess = do
GuessParams factor1 factor2 <- endpoint @"guess" @GuessParams
unspentOutputs <- utxoAt gameAddress
let redeemer = Factors factor1 factor2
tx = collectFromScript unspentOutputs redeemer
void (submitTxConstraintsSpending gameInstance unspentOutputs tx)
return Alive
game :: AsContractError e => Contract GameSchema e Liveness
game = lock `select` guess
{- Note [Contract endpoints]
A contract endpoint is a function that uses the wallet API to interact with the
blockchain. We can look at contract endpoints from two different points of view.
1. Contract users
Contract endpoints are the visible interface of the contract. They provide a
UI (HTML form) for entering the parameters of the actions we may take as part
of the contract.
2. Contract authors
As contract authors we define endpoints as functions that return a value of
type 'MockWallet ()'. This type indicates that the function uses the wallet API
to produce and spend transaction outputs on the blockchain.
Endpoints can have any number of parameters: 'lock' has two
parameters, 'guess' has one and 'startGame' has none. For each endpoint we
include a call to 'mkFunction' at the end of the contract definition. This
causes the Haskell compiler to generate a schema for the endpoint. The Plutus
Playground then uses this schema to present an HTML form to the user where the
parameters can be entered.
-}
endpoints :: AsContractError e => Contract GameSchema e Liveness
endpoints = game
mkSchemaDefinitions ''GameSchema
$(mkKnownCurrencies [])
[0,[{"simulationWallets":[{"simulatorWalletWallet":{"getWallet":1},"simulatorWalletBalance":{"getValue":[[{"unCurrencySymbol":""},[[{"unTokenName":""},10]]]]}},{"simulatorWalletWallet":{"getWallet":2},"simulatorWalletBalance":{"getValue":[[{"unCurrencySymbol":""},[[{"unTokenName":""},10]]]]}}],"simulationName":"Simulation 1","simulationId":1,"simulationActions":[{"caller":{"getWallet":1},"argumentValues":{"endpointDescription":{"getEndpointDescription":"lock"},"argument":{"contents":[["product",{"s":1,"e":1,"c":[15],"tag":"FormIntegerF"}],["amount",{"getValue":[[{"unCurrencySymbol":""},[[{"unTokenName":""},3]]]],"tag":"FormValueF"}]],"tag":"FormObjectF"}},"tag":"CallEndpoint"},{"blocks":10,"tag":"AddBlocks"},{"caller":{"getWallet":2},"argumentValues":{"endpointDescription":{"getEndpointDescription":"guess"},"argument":{"contents":[["factor1",{"s":1,"e":0,"c":[3],"tag":"FormIntegerF"}],["factor2",{"s":1,"e":0,"c":[5],"tag":"FormIntegerF"}]],"tag":"FormObjectF"}},"tag":"CallEndpoint"},{"blocks":10,"tag":"AddBlocks"}]}]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment