Canton console filter contract by key

Hello Team,

I am looking for a way to filter active contracts by the contract key in Canton console but no sure how to do that.
And I took a look on ledger_api.acs.filter but doesn’t sound there is way to do with this api. Can you advise please?

participant1.ledger_api.acs.help("filter")
filter(partyId: com.digitalasset.canton.topology.PartyId, templateCompanion: com.daml.ledger.client.binding.TemplateCompanion[T], predicate: com.daml.ledger.client.binding.Contract[T] => Boolean): (partyId: com.digitalasset.canton.topology.PartyId, templateCompanion: com.daml.ledger.client.binding.TemplateCompanion[T], predicate: com.daml.ledger.client.binding.Contract[T] => Boolean): Seq[com.daml.ledger.client.binding.Contract[T]]
To use this function, ensure a code-generated Scala model for the target template exists.
You can refine your search using the `predicate` function argument.

thanks
Dorrit

The Contract[T] contains a key, which you can use in your filter function. I scribbled up a generic utility that would work with any Scala codegen output to decode and search for a key:

  def filterThe[T, K](implicit tc: TemplateCompanion[T] { type key = K }): FilterThe[T, K] =
    new FilterThe(tc)
  final class FilterThe[T, Key](private val tc: TemplateCompanion[T] { type key = Key }) extends AnyVal {
    def byKey(key: Key)(implicit kd: ValueDecoder[Key]): Contract[T] => Boolean =
      c => c.key.exists(kv => kd.read(kv.sum).contains(key))
  }

  // assuming CallablePayout has a key type Long
  filterThe(CallablePayout).byKey(42) // returns a ContractId[CallablePayout] => Boolean