Can one use ContractId's as keys in a Map?

More specifically, can one implement the keyFromText method of MapKey typeclass?

Let me first answer the non-specific question: Can you use ContractIds as map keys? The answer to that is yes provided you can use DAML-LF 1.dev (with the usual caveats of being unstable and not suited for production). In DAML-LF 1.dev (put build-options: ["--target=1.dev"] in your daml.yaml to use it) you get acess to the DA.Map module which provides a generic Map type which supports ContractIds as keys and does not require a MapKey instance. Instead it’s based on the builtin DAML-LF value ordering which you get for ContractIds in 1.dev.

For the specific question, you are unfortunately out of luck. You cannot convert between Text and ContractId. Apart from encouraging users to treat ContractIds as opaque blobs there is a technical reason for this: ContractIds created in the current transaction look a bit different from the final one as ledgers can tweak it a bit (how they tweak it depends on the ledger). Being able to observe the difference between a contract in the current transaction and one created in another transaction would break compositionality so we avoid that.

This restriction does not apply to off-ledger code like DAML Script or DAML Triggers and in fact in DAML-LF 1.dev the show instance of ContractId will give you the actual ContractId instead of <contract-id> but only in triggers and DAML Script. I do have a usecase in mind where I want to go from Text to ContractId in DAML Script and I’ve toyed with the idea of adding it to the DAML Script API but so far this isn’t possible.

1 Like

Thank you.