Exercise choice based on template instance

I have an instance t of a template T and want to exercise a choice on it.
However, the exercise function requires a ContractId T argument.

Is there a way I can exercise a choice based on just the template instance t?

1 Like

Short answer is “no”. Here is a slightly longer explanation.

A DAML program is a piece of code that interacts with a remote ledger. Contracts are things that exist on the ledger, and, crucially, only on the ledger; you never have a contract in your (running) DAML program. What you can have in your DAML program is one of two things:

  • The payload of a contract, i.e. a piece of data that holds the same fields as the contract does. The shape of that data structure is defined implicitly by a template declaration, but as far as your DAML program is concerned, it really is the same as if you had defined the same fields with a data declaration. Except for the fact that you typically create such a piece of data based on what you recently read from the ledger, there is actually no relationship between that piece of data and any contract on the (remote, off-program) ledger.
  • The contract ID of a contract, which has no meaning by itself and is just an opaque token given to you by the ledger, which you can give back to the ledger at some future point as part of a command that should use said contract.

If you do not have the contract ID, but just a random data structure with the same fields as the contract has on the ledger, in the general case you cannot interact with the "equivalent"contract on the ledger, even should one actually exist. (Though how do you define that? There could be multiple ones with all the same values.).

In the special case where your template defined a key, you can of course reconstruct said key from your payload, but the contract the key points to may not be the same one you got the payload from, as contract keys are essentially mutable references.

Hope that helped.

5 Likes

If you have sufficient authority, you can use createAndExercise. It’s really just shorthand for

do
  cid <- create t
  exercise cid c
3 Likes

Thanks both! The solution I ended up going for was adding a key to my contract template and fetching the ContractId based on the key.

5 Likes

In that case, you may enjoy exerciseByKey.

1 Like