How to restrict the number of contracts?

I have a template that only needs to be created once. Does daml have any functionality to prevent the creation of contracts using that template when there is already a non archived contract from that template in the ledger.

something like “key 0 : Int”

2 Likes

If I’m not mistaken I think you can resort to making the key maintainers themselves the only field of the contract key, which means that you cannot have more than one active contract of a given template for the set of signatories that maintain the key.

Consider that Daml is designed to express distributed processes, the idea of a “universal singleton” doesn’t play nicely with that.

Notice that every key must have a set of maintainers, which in turn must be a (non-strict) subset of the contract signatories. You can read more about it in the documentation.

4 Likes

Yes, I would recommend exactly what @stefanobaghino-da recommends above. Other than using dirty tricks like hard-coding a party identifier you can’t restrict a template to a single instance. Think about Daml’s privacy model. Support Alice creates an instance of the template. Now Bob comes along. Thanks to Daml privacy he doesn’t know about Alice’s contract, nor does he have any right to know anything about it. So what should happen when Bob tries to create an instance? If he got an error “Can’t create because there already is an instance”, he has learnt something about the state of the Ledger he is not entitled to.

Rather, think of Alice and Bob’s contract instances as being part of different application instances on the same Ledger. Imagine the template in question was the initial contract used to bootstrap an application.

template App
  with
    initiator : Party
    app_id : Text
  where
    signatory initiator
    key this : App
    maintainer key.initiator

Now an application instance is identified by the App that bootstrapped it. And thanks to contract key uniqueness, App is unique within the application instance that it bootstrapped.

3 Likes

Thanks. This was really helpful.
Would you be able to point me in the direction of where I could learn about that dirty hard-coding trick you mentioned.
The only other idea I have for restricting the number of contracts created with this template without violating the privacy rules you mentioned, would be to have a hard coded time period after ledger creation when the template can be used. However I can’t find a way to implement that.

1 Like

Have a look at this answer for how to do it: Indicate list of OR signatories - #3 by bernhard

But let me be clear: I reeeeally don’t recommend doing this. partyFromText is a hack and shouldn’t exist in my opinion. If you do this, your application will be entirely non-portable. You won’t be able to migrate it from one ledger to another smoothly.

3 Likes