cantonjs-codegen
v0.4.0
Published
Optional DAR-to-TypeScript generator for cantonjs app code from existing Daml artifacts
Maintainers
Readme
cantonjs-codegen
Generate TypeScript types from Daml DAR files for use with cantonjs.
Install
npm install --save-dev cantonjs-codegenUsage
cantonjs-codegen --dar ./model.dar --output ./src/generatedThis reads your DAR file, extracts Daml-LF package definitions, and generates TypeScript modules.
Generated Output
Records
data Asset = Asset with
owner : Party
value : Intexport type Asset = {
readonly owner: string
readonly value: string // Int64 -> string for precision
}Variants
data Result = Success with value : Int
| Failure with reason : Textexport type Result =
| { readonly tag: 'Success'; readonly value: { readonly value: string } }
| { readonly tag: 'Failure'; readonly value: { readonly reason: string } }Enums
data Color = Red | Green | Blueexport type Color = 'Red' | 'Green' | 'Blue'Templates
Templates generate companion const objects with templateId and choice definitions:
export const Asset = {
templateId: '#my-pkg:Main:Asset' as const,
choices: {
Transfer: { name: 'Transfer' as const },
},
} as constType Mapping
| Daml Type | TypeScript Type | Notes |
|-----------|-----------------|-------|
| Int / Int64 | string | Precision preservation |
| Numeric n | string | Arbitrary precision |
| Text | string | |
| Bool | boolean | |
| Party | string | |
| ContractId a | string | |
| Date / Time | string | ISO 8601 |
| Optional a | T \| null | |
| List a | readonly T[] | |
| Map k v | ReadonlyMap<K, V> | |
Using Generated Types with cantonjs
import { createLedgerClient, jsonApi } from 'cantonjs'
import { Asset } from './generated/Main.js'
const client = createLedgerClient({
transport: jsonApi({ url: 'http://localhost:7575', token: jwt }),
actAs: 'Alice::1234',
})
// Type-safe template ID and arguments
const created = await client.createContract(Asset.templateId, {
owner: 'Alice',
value: '100',
})
await client.exerciseChoice(
Asset.templateId,
created.contractId,
Asset.choices.Transfer.name,
{ newOwner: 'Bob' },
)How It Works
- Parse — extract
.dalffiles from the DAR (ZIP) archive using JSZip - Decode — parse Daml-LF protobuf with intern table resolution using protobufjs
- Emit — generate TypeScript modules from decoded type definitions
Requirements
- Node.js >= 18
Related
- cantonjs — Core TypeScript library for Canton
- cantonjs-react — participant-private React hooks for Canton ledger apps
