What is the best way convert in JavaScript the JSON representation of Daml data retrieved from the ledger to an instance of the generated JavaScript class corresponding to that Daml type?
Would you be able to provide a bit more context or an example of what you are trying to achieve ?
I assume you’re talking about the code generator we provide with the daml codegen js
command.
First, every template gets a generated companion of the same name as the template. For example, from the tutorial, here User.Message
is the companion for template Message
:
const messagesResult = userContext.useStreamQueries(User.Message);
The first thing to note is that if you use the functions in @daml/types
or @daml/react
that take companions, like useStreamQueries
, the decoding task is done for you. The format that comes back is the final format provided by the JS bindings-and-codegen; there is no further decoded form than that one.
Now, what is that format? First, from the type of useStreamQueries
, and the generated type of the Message
companion,
export declare interface MessageInterface {
Archive: damlTypes.Choice<Message, pkgd14e08374fc7197d6a0de468c968ae8ba3aadbf9315476fd39071831f5923662.DA.Internal.Template.Archive, {}, undefined> & damlTypes.ChoiceFrom<damlTypes.Template<Message, undefined>>;
}
export declare const Message:
damlTypes.Template<Message, undefined, '305b0bfb5675213760bc3397a9015f641553d8ee6276a1a4fcc1b9668abbcddd:User:Message'> &
damlTypes.ToInterface<Message, never> &
MessageInterface;
messagesResult
has type QueryResult<Message, undefined, 'hashhere...:User:Message'>
, where Message
is the type of contracts included with the result. What’s that type?
export declare type Message = {
sender: damlTypes.Party;
receiver: damlTypes.Party;
content: string;
};
Note that there is no class here; a Message
is just an object.
That doesn’t mean that values that come back from JSON API can be used directly as values of code-generated types; things like maps have special decoding. If you are using JSON API directly for any reason (and I really recommend not doing this, but you may have your own reasons), every companion is also one of these. Use this at your own risk; as it is marked internal
, it is meant for internal use by @daml/ledger
and comes with no API compatibility guarantees.
You can see counterparts to anything I’ve pasted above by using Daml Studio; for example, if you open that tsx
file with the Message
reference, you can ctrl-click into it and see the generated type.
Thank, you, Stephen, I’m checking out the tutorial.