arjun a
arjun a

Reputation: 161

How to have either of two conditions evaluated in the `ensure` clause?

How can I pass values to the ensure clause in the form of an or condition?

template ABC

ensure (abcd)? (xyz) || (abc)

Is it possible to do this (possibly with some other syntax) to pass ensure two predicates, either of which have to be evaluated?

Upvotes: 0

Views: 229

Answers (1)

stefanobaghino
stefanobaghino

Reputation: 12794

If you just want to express a boolean expression for which either of two values is true, || will do.

The syntax you are using, though, suggests that you may be interested in expressing something like the following (in pseudo-code):

if abcd is true
  fail to create the contract if xyz is true
else
  fail to create the contract if abc is true

The ensure clause takes as a parameter a "predicate that must be true, otherwise, contract creation will fail" (docs here).

A predicate is simply a function that returns a boolean value, either true or false.

Contrary to other languages (the syntax you suggest seems to point that you are familiar with either C, C++ or Java), in DAML if is an expression, meaning that it returns a value. This means that you can use it just as you would use the <condition> ? <if_true> : <if_false> construct in, say, Java.

The following example hopefully goes into your direction:

daml 1.2
module Main where

template Main
  with
    owner : Party
    cond1 : Bool
    cond2 : Bool
    cond3 : Bool
  where
    signatory owner
    ensure if cond1 then cond2 else cond3 -- HERE!

test = scenario do
  p <- getParty "party"
  submit p do create $ Main p True True False
  submit p do create $ Main p False False True
  submitMustFail p do create $ Main p False True False

Note that depending on the situation you may want to express the same clause as a single condition using boolean operators:

ensure cond1 && cond2 || cond3

Upvotes: 2

Related Questions