4

In a DAML contract, how do I extract the name of a party from a Party field?

Currently, toText p gives me Party(Alice). I'd like to only keep the name of the party.

Leonel
  • 28,541
  • 26
  • 76
  • 103

1 Answers1

3

That you care about the precise formatting of the resulting string suggests that you are implementing a codec in DAML. As a general principle DAML excels as a modelling/contract language, but consequently has limited features to support the sort of IO-oriented work this question implies. You are generally better off returning DAML values, and implementing codecs in Java/Scala/C#/Haskell/etc interfacing with the DAML via the Ledger API.

Still, once you have a Text value you also have access to the standard List manipulation functions via unpack, so converting "Party(Alice)" to "Alice" is not too difficult:

daml 1.0 module PartyExtract where

import Base.List

def pack (cs: List Char) : Text =
  foldl (fun (acc: Text) (c: Char) -> acc <> singleton c) "" cs;

def partyToText (p: Party): Text =
  pack $ reverse $ drop 2 $ reverse $ drop 7 $ unpack $ toText p

test foo : Scenario {} = scenario
  let p = 'Alice'
  assert $ "Alice" == partyToText p

In DAML 1.2 the standard library has been expanded, so the code above can be simplified:

daml 1.2
module PartyExtract2
where

import DA.Text

traceDebug : (Show a, Show b) => b -> a -> a
traceDebug b a = trace (show b <> show a) $ a

partyToText : Party -> Text
partyToText p = dropPrefix "'" $ dropSuffix "'" $ traceDebug "show party: " $ show p

foo : Scenario ()
foo = do
  p <- getParty "Alice"
  assert $ "Alice" == (traceDebug "partyToText party: " $ partyToText p)

NOTE: I have left the definition and calls to traceDebug so you can see the exact strings being generated in the scenario trace output.

Recurse
  • 3,557
  • 1
  • 23
  • 36