How to define conditional required variable in DAML

Hi,

Let’s say i have a certain data record that consists of several fields. 2 of such has a conditional dependency meaning that if the first variable is populated than the second must be required and need to be populated as well. How can i define such logic.

Example would be much appreciated.

Hi,

You could use an Optional type and an ensure clause, e.g.

import DA.Optional (isSome)

template T with
    p : Party
    f1 : Optional Int
    f2 : Optional Bool
  where 
    signatory p
 
    ensure isSome f1 == isSome f2

Alternatively, you could directly use the type Optional (Int, Bool) in your template definition.

Matteo

1 Like

Thanks @Matteo_Limberto

Another question:

Given that i have defined a simple variable - How do i define it for a certain party as required and for all the rest of the parties as non-required/optional?

Another question should ideally mean another thread.

Generally speaking there is no mechanism in the Daml language that allows you to make a specific, hard-coded party “special”. This is by design.

One way to think about it is that if you want a party to be special for your application, you still have to account for thee fact that there may be any number of “instances” of your application on a given Daml ledger.

If you want a party to behave specially, you’ll have to encode that in your contracts somehow, for example by gating creation of your contracts to a choice of another contract, which knows which parties are special and which are not.

Conceptually, you can think of it as avoiding global variables and instead making “application instances” with all o fthe “global” variables as parameters, so you can run multiple instances of your application in the same process.

1 Like

If you want to be completely type-safe, encode the permissible combinations of optionals as a variant:

data FirstRequiresSecond a b = Neither
  | Second b
  | Both with
      first : a
      second : b
2 Likes