Skip to content
Discussions/App Development/Before creating party and user, I need to judge whether they exist. If they exist, they will not be created. How should I write the initialization script?Forum ↗

Before creating party and user, I need to judge whether they exist. If they exist, they will not be created. How should I write the initialization script?

App Development2 posts258 views4 likesLast activity Feb 2023
SK
skylornaOP
Feb 2023

Before creating party and user, I need to judge whether they exist. If they exist, they will not be created. How should I write the initialization script?
If it is the following scripts, how should they be optimized ?

val PATY1= pn1.parties.enable(“PATY1”, waitForDomain = DomainChoice.All)
val PATY2= pn1.parties.enable(“PATY2”, waitForDomain = DomainChoice.All)
val PATY3= pn1.parties.enable(“PATY3”, waitForDomain = DomainChoice.All)
pn1.ledger_api.users.create(
id = “myuser”,
actAs = Set(PATY1.toLf,PATY2.toLf,PATY3.toLf),
primaryParty = Some(PATY1.toLf),
readAs = Set(PATY1.toLf,PATY2.toLf,PATY3.toLf),
)

CO
cocreature
Feb 2023

There are a few different options here. A relatively easy one is to check if the user exists first and use that as a proxy for whether the parties have already been allocated. Something like this:

Try(pn1.ledger_api.users.get("myuser") match {
case Success(_ ) => // User exists do nothing
case Failure(_) =>
  val PATY1= pn1.parties.enable(“PATY1”, waitForDomain = DomainChoice.All)
  val PATY2= pn1.parties.enable(“PATY2”, waitForDomain = DomainChoice.All)
  val PATY3= pn1.parties.enable(“PATY3”, waitForDomain = DomainChoice.All)
  pn1.ledger_api.users.create(
    id = “myuser”,
    actAs = Set(PATY1.toLf,PATY2.toLf,PATY3.toLf),
    primaryParty = Some(PATY1.toLf),
    readAs = Set(PATY1.toLf,PATY2.toLf,PATY3.toLf),
)

This isn’t completely reliable if you somehow ended up in a situation where the parties got allocated partially but the user did not yet get created but often it can be good enough.

Alternatively, you can actually check if the party already exists relying on Canton PartyId Hint Guarantees - #2 by cocreature.

For that try something like this:

import com.digitalasset.canton.topology.PartyId
import scala.util.{Try, Success, Failure}

def allocateOrGetParty(hint: String): PartyId =
  pn1.parties.list().find(_.party.uid.id == hint) match {
    case None => pn1.parties.enable(hint)
   case Some(p) => p.party
  }

val PATY1 = allocateOrGetParty("PATY1")
val PATY2 = allocateOrGetParty("PATY2")
val PATY3 = allocateOrGetParty("PATY3")

Try(pn1.ledger_api.users.get("myuser")) match {
  case Success(_) => // user already exists
  case Failure(_) => 
    pn1.ledger_api.users.create(
      id = “myuser”,
      actAs = Set(PATY1.toLf,PATY2.toLf,PATY3.toLf),
      primaryParty = Some(PATY1.toLf),
      readAs = Set(PATY1.toLf,PATY2.toLf,PATY3.toLf),
    )
}
← Back to Discussions