@canton-network/core-ledger-client 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -123,7 +123,7 @@ const asGrpcError = (e) => {
123
123
  }
124
124
  throw e;
125
125
  };
126
- // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
126
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js
127
127
  function _typeof(o) {
128
128
  "@babel/helpers - typeof";
129
129
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -132,23 +132,23 @@ function _typeof(o) {
132
132
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
133
133
  }, _typeof(o);
134
134
  }
135
- // \0@oxc-project+runtime@0.155.0/helpers/esm/toPrimitive.js
136
- function toPrimitive(t, r) {
135
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/toPrimitive.js
136
+ function toPrimitive(t, e) {
137
137
  if ("object" != _typeof(t) || !t) return t;
138
- var e = t[Symbol.toPrimitive];
139
- if (void 0 !== e) {
140
- var i = e.call(t, r || "default");
138
+ var r;
139
+ if ("undefined" != typeof Symbol && void 0 !== (r = t[Symbol.toPrimitive])) {
140
+ var i = r.call(t, e || "default");
141
141
  if ("object" != _typeof(i)) return i;
142
142
  throw new TypeError("@@toPrimitive must return a primitive value.");
143
143
  }
144
- return ("string" === r ? String : Number)(t);
144
+ return ("string" === e ? String : Number)(t);
145
145
  }
146
- // \0@oxc-project+runtime@0.155.0/helpers/esm/toPropertyKey.js
146
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/toPropertyKey.js
147
147
  function toPropertyKey(t) {
148
148
  var i = toPrimitive(t, "string");
149
149
  return "symbol" == _typeof(i) ? i : i + "";
150
150
  }
151
- // \0@oxc-project+runtime@0.155.0/helpers/esm/defineProperty.js
151
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/defineProperty.js
152
152
  function _defineProperty(e, r, t) {
153
153
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
154
154
  value: t,
@@ -168,7 +168,7 @@ function isValidPostEndpoint(resource) {
168
168
  var LedgerClient = class {
169
169
  constructor({ baseUrl, accessTokenProvider, version }) {
170
170
  _defineProperty(this, "clients", void 0);
171
- _defineProperty(this, "clientVersion", "3.5");
171
+ _defineProperty(this, "clientVersion", "3.6");
172
172
  _defineProperty(this, "initialized", false);
173
173
  _defineProperty(this, "accessTokenProvider", void 0);
174
174
  _defineProperty(this, "logger", (0, _logtape_logtape.getLogger)([
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["getLogger","ErrorInfo","RetryInfo","supportedLedgerApiVersions","LedgerGetRoutes","LedgerPostRoutes","getLogger","createClient"],"sources":["../src/ledger-api-utils.ts","../src/ledger-client.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { LedgerClient } from './ledger-client.js'\n\nimport type { Types } from './ledger-client.js'\nimport type { PartyId } from '@canton-network/core-types'\n\nimport { ErrorInfo, RetryInfo } from '@canton-network/core-ledger-proto'\nimport { getLogger } from '@logtape/logtape'\n\ntype Completion = Types['Completion']['value']\nexport type JSContractEntry = Types['JsContractEntry']\nexport type JsCantonError = Types['JsCantonError']\n\nconst COMPLETIONS_LIMIT = '100'\nconst COMPLETIONS_STREAM_IDLE_TIMEOUT_MS = '1000'\n\nconst logger = getLogger(['core', 'ledger-client', 'ledger-api-utils'])\n\n/**\n * Polls the completions endpoint until\n * the completion with the given (userId, commandId, submissionId) is returned.\n * Then returns the updateId, synchronizerId and recordTime of that completion.\n *\n * Polls until the completion shows up unless `maxAttempts` is given, in which case\n * it throws once that many polls found nothing (e.g. the completion was pruned).\n */\nexport async function awaitCompletion(\n ledgerClient: LedgerClient,\n ledgerEnd: number,\n partyId: PartyId,\n userId: string,\n commandIdOrSubmissionId: string,\n maxAttempts = Infinity\n): Promise<Completion> {\n const responses = await ledgerClient.postWithRetry(\n '/v2/commands/completions',\n {\n userId,\n parties: [partyId],\n beginExclusive: ledgerEnd,\n },\n defaultRetryableOptions,\n {\n query: {\n limit: COMPLETIONS_LIMIT,\n stream_idle_timeout_ms: COMPLETIONS_STREAM_IDLE_TIMEOUT_MS,\n },\n }\n )\n\n const completions = responses.filter(\n (r) => r.completionResponse && 'Completion' in r.completionResponse\n )\n\n const wantedCompletion = responses.find((r) => {\n if (r.completionResponse && 'Completion' in r.completionResponse) {\n const completion = r.completionResponse.Completion?.value\n if (!completion) {\n return false\n }\n return (\n completion.userId === userId &&\n (completion.commandId === commandIdOrSubmissionId ||\n completion.submissionId === commandIdOrSubmissionId)\n )\n }\n return false\n })\n\n if (\n wantedCompletion?.completionResponse &&\n 'Completion' in wantedCompletion.completionResponse\n ) {\n const completion = wantedCompletion.completionResponse.Completion.value\n const status = completion.status\n if (status && status.code !== 0) {\n // status.code is 0 for success\n throw asGrpcError(status)\n }\n return completion\n } else {\n const lastCompletion = completions[completions.length - 1]\n const newLedgerEnd =\n lastCompletion?.completionResponse &&\n 'Completion' in lastCompletion.completionResponse\n ? lastCompletion.completionResponse.Completion.value.offset\n : undefined\n\n if (maxAttempts <= 1) {\n throw new Error(\n `Completion for ${commandIdOrSubmissionId} not found`\n )\n }\n\n return awaitCompletion(\n ledgerClient,\n newLedgerEnd || ledgerEnd, // !newLedgerEnd implies response was empty\n partyId,\n userId,\n commandIdOrSubmissionId,\n maxAttempts - 1\n )\n }\n}\n\nexport type RetryableOptions = {\n retries: number\n delayMs: number\n cantonErrorKeys: string[]\n}\nexport const defaultRetryableOptions: RetryableOptions = {\n retries: 5,\n delayMs: 3000,\n cantonErrorKeys: [\n 'SEQUENCER_REQUEST_FAILED',\n 'SEQUENCER_BACKPRESSURE',\n 'SUBMISSION_ALREADY_IN_FLIGHT',\n 'LOCAL_VERDICT_TIMEOUT',\n 'NOT_SEQUENCED_TIMEOUT',\n 'NO_VIEW_WITH_VALID_RECIPIENTS',\n ],\n}\n\nexport async function retryable<T>(\n fn: () => Promise<T>,\n retryableOptions: RetryableOptions\n): Promise<T> {\n for (let attempts = 1; attempts <= retryableOptions.retries; attempts++) {\n try {\n return await fn()\n } catch (err: unknown) {\n const grpcError = asGrpcError(err)\n const message: string = grpcError.message\n const shouldRetry =\n retryableOptions.cantonErrorKeys.length === 0 ||\n retryableOptions.cantonErrorKeys.some((key) =>\n message.includes(key)\n )\n if (attempts < retryableOptions.retries && shouldRetry) {\n logger.warn(\n `Caught retryiable error: ${message}. Retrying attempt ${attempts} of ${retryableOptions.retries}...`\n )\n await new Promise((res) =>\n setTimeout(res, retryableOptions.delayMs)\n )\n // continue to next attempt\n } else {\n throw grpcError\n }\n }\n }\n throw new Error('retryable: Exceeded maximum retries without throwing.')\n}\n\n// Helper for differentiating ledger errors from others and satisfying TS when checking error properties\nexport const isJsCantonError = (e: unknown): e is JsCantonError =>\n typeof e === 'object' &&\n e !== null &&\n 'code' in e &&\n 'cause' in e &&\n 'errorCategory' in e\n\nexport const asJsCantonError = (e: unknown): JsCantonError => {\n if (isJsCantonError(e)) {\n return e\n } else {\n throw e\n }\n}\n\nexport const asGrpcError = (\n e: unknown\n): {\n code: number\n message: string\n errorInfo: ErrorInfo | undefined\n retryInfo: RetryInfo | undefined\n} => {\n let errorInfo: ErrorInfo | undefined\n let retryInfo: RetryInfo | undefined\n\n if (\n typeof e === 'object' &&\n e !== null &&\n 'code' in e &&\n 'message' in e &&\n 'details' in e &&\n Array.isArray(e.details)\n ) {\n const code = e.code as number\n const message = e.message as string\n\n for (const detail of e.details) {\n if (\n detail.typeUrl === 'type.googleapis.com/google.rpc.ErrorInfo' &&\n typeof detail.value === 'string'\n ) {\n try {\n errorInfo = ErrorInfo.fromBinary(\n Buffer.from(detail.value, 'base64')\n )\n } catch {\n //if parsing fails, we skip adding ErrorInfo\n }\n } else if (\n detail.typeUrl === 'type.googleapis.com/google.rpc.RetryInfo' &&\n typeof detail.value === 'string'\n ) {\n try {\n retryInfo = RetryInfo.fromBinary(\n Buffer.from(detail.value, 'base64')\n )\n } catch {\n //if parsing fails, we skip adding RetryInfo\n }\n }\n }\n return { code, message, errorInfo, retryInfo }\n }\n\n // Not a gRPC error, rethrow\n throw e\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n supportedLedgerApiVersions,\n type LedgerApiVersion,\n type LedgerCommonPaths,\n type LedgerCommonSchemas,\n LedgerGetRoutes,\n LedgerPostRoutes,\n} from '@canton-network/core-ledger-client-types'\nimport createClient, { type Client, type FetchOptions } from 'openapi-fetch'\nimport type { PartyId } from '@canton-network/core-types'\nimport {\n asJsCantonError,\n defaultRetryableOptions,\n retryable,\n type RetryableOptions,\n} from './ledger-api-utils.js'\nimport type { AccessTokenProvider } from '@canton-network/core-wallet-auth'\nimport { getLogger } from '@logtape/logtape'\n\nexport const supportedVersions = supportedLedgerApiVersions\n\nexport type SupportedVersions = LedgerApiVersion\n\ntype paths = LedgerCommonPaths\n\ntype SchemaByVersion<Name extends keyof LedgerCommonSchemas> =\n LedgerCommonSchemas[Name]\n\ntype ClientsByVersion = {\n [V in SupportedVersions]: Client<paths>\n}\n\nexport type UserSchema = SchemaByVersion<'User'>\n\nexport type Types = LedgerCommonSchemas\n\n// A conditional type that filters the set of OpenAPI path names to those that actually have a defined POST operation.\n// Any path without a POST is excluded via the `never` branch of the conditional\nexport type PatchEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n patch: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\n// Given a pathname (string) that has a POST, this helper type extracts the request body type from the OpenAPI definition.\nexport type PatchRequest<Path extends PatchEndpoint> = paths[Path] extends {\n patch: { requestBody: { content: { 'application/json': infer Req } } }\n}\n ? Req\n : never\n\n// Given a pathname (string) that has a POST, this helper type extracts the 200 response type from the OpenAPI definition.\nexport type PatchResponse<Path extends PatchEndpoint> = paths[Path] extends {\n patch: {\n responses: { 200: { content: { 'application/json': infer Res } } }\n }\n}\n ? Res\n : never\n\n// A conditional type that filters the set of OpenAPI path names to those that actually have a defined POST operation.\n// Any path without a POST is excluded via the `never` branch of the conditional\nexport type PostEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n post: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\n// Given a pathname (string) that has a POST, this helper type extracts the request body type from the OpenAPI definition.\nexport type PostRequest<Path extends PostEndpoint> = paths[Path] extends {\n post: { requestBody: { content: { 'application/json': infer Req } } }\n}\n ? Req\n : never\n\n// Given a pathname (string) that has a POST, this helper type extracts the 200 response type from the OpenAPI definition.\nexport type PostResponse<Path extends PostEndpoint> = paths[Path] extends {\n post: { responses: { 200: { content: { 'application/json': infer Res } } } }\n}\n ? Res\n : never\n\n// Similar as above, for GETs\nexport type GetEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n get: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\nexport function isValidGetEndpoint(resource: string): resource is GetEndpoint {\n return LedgerGetRoutes.has(resource)\n}\n\nexport function isValidPostEndpoint(\n resource: string\n): resource is PostEndpoint {\n return LedgerPostRoutes.has(resource)\n}\n\n// Similar as above, for GETs\nexport type GetResponse<Path extends GetEndpoint> = paths[Path] extends {\n get: { responses: { 200: { content: { 'application/json': infer Res } } } }\n}\n ? Res\n : never\n\nexport type GenerateTransactionResponse =\n SchemaByVersion<'GenerateExternalPartyTopologyResponse'>\n\nexport type AllocateExternalPartyResponse =\n SchemaByVersion<'AllocateExternalPartyResponse'>\nexport type OnboardingTransactions = NonNullable<\n SchemaByVersion<'AllocateExternalPartyRequest'>['onboardingTransactions']\n>\n\nexport type MultiHashSignatures = NonNullable<\n SchemaByVersion<'AllocateExternalPartyRequest'>['multiHashSignatures']\n>\nexport type PrepareSubmissionResponse =\n SchemaByVersion<'JsPrepareSubmissionResponse'>\n\n// Any options the client accepts besides body/params\ntype ExtraPostOpts = Omit<FetchOptions<paths>, 'body' | 'params'>\n\nexport class LedgerClient {\n // privately manage the active connected version and associated client codegen\n private readonly clients: ClientsByVersion\n private clientVersion: SupportedVersions = '3.5'\n private initialized: boolean = false\n private accessTokenProvider: AccessTokenProvider\n private readonly logger = getLogger([\n 'core',\n 'ledger-client',\n 'LedgerClient',\n ])\n private synchronizerId: string | undefined\n baseUrl: URL\n\n constructor({\n baseUrl,\n accessTokenProvider,\n version,\n }: {\n baseUrl: URL\n accessTokenProvider: AccessTokenProvider\n version?: SupportedVersions\n }) {\n this.accessTokenProvider = accessTokenProvider\n\n const authenticatedFetch = async (\n url: RequestInfo,\n options: RequestInit = {}\n ) => {\n const accessToken = await this.accessTokenProvider.getAccessToken()\n const headers = new Headers(options.headers)\n if (accessToken) {\n headers.set('Authorization', `Bearer ${accessToken}`)\n }\n\n return fetch(url, { ...options, headers })\n }\n\n this.clients = supportedVersions.reduce((acc, version) => {\n acc[version] = createClient<paths>({\n baseUrl: baseUrl.href,\n fetch: authenticatedFetch,\n })\n return acc\n }, {} as ClientsByVersion)\n\n this.clientVersion = version ?? this.clientVersion\n this.baseUrl = baseUrl\n }\n\n private get currentClient(): Client<paths> {\n return this.clients[this.clientVersion] as unknown as Client<paths>\n }\n\n public async init() {\n if (!this.initialized) {\n //TODO: parse error response and escalate\n const versionFromClient =\n await this.currentClient.GET('/v2/version')\n\n this.logger.debug('getV2Version response', {\n data: versionFromClient.data,\n status: versionFromClient.response.status,\n })\n\n this.clientVersion = this.parseSupportedVersions(\n versionFromClient.data?.version\n )\n this.initialized = true\n\n this.logger.debug(\n `Initializing LedgerClient with version ${this.clientVersion} for url ${this.baseUrl.href} and setting initialized to true`\n )\n }\n }\n\n public getCurrentClientVersion(): SupportedVersions {\n return this.clientVersion\n }\n\n parseSupportedVersions(version: string | undefined): SupportedVersions {\n if (!version) {\n throw new Error('Client version missing from response')\n }\n\n const match = supportedVersions.find((v) => version.startsWith(v))\n if (!match) {\n this.logger.warn(\n `Unknown support of version ${version} (defaulting to ${this.clientVersion}) please check if a newer version is available that support this version of canton.`\n )\n return this.clientVersion\n }\n\n return match\n }\n\n /**\n * Check if a party exists\n *\n * @param partyId The ID of the party to look for\n * @returns A promise to resolves to a boolean.\n */\n public async checkIfPartyExists(partyId: PartyId): Promise<boolean> {\n try {\n const party = await this.get('/v2/parties/{party}', {\n path: { party: partyId },\n })\n return (\n party.partyDetails !== undefined &&\n party.partyDetails[0].party === partyId\n )\n } catch {\n return false\n }\n }\n\n /**\n * grant \"Master User\" rights to a user.\n *\n * this require running with an admin token.\n *\n * @param userId The ID of the user to grant rights to.\n * @param canReadAsAnyParty define if the user can read as any party.\n * @param canExecuteAsAnyParty define if the user can execute as any party.\n */\n public async grantMasterUserRights(\n userId: string,\n canReadAsAnyParty: boolean,\n canExecuteAsAnyParty: boolean\n ) {\n const rights = []\n if (canReadAsAnyParty) {\n rights.push({\n kind: {\n CanReadAsAnyParty: { value: {} as Record<string, never> },\n },\n })\n }\n if (canExecuteAsAnyParty) {\n rights.push({\n kind: {\n CanExecuteAsAnyParty: {\n value: {} as Record<string, never>,\n },\n },\n })\n }\n\n const result = await this.post(\n '/v2/users/{user-id}/rights',\n {\n identityProviderId: '',\n userId,\n rights,\n },\n {\n path: {\n 'user-id': userId,\n },\n }\n )\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n }\n\n /**\n * Create a new user.\n *\n * @param userId The ID of the user to create.\n * @param primaryParty The primary party of the user.\n */\n public async createUser(\n userId: string,\n primaryParty: PartyId\n ): Promise<UserSchema> {\n try {\n const existing = await this.get('/v2/users/{user-id}', {\n path: { 'user-id': userId },\n })\n\n if (existing && existing.user) {\n return existing.user!\n }\n } catch {\n //TODO: proper error handling based on daml code\n // we continue if code is:\n // code: 'USER_NOT_FOUND',\n // cause: 'getting user failed for unknown user \"master-user\"',\n }\n\n return (\n await this.post('/v2/users', {\n user: {\n identityProviderId: '',\n id: userId,\n isDeactivated: false,\n primaryParty: primaryParty,\n },\n rights: [\n {\n kind: {\n ParticipantAdmin: {\n value: {} as Record<string, never>,\n },\n },\n },\n ],\n })\n ).user!\n }\n\n /**\n * Grants a user the right to act as a party, while ensuring the party exists.\n *\n * @param userId The ID of the user to grant rights to.\n * @param partyId The ID of the party to grant rights for.\n * @param maxTries Optional max number of retries with default 30. May be increased if expecting heavy load.\n * @param retryIntervalMs Optional interval between retries to verify that party exists with default 2000ms. May be increased if expecting heavy load.\n * @returns A promise that resolves when the rights have been granted.\n */\n public async waitForPartyAndGrantUserRights(\n userId: string,\n partyId: PartyId,\n maxTries: number = 30,\n retryIntervalMs: number = 2000\n ) {\n await this.init()\n // Wait for party to appear on participant, only sleeping between checks\n let partyFound = await this.checkIfPartyExists(partyId)\n for (let tries = 1; !partyFound && tries < maxTries; tries++) {\n await new Promise((resolve) => setTimeout(resolve, retryIntervalMs))\n partyFound = await this.checkIfPartyExists(partyId)\n }\n\n if (!partyFound) {\n throw new Error(\n `timed out waiting for new party to appear after ${maxTries} tries`\n )\n }\n\n const result = await this.grantRights(userId, {\n actAs: [partyId],\n })\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n\n return\n }\n\n public async grantRights(\n userId: string,\n userRightsOptions: {\n canReadAsAnyParty?: boolean\n canExecuteAsAnyParty?: boolean\n readAs?: PartyId[]\n actAs?: PartyId[]\n }\n ) {\n await this.init()\n const rights = []\n\n for (const partyId of userRightsOptions.readAs ?? []) {\n rights.push({\n kind: {\n CanReadAs: {\n value: {\n party: partyId,\n },\n },\n },\n })\n }\n\n for (const partyId of userRightsOptions.actAs ?? []) {\n rights.push({\n kind: {\n CanActAs: {\n value: {\n party: partyId,\n },\n },\n },\n })\n }\n\n if (userRightsOptions.canReadAsAnyParty) {\n rights.push({\n kind: {\n CanReadAsAnyParty: { value: {} as Record<string, never> },\n },\n })\n }\n if (userRightsOptions.canExecuteAsAnyParty) {\n rights.push({\n kind: {\n CanExecuteAsAnyParty: {\n value: {} as Record<string, never>,\n },\n },\n })\n }\n\n const result = await this.post(\n '/v2/users/{user-id}/rights',\n {\n identityProviderId: '',\n userId,\n rights,\n },\n {\n path: {\n 'user-id': userId,\n },\n }\n )\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n\n return result\n }\n\n public async allocateExternalParty(\n synchronizerId: string,\n onboardingTransactions: OnboardingTransactions,\n multiHashSignatures: MultiHashSignatures\n ): Promise<AllocateExternalPartyResponse> {\n await this.init()\n const resp = await this.currentClient.POST(\n '/v2/parties/external/allocate',\n {\n body: {\n synchronizer: synchronizerId,\n identityProviderId: '',\n onboardingTransactions,\n multiHashSignatures,\n },\n }\n )\n\n return this.valueOrError(resp)\n }\n\n public async generateTopology(\n synchronizerId: string,\n publicKey: string,\n partyHint: string,\n localParticipantObservationOnly: boolean = false,\n confirmationThreshold: number = 1,\n otherConfirmingParticipantUids: string[] = [],\n observingParticipantUids: string[] = []\n ): Promise<GenerateTransactionResponse> {\n await this.init()\n\n const body = {\n synchronizer: synchronizerId,\n partyHint,\n publicKey: {\n format: 'CRYPTO_KEY_FORMAT_RAW',\n keyData: publicKey,\n keySpec: 'SIGNING_KEY_SPEC_EC_CURVE25519',\n },\n localParticipantObservationOnly,\n confirmationThreshold,\n otherConfirmingParticipantUids,\n observingParticipantUids,\n }\n\n this.logger.trace('generateTopology request body', { body })\n\n const resp = await this.currentClient.POST(\n '/v2/parties/external/generate-topology',\n { body }\n )\n\n return this.valueOrError(resp)\n }\n\n // Retrieve the default synchronizer id from the validator.\n // Prefers a synchronizer aliased 'global' over application-specific ones.\n // This synchronizer id is cached for the remainder of this object's life.\n public async getSynchronizerId(): Promise<string> {\n if (this.synchronizerId) return this.synchronizerId\n const response = await this.getWithRetry(\n '/v2/state/connected-synchronizers'\n )\n const synchronizers = response.connectedSynchronizers\n if (!synchronizers?.[0]) {\n throw new Error('No connected synchronizers found')\n }\n const defaultEntry =\n synchronizers.find((s) => s.synchronizerAlias === 'global') ??\n synchronizers.find(\n (s) => s.synchronizerAlias !== 'app-synchronizer'\n ) ??\n synchronizers[0]\n const synchronizerId = defaultEntry.synchronizerId\n if (synchronizers.length > 1) {\n this.logger.warn(\n `Found ${synchronizers.length} synchronizers, defaulting to ${synchronizerId}`\n )\n }\n this.synchronizerId = synchronizerId\n return synchronizerId\n }\n\n public async postWithRetry<Path extends PostEndpoint>(\n path: Path,\n body: PostRequest<Path>,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n },\n additionalOptions?: ExtraPostOpts\n ): Promise<PostResponse<Path>> {\n return await retryable(\n () => this.post(path, body, params, additionalOptions),\n retryOptions\n ).catch((e) => {\n this.logger.warn(`Error in postWithRetry for path {path}`, {\n path,\n options: retryOptions,\n })\n this.logger.debug({ body })\n throw asJsCantonError(e)\n })\n }\n\n public async getWithRetry<Path extends GetEndpoint>(\n path: Path,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n }\n ): Promise<GetResponse<Path>> {\n return await retryable(\n () => this.get(path, params),\n retryOptions\n ).catch((e) => {\n this.logger.warn(\n `Error in getWithRetry for path ${path} with retry options ${JSON.stringify(retryOptions)}`\n )\n\n throw asJsCantonError(e)\n })\n }\n\n public async patchWithRetry<Path extends PatchEndpoint>(\n path: Path,\n body: PatchRequest<Path>,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n },\n additionalOptions?: ExtraPostOpts\n ): Promise<PatchResponse<Path>> {\n return await retryable(\n () => this.patch(path, body, params, additionalOptions),\n retryOptions\n ).catch((e) => {\n this.logger.warn(\n `Error in patchWithRetry for path ${path} with body retry options ${JSON.stringify(retryOptions)}`\n )\n throw asJsCantonError(e)\n })\n }\n\n public async patch<Path extends PatchEndpoint>(\n path: Path,\n body: PatchRequest<Path>,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string | number | boolean>\n },\n // needed when posting to /packages, so content type and jsonification of bytes can be overriden\n additionalOptions?: ExtraPostOpts\n ): Promise<PatchResponse<Path>> {\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { body, params, ...additionalOptions } as any\n\n const resp = await this.currentClient.PATCH(path, options)\n return this.valueOrError(resp)\n }\n\n public async post<Path extends PostEndpoint>(\n path: Path,\n body: PostRequest<Path>,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string | number | boolean>\n },\n // needed when posting to /packages, so content type and jsonification of bytes can be overriden\n additionalOptions?: ExtraPostOpts\n ): Promise<PostResponse<Path>> {\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { body, params, ...additionalOptions } as any\n\n const resp = await this.currentClient.POST(path, options)\n return this.valueOrError(resp)\n }\n\n public async get<Path extends GetEndpoint>(\n path: Path,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n }\n ): Promise<GetResponse<Path>> {\n await this.init()\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { params } as any\n const resp = await this.currentClient.GET(path, options)\n return this.valueOrError(resp)\n }\n\n private async valueOrError<T>(response: {\n data?: T\n error?: unknown\n }): Promise<T> {\n if (response.data === undefined) {\n return Promise.reject(response.error)\n } else {\n return Promise.resolve(response.data)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,oBAAoB;AAC1B,MAAM,qCAAqC;AAE3C,MAAM,UAAA,GAASA,iBAAAA,UAAAA,CAAU;CAAC;CAAQ;CAAiB;AAAkB,CAAC;;;;;;;;;AAUtE,eAAsB,gBAClB,cACA,WACA,SACA,QACA,yBACA,cAAc,UACK;CACnB,MAAM,YAAY,MAAM,aAAa,cACjC,4BACA;EACI;EACA,SAAS,CAAC,OAAO;EACjB,gBAAgB;CACpB,GACA,yBACA,EACI,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,EAAE,OAAO;EACzB,MAAM,OAAO,MAAM,KAAK,cAAc,IAAI,MAAM,OAAO;EACvD,OAAO,KAAK,aAAa,IAAI;CACjC;CAEA,MAAc,aAAgB,UAGf;EACX,IAAI,SAAS,SAAS,KAAA,GAClB,OAAO,QAAQ,OAAO,SAAS,KAAK;OAEpC,OAAO,QAAQ,QAAQ,SAAS,IAAI;CAE5C;AACJ"}
1
+ {"version":3,"file":"index.cjs","names":["getLogger","ErrorInfo","RetryInfo","supportedLedgerApiVersions","LedgerGetRoutes","LedgerPostRoutes","getLogger","createClient"],"sources":["../src/ledger-api-utils.ts","../src/ledger-client.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { LedgerClient } from './ledger-client.js'\n\nimport type { Types } from './ledger-client.js'\nimport type { PartyId } from '@canton-network/core-types'\n\nimport { ErrorInfo, RetryInfo } from '@canton-network/core-ledger-proto'\nimport { getLogger } from '@logtape/logtape'\n\ntype Completion = Types['Completion']['value']\nexport type JSContractEntry = Types['JsContractEntry']\nexport type JsCantonError = Types['JsCantonError']\n\nconst COMPLETIONS_LIMIT = '100'\nconst COMPLETIONS_STREAM_IDLE_TIMEOUT_MS = '1000'\n\nconst logger = getLogger(['core', 'ledger-client', 'ledger-api-utils'])\n\n/**\n * Polls the completions endpoint until\n * the completion with the given (userId, commandId, submissionId) is returned.\n * Then returns the updateId, synchronizerId and recordTime of that completion.\n *\n * Polls until the completion shows up unless `maxAttempts` is given, in which case\n * it throws once that many polls found nothing (e.g. the completion was pruned).\n */\nexport async function awaitCompletion(\n ledgerClient: LedgerClient,\n ledgerEnd: number,\n partyId: PartyId,\n userId: string,\n commandIdOrSubmissionId: string,\n maxAttempts = Infinity\n): Promise<Completion> {\n const responses = await ledgerClient.postWithRetry(\n '/v2/commands/completions',\n {\n userId,\n parties: [partyId],\n beginExclusive: ledgerEnd,\n },\n defaultRetryableOptions,\n {\n query: {\n limit: COMPLETIONS_LIMIT,\n stream_idle_timeout_ms: COMPLETIONS_STREAM_IDLE_TIMEOUT_MS,\n },\n }\n )\n\n const completions = responses.filter(\n (r) => r.completionResponse && 'Completion' in r.completionResponse\n )\n\n const wantedCompletion = responses.find((r) => {\n if (r.completionResponse && 'Completion' in r.completionResponse) {\n const completion = r.completionResponse.Completion?.value\n if (!completion) {\n return false\n }\n return (\n completion.userId === userId &&\n (completion.commandId === commandIdOrSubmissionId ||\n completion.submissionId === commandIdOrSubmissionId)\n )\n }\n return false\n })\n\n if (\n wantedCompletion?.completionResponse &&\n 'Completion' in wantedCompletion.completionResponse\n ) {\n const completion = wantedCompletion.completionResponse.Completion.value\n const status = completion.status\n if (status && status.code !== 0) {\n // status.code is 0 for success\n throw asGrpcError(status)\n }\n return completion\n } else {\n const lastCompletion = completions[completions.length - 1]\n const newLedgerEnd =\n lastCompletion?.completionResponse &&\n 'Completion' in lastCompletion.completionResponse\n ? lastCompletion.completionResponse.Completion.value.offset\n : undefined\n\n if (maxAttempts <= 1) {\n throw new Error(\n `Completion for ${commandIdOrSubmissionId} not found`\n )\n }\n\n return awaitCompletion(\n ledgerClient,\n newLedgerEnd || ledgerEnd, // !newLedgerEnd implies response was empty\n partyId,\n userId,\n commandIdOrSubmissionId,\n maxAttempts - 1\n )\n }\n}\n\nexport type RetryableOptions = {\n retries: number\n delayMs: number\n cantonErrorKeys: string[]\n}\nexport const defaultRetryableOptions: RetryableOptions = {\n retries: 5,\n delayMs: 3000,\n cantonErrorKeys: [\n 'SEQUENCER_REQUEST_FAILED',\n 'SEQUENCER_BACKPRESSURE',\n 'SUBMISSION_ALREADY_IN_FLIGHT',\n 'LOCAL_VERDICT_TIMEOUT',\n 'NOT_SEQUENCED_TIMEOUT',\n 'NO_VIEW_WITH_VALID_RECIPIENTS',\n ],\n}\n\nexport async function retryable<T>(\n fn: () => Promise<T>,\n retryableOptions: RetryableOptions\n): Promise<T> {\n for (let attempts = 1; attempts <= retryableOptions.retries; attempts++) {\n try {\n return await fn()\n } catch (err: unknown) {\n const grpcError = asGrpcError(err)\n const message: string = grpcError.message\n const shouldRetry =\n retryableOptions.cantonErrorKeys.length === 0 ||\n retryableOptions.cantonErrorKeys.some((key) =>\n message.includes(key)\n )\n if (attempts < retryableOptions.retries && shouldRetry) {\n logger.warn(\n `Caught retryiable error: ${message}. Retrying attempt ${attempts} of ${retryableOptions.retries}...`\n )\n await new Promise((res) =>\n setTimeout(res, retryableOptions.delayMs)\n )\n // continue to next attempt\n } else {\n throw grpcError\n }\n }\n }\n throw new Error('retryable: Exceeded maximum retries without throwing.')\n}\n\n// Helper for differentiating ledger errors from others and satisfying TS when checking error properties\nexport const isJsCantonError = (e: unknown): e is JsCantonError =>\n typeof e === 'object' &&\n e !== null &&\n 'code' in e &&\n 'cause' in e &&\n 'errorCategory' in e\n\nexport const asJsCantonError = (e: unknown): JsCantonError => {\n if (isJsCantonError(e)) {\n return e\n } else {\n throw e\n }\n}\n\nexport const asGrpcError = (\n e: unknown\n): {\n code: number\n message: string\n errorInfo: ErrorInfo | undefined\n retryInfo: RetryInfo | undefined\n} => {\n let errorInfo: ErrorInfo | undefined\n let retryInfo: RetryInfo | undefined\n\n if (\n typeof e === 'object' &&\n e !== null &&\n 'code' in e &&\n 'message' in e &&\n 'details' in e &&\n Array.isArray(e.details)\n ) {\n const code = e.code as number\n const message = e.message as string\n\n for (const detail of e.details) {\n if (\n detail.typeUrl === 'type.googleapis.com/google.rpc.ErrorInfo' &&\n typeof detail.value === 'string'\n ) {\n try {\n errorInfo = ErrorInfo.fromBinary(\n Buffer.from(detail.value, 'base64')\n )\n } catch {\n //if parsing fails, we skip adding ErrorInfo\n }\n } else if (\n detail.typeUrl === 'type.googleapis.com/google.rpc.RetryInfo' &&\n typeof detail.value === 'string'\n ) {\n try {\n retryInfo = RetryInfo.fromBinary(\n Buffer.from(detail.value, 'base64')\n )\n } catch {\n //if parsing fails, we skip adding RetryInfo\n }\n }\n }\n return { code, message, errorInfo, retryInfo }\n }\n\n // Not a gRPC error, rethrow\n throw e\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n supportedLedgerApiVersions,\n type LedgerApiVersion,\n type LedgerCommonPaths,\n type LedgerCommonSchemas,\n LedgerGetRoutes,\n LedgerPostRoutes,\n} from '@canton-network/core-ledger-client-types'\nimport createClient, { type Client, type FetchOptions } from 'openapi-fetch'\nimport type { PartyId } from '@canton-network/core-types'\nimport {\n asJsCantonError,\n defaultRetryableOptions,\n retryable,\n type RetryableOptions,\n} from './ledger-api-utils.js'\nimport type { AccessTokenProvider } from '@canton-network/core-wallet-auth'\nimport { getLogger } from '@logtape/logtape'\n\nexport const supportedVersions = supportedLedgerApiVersions\n\nexport type SupportedVersions = LedgerApiVersion\n\ntype paths = LedgerCommonPaths\n\ntype SchemaByVersion<Name extends keyof LedgerCommonSchemas> =\n LedgerCommonSchemas[Name]\n\ntype ClientsByVersion = {\n [V in SupportedVersions]: Client<paths>\n}\n\nexport type UserSchema = SchemaByVersion<'User'>\n\nexport type Types = LedgerCommonSchemas\n\n// A conditional type that filters the set of OpenAPI path names to those that actually have a defined POST operation.\n// Any path without a POST is excluded via the `never` branch of the conditional\nexport type PatchEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n patch: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\n// Given a pathname (string) that has a POST, this helper type extracts the request body type from the OpenAPI definition.\nexport type PatchRequest<Path extends PatchEndpoint> = paths[Path] extends {\n patch: { requestBody: { content: { 'application/json': infer Req } } }\n}\n ? Req\n : never\n\n// Given a pathname (string) that has a POST, this helper type extracts the 200 response type from the OpenAPI definition.\nexport type PatchResponse<Path extends PatchEndpoint> = paths[Path] extends {\n patch: {\n responses: { 200: { content: { 'application/json': infer Res } } }\n }\n}\n ? Res\n : never\n\n// A conditional type that filters the set of OpenAPI path names to those that actually have a defined POST operation.\n// Any path without a POST is excluded via the `never` branch of the conditional\nexport type PostEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n post: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\n// Given a pathname (string) that has a POST, this helper type extracts the request body type from the OpenAPI definition.\nexport type PostRequest<Path extends PostEndpoint> = paths[Path] extends {\n post: { requestBody: { content: { 'application/json': infer Req } } }\n}\n ? Req\n : never\n\n// Given a pathname (string) that has a POST, this helper type extracts the 200 response type from the OpenAPI definition.\nexport type PostResponse<Path extends PostEndpoint> = paths[Path] extends {\n post: { responses: { 200: { content: { 'application/json': infer Res } } } }\n}\n ? Res\n : never\n\n// Similar as above, for GETs\nexport type GetEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n get: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\nexport function isValidGetEndpoint(resource: string): resource is GetEndpoint {\n return LedgerGetRoutes.has(resource)\n}\n\nexport function isValidPostEndpoint(\n resource: string\n): resource is PostEndpoint {\n return LedgerPostRoutes.has(resource)\n}\n\n// Similar as above, for GETs\nexport type GetResponse<Path extends GetEndpoint> = paths[Path] extends {\n get: { responses: { 200: { content: { 'application/json': infer Res } } } }\n}\n ? Res\n : never\n\nexport type GenerateTransactionResponse =\n SchemaByVersion<'GenerateExternalPartyTopologyResponse'>\n\nexport type AllocateExternalPartyResponse =\n SchemaByVersion<'AllocateExternalPartyResponse'>\nexport type OnboardingTransactions = NonNullable<\n SchemaByVersion<'AllocateExternalPartyRequest'>['onboardingTransactions']\n>\n\nexport type MultiHashSignatures = NonNullable<\n SchemaByVersion<'AllocateExternalPartyRequest'>['multiHashSignatures']\n>\nexport type PrepareSubmissionResponse =\n SchemaByVersion<'JsPrepareSubmissionResponse'>\n\n// Any options the client accepts besides body/params\ntype ExtraPostOpts = Omit<FetchOptions<paths>, 'body' | 'params'>\n\nexport class LedgerClient {\n // privately manage the active connected version and associated client codegen\n private readonly clients: ClientsByVersion\n private clientVersion: SupportedVersions = '3.6'\n private initialized: boolean = false\n private accessTokenProvider: AccessTokenProvider\n private readonly logger = getLogger([\n 'core',\n 'ledger-client',\n 'LedgerClient',\n ])\n private synchronizerId: string | undefined\n baseUrl: URL\n\n constructor({\n baseUrl,\n accessTokenProvider,\n version,\n }: {\n baseUrl: URL\n accessTokenProvider: AccessTokenProvider\n version?: SupportedVersions\n }) {\n this.accessTokenProvider = accessTokenProvider\n\n const authenticatedFetch = async (\n url: RequestInfo,\n options: RequestInit = {}\n ) => {\n const accessToken = await this.accessTokenProvider.getAccessToken()\n const headers = new Headers(options.headers)\n if (accessToken) {\n headers.set('Authorization', `Bearer ${accessToken}`)\n }\n\n return fetch(url, { ...options, headers })\n }\n\n this.clients = supportedVersions.reduce((acc, version) => {\n acc[version] = createClient<paths>({\n baseUrl: baseUrl.href,\n fetch: authenticatedFetch,\n })\n return acc\n }, {} as ClientsByVersion)\n\n this.clientVersion = version ?? this.clientVersion\n this.baseUrl = baseUrl\n }\n\n private get currentClient(): Client<paths> {\n return this.clients[this.clientVersion] as unknown as Client<paths>\n }\n\n public async init() {\n if (!this.initialized) {\n //TODO: parse error response and escalate\n const versionFromClient =\n await this.currentClient.GET('/v2/version')\n\n this.logger.debug('getV2Version response', {\n data: versionFromClient.data,\n status: versionFromClient.response.status,\n })\n\n this.clientVersion = this.parseSupportedVersions(\n versionFromClient.data?.version\n )\n this.initialized = true\n\n this.logger.debug(\n `Initializing LedgerClient with version ${this.clientVersion} for url ${this.baseUrl.href} and setting initialized to true`\n )\n }\n }\n\n public getCurrentClientVersion(): SupportedVersions {\n return this.clientVersion\n }\n\n parseSupportedVersions(version: string | undefined): SupportedVersions {\n if (!version) {\n throw new Error('Client version missing from response')\n }\n\n const match = supportedVersions.find((v) => version.startsWith(v))\n if (!match) {\n this.logger.warn(\n `Unknown support of version ${version} (defaulting to ${this.clientVersion}) please check if a newer version is available that support this version of canton.`\n )\n return this.clientVersion\n }\n\n return match\n }\n\n /**\n * Check if a party exists\n *\n * @param partyId The ID of the party to look for\n * @returns A promise to resolves to a boolean.\n */\n public async checkIfPartyExists(partyId: PartyId): Promise<boolean> {\n try {\n const party = await this.get('/v2/parties/{party}', {\n path: { party: partyId },\n })\n return (\n party.partyDetails !== undefined &&\n party.partyDetails[0].party === partyId\n )\n } catch {\n return false\n }\n }\n\n /**\n * grant \"Master User\" rights to a user.\n *\n * this require running with an admin token.\n *\n * @param userId The ID of the user to grant rights to.\n * @param canReadAsAnyParty define if the user can read as any party.\n * @param canExecuteAsAnyParty define if the user can execute as any party.\n */\n public async grantMasterUserRights(\n userId: string,\n canReadAsAnyParty: boolean,\n canExecuteAsAnyParty: boolean\n ) {\n const rights = []\n if (canReadAsAnyParty) {\n rights.push({\n kind: {\n CanReadAsAnyParty: { value: {} as Record<string, never> },\n },\n })\n }\n if (canExecuteAsAnyParty) {\n rights.push({\n kind: {\n CanExecuteAsAnyParty: {\n value: {} as Record<string, never>,\n },\n },\n })\n }\n\n const result = await this.post(\n '/v2/users/{user-id}/rights',\n {\n identityProviderId: '',\n userId,\n rights,\n },\n {\n path: {\n 'user-id': userId,\n },\n }\n )\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n }\n\n /**\n * Create a new user.\n *\n * @param userId The ID of the user to create.\n * @param primaryParty The primary party of the user.\n */\n public async createUser(\n userId: string,\n primaryParty: PartyId\n ): Promise<UserSchema> {\n try {\n const existing = await this.get('/v2/users/{user-id}', {\n path: { 'user-id': userId },\n })\n\n if (existing && existing.user) {\n return existing.user!\n }\n } catch {\n //TODO: proper error handling based on daml code\n // we continue if code is:\n // code: 'USER_NOT_FOUND',\n // cause: 'getting user failed for unknown user \"master-user\"',\n }\n\n return (\n await this.post('/v2/users', {\n user: {\n identityProviderId: '',\n id: userId,\n isDeactivated: false,\n primaryParty: primaryParty,\n },\n rights: [\n {\n kind: {\n ParticipantAdmin: {\n value: {} as Record<string, never>,\n },\n },\n },\n ],\n })\n ).user!\n }\n\n /**\n * Grants a user the right to act as a party, while ensuring the party exists.\n *\n * @param userId The ID of the user to grant rights to.\n * @param partyId The ID of the party to grant rights for.\n * @param maxTries Optional max number of retries with default 30. May be increased if expecting heavy load.\n * @param retryIntervalMs Optional interval between retries to verify that party exists with default 2000ms. May be increased if expecting heavy load.\n * @returns A promise that resolves when the rights have been granted.\n */\n public async waitForPartyAndGrantUserRights(\n userId: string,\n partyId: PartyId,\n maxTries: number = 30,\n retryIntervalMs: number = 2000\n ) {\n await this.init()\n // Wait for party to appear on participant, only sleeping between checks\n let partyFound = await this.checkIfPartyExists(partyId)\n for (let tries = 1; !partyFound && tries < maxTries; tries++) {\n await new Promise((resolve) => setTimeout(resolve, retryIntervalMs))\n partyFound = await this.checkIfPartyExists(partyId)\n }\n\n if (!partyFound) {\n throw new Error(\n `timed out waiting for new party to appear after ${maxTries} tries`\n )\n }\n\n const result = await this.grantRights(userId, {\n actAs: [partyId],\n })\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n\n return\n }\n\n public async grantRights(\n userId: string,\n userRightsOptions: {\n canReadAsAnyParty?: boolean\n canExecuteAsAnyParty?: boolean\n readAs?: PartyId[]\n actAs?: PartyId[]\n }\n ) {\n await this.init()\n const rights = []\n\n for (const partyId of userRightsOptions.readAs ?? []) {\n rights.push({\n kind: {\n CanReadAs: {\n value: {\n party: partyId,\n },\n },\n },\n })\n }\n\n for (const partyId of userRightsOptions.actAs ?? []) {\n rights.push({\n kind: {\n CanActAs: {\n value: {\n party: partyId,\n },\n },\n },\n })\n }\n\n if (userRightsOptions.canReadAsAnyParty) {\n rights.push({\n kind: {\n CanReadAsAnyParty: { value: {} as Record<string, never> },\n },\n })\n }\n if (userRightsOptions.canExecuteAsAnyParty) {\n rights.push({\n kind: {\n CanExecuteAsAnyParty: {\n value: {} as Record<string, never>,\n },\n },\n })\n }\n\n const result = await this.post(\n '/v2/users/{user-id}/rights',\n {\n identityProviderId: '',\n userId,\n rights,\n },\n {\n path: {\n 'user-id': userId,\n },\n }\n )\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n\n return result\n }\n\n public async allocateExternalParty(\n synchronizerId: string,\n onboardingTransactions: OnboardingTransactions,\n multiHashSignatures: MultiHashSignatures\n ): Promise<AllocateExternalPartyResponse> {\n await this.init()\n const resp = await this.currentClient.POST(\n '/v2/parties/external/allocate',\n {\n body: {\n synchronizer: synchronizerId,\n identityProviderId: '',\n onboardingTransactions,\n multiHashSignatures,\n },\n }\n )\n\n return this.valueOrError(resp)\n }\n\n public async generateTopology(\n synchronizerId: string,\n publicKey: string,\n partyHint: string,\n localParticipantObservationOnly: boolean = false,\n confirmationThreshold: number = 1,\n otherConfirmingParticipantUids: string[] = [],\n observingParticipantUids: string[] = []\n ): Promise<GenerateTransactionResponse> {\n await this.init()\n\n const body = {\n synchronizer: synchronizerId,\n partyHint,\n publicKey: {\n format: 'CRYPTO_KEY_FORMAT_RAW',\n keyData: publicKey,\n keySpec: 'SIGNING_KEY_SPEC_EC_CURVE25519',\n },\n localParticipantObservationOnly,\n confirmationThreshold,\n otherConfirmingParticipantUids,\n observingParticipantUids,\n }\n\n this.logger.trace('generateTopology request body', { body })\n\n const resp = await this.currentClient.POST(\n '/v2/parties/external/generate-topology',\n { body }\n )\n\n return this.valueOrError(resp)\n }\n\n // Retrieve the default synchronizer id from the validator.\n // Prefers a synchronizer aliased 'global' over application-specific ones.\n // This synchronizer id is cached for the remainder of this object's life.\n public async getSynchronizerId(): Promise<string> {\n if (this.synchronizerId) return this.synchronizerId\n const response = await this.getWithRetry(\n '/v2/state/connected-synchronizers'\n )\n const synchronizers = response.connectedSynchronizers\n if (!synchronizers?.[0]) {\n throw new Error('No connected synchronizers found')\n }\n const defaultEntry =\n synchronizers.find((s) => s.synchronizerAlias === 'global') ??\n synchronizers.find(\n (s) => s.synchronizerAlias !== 'app-synchronizer'\n ) ??\n synchronizers[0]\n const synchronizerId = defaultEntry.synchronizerId\n if (synchronizers.length > 1) {\n this.logger.warn(\n `Found ${synchronizers.length} synchronizers, defaulting to ${synchronizerId}`\n )\n }\n this.synchronizerId = synchronizerId\n return synchronizerId\n }\n\n public async postWithRetry<Path extends PostEndpoint>(\n path: Path,\n body: PostRequest<Path>,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n },\n additionalOptions?: ExtraPostOpts\n ): Promise<PostResponse<Path>> {\n return await retryable(\n () => this.post(path, body, params, additionalOptions),\n retryOptions\n ).catch((e) => {\n this.logger.warn(`Error in postWithRetry for path {path}`, {\n path,\n options: retryOptions,\n })\n this.logger.debug({ body })\n throw asJsCantonError(e)\n })\n }\n\n public async getWithRetry<Path extends GetEndpoint>(\n path: Path,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n }\n ): Promise<GetResponse<Path>> {\n return await retryable(\n () => this.get(path, params),\n retryOptions\n ).catch((e) => {\n this.logger.warn(\n `Error in getWithRetry for path ${path} with retry options ${JSON.stringify(retryOptions)}`\n )\n\n throw asJsCantonError(e)\n })\n }\n\n public async patchWithRetry<Path extends PatchEndpoint>(\n path: Path,\n body: PatchRequest<Path>,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n },\n additionalOptions?: ExtraPostOpts\n ): Promise<PatchResponse<Path>> {\n return await retryable(\n () => this.patch(path, body, params, additionalOptions),\n retryOptions\n ).catch((e) => {\n this.logger.warn(\n `Error in patchWithRetry for path ${path} with body retry options ${JSON.stringify(retryOptions)}`\n )\n throw asJsCantonError(e)\n })\n }\n\n public async patch<Path extends PatchEndpoint>(\n path: Path,\n body: PatchRequest<Path>,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string | number | boolean>\n },\n // needed when posting to /packages, so content type and jsonification of bytes can be overriden\n additionalOptions?: ExtraPostOpts\n ): Promise<PatchResponse<Path>> {\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { body, params, ...additionalOptions } as any\n\n const resp = await this.currentClient.PATCH(path, options)\n return this.valueOrError(resp)\n }\n\n public async post<Path extends PostEndpoint>(\n path: Path,\n body: PostRequest<Path>,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string | number | boolean>\n },\n // needed when posting to /packages, so content type and jsonification of bytes can be overriden\n additionalOptions?: ExtraPostOpts\n ): Promise<PostResponse<Path>> {\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { body, params, ...additionalOptions } as any\n\n const resp = await this.currentClient.POST(path, options)\n return this.valueOrError(resp)\n }\n\n public async get<Path extends GetEndpoint>(\n path: Path,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n }\n ): Promise<GetResponse<Path>> {\n await this.init()\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { params } as any\n const resp = await this.currentClient.GET(path, options)\n return this.valueOrError(resp)\n }\n\n private async valueOrError<T>(response: {\n data?: T\n error?: unknown\n }): Promise<T> {\n if (response.data === undefined) {\n return Promise.reject(response.error)\n } else {\n return Promise.resolve(response.data)\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,MAAM,oBAAoB;AAC1B,MAAM,qCAAqC;AAE3C,MAAM,UAAA,GAASA,iBAAAA,UAAAA,CAAU;CAAC;CAAQ;CAAiB;AAAkB,CAAC;;;;;;;;;AAUtE,eAAsB,gBAClB,cACA,WACA,SACA,QACA,yBACA,cAAc,UACK;CACnB,MAAM,YAAY,MAAM,aAAa,cACjC,4BACA;EACI;EACA,SAAS,CAAC,OAAO;EACjB,gBAAgB;CACpB,GACA,yBACA,EACI,OAAO;EACH,OAAO;EACP,wBAAwB;CAC5B,EACJ,CACJ;CAEA,MAAM,cAAc,UAAU,QACzB,MAAM,EAAE,sBAAsB,gBAAgB,EAAE,kBACrD;CAEA,MAAM,mBAAmB,UAAU,MAA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KAAA,GAClB,OAAO,QAAQ,OAAO,SAAS,KAAK;OAEpC,OAAO,QAAQ,QAAQ,SAAS,IAAI;CAE5C;AACJ"}
package/dist/index.js CHANGED
@@ -100,7 +100,7 @@ const asGrpcError = (e) => {
100
100
  }
101
101
  throw e;
102
102
  };
103
- // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
103
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js
104
104
  function _typeof(o) {
105
105
  "@babel/helpers - typeof";
106
106
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -109,23 +109,23 @@ function _typeof(o) {
109
109
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
110
110
  }, _typeof(o);
111
111
  }
112
- // \0@oxc-project+runtime@0.155.0/helpers/esm/toPrimitive.js
113
- function toPrimitive(t, r) {
112
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/toPrimitive.js
113
+ function toPrimitive(t, e) {
114
114
  if ("object" != _typeof(t) || !t) return t;
115
- var e = t[Symbol.toPrimitive];
116
- if (void 0 !== e) {
117
- var i = e.call(t, r || "default");
115
+ var r;
116
+ if ("undefined" != typeof Symbol && void 0 !== (r = t[Symbol.toPrimitive])) {
117
+ var i = r.call(t, e || "default");
118
118
  if ("object" != _typeof(i)) return i;
119
119
  throw new TypeError("@@toPrimitive must return a primitive value.");
120
120
  }
121
- return ("string" === r ? String : Number)(t);
121
+ return ("string" === e ? String : Number)(t);
122
122
  }
123
- // \0@oxc-project+runtime@0.155.0/helpers/esm/toPropertyKey.js
123
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/toPropertyKey.js
124
124
  function toPropertyKey(t) {
125
125
  var i = toPrimitive(t, "string");
126
126
  return "symbol" == _typeof(i) ? i : i + "";
127
127
  }
128
- // \0@oxc-project+runtime@0.155.0/helpers/esm/defineProperty.js
128
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/defineProperty.js
129
129
  function _defineProperty(e, r, t) {
130
130
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
131
131
  value: t,
@@ -145,7 +145,7 @@ function isValidPostEndpoint(resource) {
145
145
  var LedgerClient = class {
146
146
  constructor({ baseUrl, accessTokenProvider, version }) {
147
147
  _defineProperty(this, "clients", void 0);
148
- _defineProperty(this, "clientVersion", "3.5");
148
+ _defineProperty(this, "clientVersion", "3.6");
149
149
  _defineProperty(this, "initialized", false);
150
150
  _defineProperty(this, "accessTokenProvider", void 0);
151
151
  _defineProperty(this, "logger", getLogger([
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/ledger-api-utils.ts","../src/ledger-client.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { LedgerClient } from './ledger-client.js'\n\nimport type { Types } from './ledger-client.js'\nimport type { PartyId } from '@canton-network/core-types'\n\nimport { ErrorInfo, RetryInfo } from '@canton-network/core-ledger-proto'\nimport { getLogger } from '@logtape/logtape'\n\ntype Completion = Types['Completion']['value']\nexport type JSContractEntry = Types['JsContractEntry']\nexport type JsCantonError = Types['JsCantonError']\n\nconst COMPLETIONS_LIMIT = '100'\nconst COMPLETIONS_STREAM_IDLE_TIMEOUT_MS = '1000'\n\nconst logger = getLogger(['core', 'ledger-client', 'ledger-api-utils'])\n\n/**\n * Polls the completions endpoint until\n * the completion with the given (userId, commandId, submissionId) is returned.\n * Then returns the updateId, synchronizerId and recordTime of that completion.\n *\n * Polls until the completion shows up unless `maxAttempts` is given, in which case\n * it throws once that many polls found nothing (e.g. the completion was pruned).\n */\nexport async function awaitCompletion(\n ledgerClient: LedgerClient,\n ledgerEnd: number,\n partyId: PartyId,\n userId: string,\n commandIdOrSubmissionId: string,\n maxAttempts = Infinity\n): Promise<Completion> {\n const responses = await ledgerClient.postWithRetry(\n '/v2/commands/completions',\n {\n userId,\n parties: [partyId],\n beginExclusive: ledgerEnd,\n },\n defaultRetryableOptions,\n {\n query: {\n limit: COMPLETIONS_LIMIT,\n stream_idle_timeout_ms: COMPLETIONS_STREAM_IDLE_TIMEOUT_MS,\n },\n }\n )\n\n const completions = responses.filter(\n (r) => r.completionResponse && 'Completion' in r.completionResponse\n )\n\n const wantedCompletion = responses.find((r) => {\n if (r.completionResponse && 'Completion' in r.completionResponse) {\n const completion = r.completionResponse.Completion?.value\n if (!completion) {\n return false\n }\n return (\n completion.userId === userId &&\n (completion.commandId === commandIdOrSubmissionId ||\n completion.submissionId === commandIdOrSubmissionId)\n )\n }\n return false\n })\n\n if (\n wantedCompletion?.completionResponse &&\n 'Completion' in wantedCompletion.completionResponse\n ) {\n const completion = wantedCompletion.completionResponse.Completion.value\n const status = completion.status\n if (status && status.code !== 0) {\n // status.code is 0 for success\n throw asGrpcError(status)\n }\n return completion\n } else {\n const lastCompletion = completions[completions.length - 1]\n const newLedgerEnd =\n lastCompletion?.completionResponse &&\n 'Completion' in lastCompletion.completionResponse\n ? lastCompletion.completionResponse.Completion.value.offset\n : undefined\n\n if (maxAttempts <= 1) {\n throw new Error(\n `Completion for ${commandIdOrSubmissionId} not found`\n )\n }\n\n return awaitCompletion(\n ledgerClient,\n newLedgerEnd || ledgerEnd, // !newLedgerEnd implies response was empty\n partyId,\n userId,\n commandIdOrSubmissionId,\n maxAttempts - 1\n )\n }\n}\n\nexport type RetryableOptions = {\n retries: number\n delayMs: number\n cantonErrorKeys: string[]\n}\nexport const defaultRetryableOptions: RetryableOptions = {\n retries: 5,\n delayMs: 3000,\n cantonErrorKeys: [\n 'SEQUENCER_REQUEST_FAILED',\n 'SEQUENCER_BACKPRESSURE',\n 'SUBMISSION_ALREADY_IN_FLIGHT',\n 'LOCAL_VERDICT_TIMEOUT',\n 'NOT_SEQUENCED_TIMEOUT',\n 'NO_VIEW_WITH_VALID_RECIPIENTS',\n ],\n}\n\nexport async function retryable<T>(\n fn: () => Promise<T>,\n retryableOptions: RetryableOptions\n): Promise<T> {\n for (let attempts = 1; attempts <= retryableOptions.retries; attempts++) {\n try {\n return await fn()\n } catch (err: unknown) {\n const grpcError = asGrpcError(err)\n const message: string = grpcError.message\n const shouldRetry =\n retryableOptions.cantonErrorKeys.length === 0 ||\n retryableOptions.cantonErrorKeys.some((key) =>\n message.includes(key)\n )\n if (attempts < retryableOptions.retries && shouldRetry) {\n logger.warn(\n `Caught retryiable error: ${message}. Retrying attempt ${attempts} of ${retryableOptions.retries}...`\n )\n await new Promise((res) =>\n setTimeout(res, retryableOptions.delayMs)\n )\n // continue to next attempt\n } else {\n throw grpcError\n }\n }\n }\n throw new Error('retryable: Exceeded maximum retries without throwing.')\n}\n\n// Helper for differentiating ledger errors from others and satisfying TS when checking error properties\nexport const isJsCantonError = (e: unknown): e is JsCantonError =>\n typeof e === 'object' &&\n e !== null &&\n 'code' in e &&\n 'cause' in e &&\n 'errorCategory' in e\n\nexport const asJsCantonError = (e: unknown): JsCantonError => {\n if (isJsCantonError(e)) {\n return e\n } else {\n throw e\n }\n}\n\nexport const asGrpcError = (\n e: unknown\n): {\n code: number\n message: string\n errorInfo: ErrorInfo | undefined\n retryInfo: RetryInfo | undefined\n} => {\n let errorInfo: ErrorInfo | undefined\n let retryInfo: RetryInfo | undefined\n\n if (\n typeof e === 'object' &&\n e !== null &&\n 'code' in e &&\n 'message' in e &&\n 'details' in e &&\n Array.isArray(e.details)\n ) {\n const code = e.code as number\n const message = e.message as string\n\n for (const detail of e.details) {\n if (\n detail.typeUrl === 'type.googleapis.com/google.rpc.ErrorInfo' &&\n typeof detail.value === 'string'\n ) {\n try {\n errorInfo = ErrorInfo.fromBinary(\n Buffer.from(detail.value, 'base64')\n )\n } catch {\n //if parsing fails, we skip adding ErrorInfo\n }\n } else if (\n detail.typeUrl === 'type.googleapis.com/google.rpc.RetryInfo' &&\n typeof detail.value === 'string'\n ) {\n try {\n retryInfo = RetryInfo.fromBinary(\n Buffer.from(detail.value, 'base64')\n )\n } catch {\n //if parsing fails, we skip adding RetryInfo\n }\n }\n }\n return { code, message, errorInfo, retryInfo }\n }\n\n // Not a gRPC error, rethrow\n throw e\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n supportedLedgerApiVersions,\n type LedgerApiVersion,\n type LedgerCommonPaths,\n type LedgerCommonSchemas,\n LedgerGetRoutes,\n LedgerPostRoutes,\n} from '@canton-network/core-ledger-client-types'\nimport createClient, { type Client, type FetchOptions } from 'openapi-fetch'\nimport type { PartyId } from '@canton-network/core-types'\nimport {\n asJsCantonError,\n defaultRetryableOptions,\n retryable,\n type RetryableOptions,\n} from './ledger-api-utils.js'\nimport type { AccessTokenProvider } from '@canton-network/core-wallet-auth'\nimport { getLogger } from '@logtape/logtape'\n\nexport const supportedVersions = supportedLedgerApiVersions\n\nexport type SupportedVersions = LedgerApiVersion\n\ntype paths = LedgerCommonPaths\n\ntype SchemaByVersion<Name extends keyof LedgerCommonSchemas> =\n LedgerCommonSchemas[Name]\n\ntype ClientsByVersion = {\n [V in SupportedVersions]: Client<paths>\n}\n\nexport type UserSchema = SchemaByVersion<'User'>\n\nexport type Types = LedgerCommonSchemas\n\n// A conditional type that filters the set of OpenAPI path names to those that actually have a defined POST operation.\n// Any path without a POST is excluded via the `never` branch of the conditional\nexport type PatchEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n patch: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\n// Given a pathname (string) that has a POST, this helper type extracts the request body type from the OpenAPI definition.\nexport type PatchRequest<Path extends PatchEndpoint> = paths[Path] extends {\n patch: { requestBody: { content: { 'application/json': infer Req } } }\n}\n ? Req\n : never\n\n// Given a pathname (string) that has a POST, this helper type extracts the 200 response type from the OpenAPI definition.\nexport type PatchResponse<Path extends PatchEndpoint> = paths[Path] extends {\n patch: {\n responses: { 200: { content: { 'application/json': infer Res } } }\n }\n}\n ? Res\n : never\n\n// A conditional type that filters the set of OpenAPI path names to those that actually have a defined POST operation.\n// Any path without a POST is excluded via the `never` branch of the conditional\nexport type PostEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n post: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\n// Given a pathname (string) that has a POST, this helper type extracts the request body type from the OpenAPI definition.\nexport type PostRequest<Path extends PostEndpoint> = paths[Path] extends {\n post: { requestBody: { content: { 'application/json': infer Req } } }\n}\n ? Req\n : never\n\n// Given a pathname (string) that has a POST, this helper type extracts the 200 response type from the OpenAPI definition.\nexport type PostResponse<Path extends PostEndpoint> = paths[Path] extends {\n post: { responses: { 200: { content: { 'application/json': infer Res } } } }\n}\n ? Res\n : never\n\n// Similar as above, for GETs\nexport type GetEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n get: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\nexport function isValidGetEndpoint(resource: string): resource is GetEndpoint {\n return LedgerGetRoutes.has(resource)\n}\n\nexport function isValidPostEndpoint(\n resource: string\n): resource is PostEndpoint {\n return LedgerPostRoutes.has(resource)\n}\n\n// Similar as above, for GETs\nexport type GetResponse<Path extends GetEndpoint> = paths[Path] extends {\n get: { responses: { 200: { content: { 'application/json': infer Res } } } }\n}\n ? Res\n : never\n\nexport type GenerateTransactionResponse =\n SchemaByVersion<'GenerateExternalPartyTopologyResponse'>\n\nexport type AllocateExternalPartyResponse =\n SchemaByVersion<'AllocateExternalPartyResponse'>\nexport type OnboardingTransactions = NonNullable<\n SchemaByVersion<'AllocateExternalPartyRequest'>['onboardingTransactions']\n>\n\nexport type MultiHashSignatures = NonNullable<\n SchemaByVersion<'AllocateExternalPartyRequest'>['multiHashSignatures']\n>\nexport type PrepareSubmissionResponse =\n SchemaByVersion<'JsPrepareSubmissionResponse'>\n\n// Any options the client accepts besides body/params\ntype ExtraPostOpts = Omit<FetchOptions<paths>, 'body' | 'params'>\n\nexport class LedgerClient {\n // privately manage the active connected version and associated client codegen\n private readonly clients: ClientsByVersion\n private clientVersion: SupportedVersions = '3.5'\n private initialized: boolean = false\n private accessTokenProvider: AccessTokenProvider\n private readonly logger = getLogger([\n 'core',\n 'ledger-client',\n 'LedgerClient',\n ])\n private synchronizerId: string | undefined\n baseUrl: URL\n\n constructor({\n baseUrl,\n accessTokenProvider,\n version,\n }: {\n baseUrl: URL\n accessTokenProvider: AccessTokenProvider\n version?: SupportedVersions\n }) {\n this.accessTokenProvider = accessTokenProvider\n\n const authenticatedFetch = async (\n url: RequestInfo,\n options: RequestInit = {}\n ) => {\n const accessToken = await this.accessTokenProvider.getAccessToken()\n const headers = new Headers(options.headers)\n if (accessToken) {\n headers.set('Authorization', `Bearer ${accessToken}`)\n }\n\n return fetch(url, { ...options, headers })\n }\n\n this.clients = supportedVersions.reduce((acc, version) => {\n acc[version] = createClient<paths>({\n baseUrl: baseUrl.href,\n fetch: authenticatedFetch,\n })\n return acc\n }, {} as ClientsByVersion)\n\n this.clientVersion = version ?? this.clientVersion\n this.baseUrl = baseUrl\n }\n\n private get currentClient(): Client<paths> {\n return this.clients[this.clientVersion] as unknown as Client<paths>\n }\n\n public async init() {\n if (!this.initialized) {\n //TODO: parse error response and escalate\n const versionFromClient =\n await this.currentClient.GET('/v2/version')\n\n this.logger.debug('getV2Version response', {\n data: versionFromClient.data,\n status: versionFromClient.response.status,\n })\n\n this.clientVersion = this.parseSupportedVersions(\n versionFromClient.data?.version\n )\n this.initialized = true\n\n this.logger.debug(\n `Initializing LedgerClient with version ${this.clientVersion} for url ${this.baseUrl.href} and setting initialized to true`\n )\n }\n }\n\n public getCurrentClientVersion(): SupportedVersions {\n return this.clientVersion\n }\n\n parseSupportedVersions(version: string | undefined): SupportedVersions {\n if (!version) {\n throw new Error('Client version missing from response')\n }\n\n const match = supportedVersions.find((v) => version.startsWith(v))\n if (!match) {\n this.logger.warn(\n `Unknown support of version ${version} (defaulting to ${this.clientVersion}) please check if a newer version is available that support this version of canton.`\n )\n return this.clientVersion\n }\n\n return match\n }\n\n /**\n * Check if a party exists\n *\n * @param partyId The ID of the party to look for\n * @returns A promise to resolves to a boolean.\n */\n public async checkIfPartyExists(partyId: PartyId): Promise<boolean> {\n try {\n const party = await this.get('/v2/parties/{party}', {\n path: { party: partyId },\n })\n return (\n party.partyDetails !== undefined &&\n party.partyDetails[0].party === partyId\n )\n } catch {\n return false\n }\n }\n\n /**\n * grant \"Master User\" rights to a user.\n *\n * this require running with an admin token.\n *\n * @param userId The ID of the user to grant rights to.\n * @param canReadAsAnyParty define if the user can read as any party.\n * @param canExecuteAsAnyParty define if the user can execute as any party.\n */\n public async grantMasterUserRights(\n userId: string,\n canReadAsAnyParty: boolean,\n canExecuteAsAnyParty: boolean\n ) {\n const rights = []\n if (canReadAsAnyParty) {\n rights.push({\n kind: {\n CanReadAsAnyParty: { value: {} as Record<string, never> },\n },\n })\n }\n if (canExecuteAsAnyParty) {\n rights.push({\n kind: {\n CanExecuteAsAnyParty: {\n value: {} as Record<string, never>,\n },\n },\n })\n }\n\n const result = await this.post(\n '/v2/users/{user-id}/rights',\n {\n identityProviderId: '',\n userId,\n rights,\n },\n {\n path: {\n 'user-id': userId,\n },\n }\n )\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n }\n\n /**\n * Create a new user.\n *\n * @param userId The ID of the user to create.\n * @param primaryParty The primary party of the user.\n */\n public async createUser(\n userId: string,\n primaryParty: PartyId\n ): Promise<UserSchema> {\n try {\n const existing = await this.get('/v2/users/{user-id}', {\n path: { 'user-id': userId },\n })\n\n if (existing && existing.user) {\n return existing.user!\n }\n } catch {\n //TODO: proper error handling based on daml code\n // we continue if code is:\n // code: 'USER_NOT_FOUND',\n // cause: 'getting user failed for unknown user \"master-user\"',\n }\n\n return (\n await this.post('/v2/users', {\n user: {\n identityProviderId: '',\n id: userId,\n isDeactivated: false,\n primaryParty: primaryParty,\n },\n rights: [\n {\n kind: {\n ParticipantAdmin: {\n value: {} as Record<string, never>,\n },\n },\n },\n ],\n })\n ).user!\n }\n\n /**\n * Grants a user the right to act as a party, while ensuring the party exists.\n *\n * @param userId The ID of the user to grant rights to.\n * @param partyId The ID of the party to grant rights for.\n * @param maxTries Optional max number of retries with default 30. May be increased if expecting heavy load.\n * @param retryIntervalMs Optional interval between retries to verify that party exists with default 2000ms. May be increased if expecting heavy load.\n * @returns A promise that resolves when the rights have been granted.\n */\n public async waitForPartyAndGrantUserRights(\n userId: string,\n partyId: PartyId,\n maxTries: number = 30,\n retryIntervalMs: number = 2000\n ) {\n await this.init()\n // Wait for party to appear on participant, only sleeping between checks\n let partyFound = await this.checkIfPartyExists(partyId)\n for (let tries = 1; !partyFound && tries < maxTries; tries++) {\n await new Promise((resolve) => setTimeout(resolve, retryIntervalMs))\n partyFound = await this.checkIfPartyExists(partyId)\n }\n\n if (!partyFound) {\n throw new Error(\n `timed out waiting for new party to appear after ${maxTries} tries`\n )\n }\n\n const result = await this.grantRights(userId, {\n actAs: [partyId],\n })\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n\n return\n }\n\n public async grantRights(\n userId: string,\n userRightsOptions: {\n canReadAsAnyParty?: boolean\n canExecuteAsAnyParty?: boolean\n readAs?: PartyId[]\n actAs?: PartyId[]\n }\n ) {\n await this.init()\n const rights = []\n\n for (const partyId of userRightsOptions.readAs ?? []) {\n rights.push({\n kind: {\n CanReadAs: {\n value: {\n party: partyId,\n },\n },\n },\n })\n }\n\n for (const partyId of userRightsOptions.actAs ?? []) {\n rights.push({\n kind: {\n CanActAs: {\n value: {\n party: partyId,\n },\n },\n },\n })\n }\n\n if (userRightsOptions.canReadAsAnyParty) {\n rights.push({\n kind: {\n CanReadAsAnyParty: { value: {} as Record<string, never> },\n },\n })\n }\n if (userRightsOptions.canExecuteAsAnyParty) {\n rights.push({\n kind: {\n CanExecuteAsAnyParty: {\n value: {} as Record<string, never>,\n },\n },\n })\n }\n\n const result = await this.post(\n '/v2/users/{user-id}/rights',\n {\n identityProviderId: '',\n userId,\n rights,\n },\n {\n path: {\n 'user-id': userId,\n },\n }\n )\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n\n return result\n }\n\n public async allocateExternalParty(\n synchronizerId: string,\n onboardingTransactions: OnboardingTransactions,\n multiHashSignatures: MultiHashSignatures\n ): Promise<AllocateExternalPartyResponse> {\n await this.init()\n const resp = await this.currentClient.POST(\n '/v2/parties/external/allocate',\n {\n body: {\n synchronizer: synchronizerId,\n identityProviderId: '',\n onboardingTransactions,\n multiHashSignatures,\n },\n }\n )\n\n return this.valueOrError(resp)\n }\n\n public async generateTopology(\n synchronizerId: string,\n publicKey: string,\n partyHint: string,\n localParticipantObservationOnly: boolean = false,\n confirmationThreshold: number = 1,\n otherConfirmingParticipantUids: string[] = [],\n observingParticipantUids: string[] = []\n ): Promise<GenerateTransactionResponse> {\n await this.init()\n\n const body = {\n synchronizer: synchronizerId,\n partyHint,\n publicKey: {\n format: 'CRYPTO_KEY_FORMAT_RAW',\n keyData: publicKey,\n keySpec: 'SIGNING_KEY_SPEC_EC_CURVE25519',\n },\n localParticipantObservationOnly,\n confirmationThreshold,\n otherConfirmingParticipantUids,\n observingParticipantUids,\n }\n\n this.logger.trace('generateTopology request body', { body })\n\n const resp = await this.currentClient.POST(\n '/v2/parties/external/generate-topology',\n { body }\n )\n\n return this.valueOrError(resp)\n }\n\n // Retrieve the default synchronizer id from the validator.\n // Prefers a synchronizer aliased 'global' over application-specific ones.\n // This synchronizer id is cached for the remainder of this object's life.\n public async getSynchronizerId(): Promise<string> {\n if (this.synchronizerId) return this.synchronizerId\n const response = await this.getWithRetry(\n '/v2/state/connected-synchronizers'\n )\n const synchronizers = response.connectedSynchronizers\n if (!synchronizers?.[0]) {\n throw new Error('No connected synchronizers found')\n }\n const defaultEntry =\n synchronizers.find((s) => s.synchronizerAlias === 'global') ??\n synchronizers.find(\n (s) => s.synchronizerAlias !== 'app-synchronizer'\n ) ??\n synchronizers[0]\n const synchronizerId = defaultEntry.synchronizerId\n if (synchronizers.length > 1) {\n this.logger.warn(\n `Found ${synchronizers.length} synchronizers, defaulting to ${synchronizerId}`\n )\n }\n this.synchronizerId = synchronizerId\n return synchronizerId\n }\n\n public async postWithRetry<Path extends PostEndpoint>(\n path: Path,\n body: PostRequest<Path>,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n },\n additionalOptions?: ExtraPostOpts\n ): Promise<PostResponse<Path>> {\n return await retryable(\n () => this.post(path, body, params, additionalOptions),\n retryOptions\n ).catch((e) => {\n this.logger.warn(`Error in postWithRetry for path {path}`, {\n path,\n options: retryOptions,\n })\n this.logger.debug({ body })\n throw asJsCantonError(e)\n })\n }\n\n public async getWithRetry<Path extends GetEndpoint>(\n path: Path,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n }\n ): Promise<GetResponse<Path>> {\n return await retryable(\n () => this.get(path, params),\n retryOptions\n ).catch((e) => {\n this.logger.warn(\n `Error in getWithRetry for path ${path} with retry options ${JSON.stringify(retryOptions)}`\n )\n\n throw asJsCantonError(e)\n })\n }\n\n public async patchWithRetry<Path extends PatchEndpoint>(\n path: Path,\n body: PatchRequest<Path>,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n },\n additionalOptions?: ExtraPostOpts\n ): Promise<PatchResponse<Path>> {\n return await retryable(\n () => this.patch(path, body, params, additionalOptions),\n retryOptions\n ).catch((e) => {\n this.logger.warn(\n `Error in patchWithRetry for path ${path} with body retry options ${JSON.stringify(retryOptions)}`\n )\n throw asJsCantonError(e)\n })\n }\n\n public async patch<Path extends PatchEndpoint>(\n path: Path,\n body: PatchRequest<Path>,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string | number | boolean>\n },\n // needed when posting to /packages, so content type and jsonification of bytes can be overriden\n additionalOptions?: ExtraPostOpts\n ): Promise<PatchResponse<Path>> {\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { body, params, ...additionalOptions } as any\n\n const resp = await this.currentClient.PATCH(path, options)\n return this.valueOrError(resp)\n }\n\n public async post<Path extends PostEndpoint>(\n path: Path,\n body: PostRequest<Path>,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string | number | boolean>\n },\n // needed when posting to /packages, so content type and jsonification of bytes can be overriden\n additionalOptions?: ExtraPostOpts\n ): Promise<PostResponse<Path>> {\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { body, params, ...additionalOptions } as any\n\n const resp = await this.currentClient.POST(path, options)\n return this.valueOrError(resp)\n }\n\n public async get<Path extends GetEndpoint>(\n path: Path,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n }\n ): Promise<GetResponse<Path>> {\n await this.init()\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { params } as any\n const resp = await this.currentClient.GET(path, options)\n return this.valueOrError(resp)\n }\n\n private async valueOrError<T>(response: {\n data?: T\n error?: unknown\n }): Promise<T> {\n if (response.data === undefined) {\n return Promise.reject(response.error)\n } else {\n return Promise.resolve(response.data)\n }\n }\n}\n"],"mappings":";;;;;AAeA,MAAM,oBAAoB;AAC1B,MAAM,qCAAqC;AAE3C,MAAM,SAAS,UAAU;CAAC;CAAQ;CAAiB;AAAkB,CAAC;;;;;;;;;AAUtE,eAAsB,gBAClB,cACA,WACA,SACA,QACA,yBACA,cAAc,UACK;CACnB,MAAM,YAAY,MAAM,aAAa,cACjC,4BACA;EACI;EACA,SAAS,CAAC,OAAO;EACjB,gBAAgB;CACpB,GACA,yBACA,EACI,OAAO;EACH,OAAO;EACP,wBAAwB;CAC5B,EACJ,CACJ;CAEA,MAAM,cAAc,UAAU,QACzB,MAAM,EAAE,sBAAsB,gBAAgB,EAAE,kBACrD;CAEA,MAAM,mBAAmB,UAA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E5C;AACJ"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/ledger-api-utils.ts","../src/ledger-client.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport type { LedgerClient } from './ledger-client.js'\n\nimport type { Types } from './ledger-client.js'\nimport type { PartyId } from '@canton-network/core-types'\n\nimport { ErrorInfo, RetryInfo } from '@canton-network/core-ledger-proto'\nimport { getLogger } from '@logtape/logtape'\n\ntype Completion = Types['Completion']['value']\nexport type JSContractEntry = Types['JsContractEntry']\nexport type JsCantonError = Types['JsCantonError']\n\nconst COMPLETIONS_LIMIT = '100'\nconst COMPLETIONS_STREAM_IDLE_TIMEOUT_MS = '1000'\n\nconst logger = getLogger(['core', 'ledger-client', 'ledger-api-utils'])\n\n/**\n * Polls the completions endpoint until\n * the completion with the given (userId, commandId, submissionId) is returned.\n * Then returns the updateId, synchronizerId and recordTime of that completion.\n *\n * Polls until the completion shows up unless `maxAttempts` is given, in which case\n * it throws once that many polls found nothing (e.g. the completion was pruned).\n */\nexport async function awaitCompletion(\n ledgerClient: LedgerClient,\n ledgerEnd: number,\n partyId: PartyId,\n userId: string,\n commandIdOrSubmissionId: string,\n maxAttempts = Infinity\n): Promise<Completion> {\n const responses = await ledgerClient.postWithRetry(\n '/v2/commands/completions',\n {\n userId,\n parties: [partyId],\n beginExclusive: ledgerEnd,\n },\n defaultRetryableOptions,\n {\n query: {\n limit: COMPLETIONS_LIMIT,\n stream_idle_timeout_ms: COMPLETIONS_STREAM_IDLE_TIMEOUT_MS,\n },\n }\n )\n\n const completions = responses.filter(\n (r) => r.completionResponse && 'Completion' in r.completionResponse\n )\n\n const wantedCompletion = responses.find((r) => {\n if (r.completionResponse && 'Completion' in r.completionResponse) {\n const completion = r.completionResponse.Completion?.value\n if (!completion) {\n return false\n }\n return (\n completion.userId === userId &&\n (completion.commandId === commandIdOrSubmissionId ||\n completion.submissionId === commandIdOrSubmissionId)\n )\n }\n return false\n })\n\n if (\n wantedCompletion?.completionResponse &&\n 'Completion' in wantedCompletion.completionResponse\n ) {\n const completion = wantedCompletion.completionResponse.Completion.value\n const status = completion.status\n if (status && status.code !== 0) {\n // status.code is 0 for success\n throw asGrpcError(status)\n }\n return completion\n } else {\n const lastCompletion = completions[completions.length - 1]\n const newLedgerEnd =\n lastCompletion?.completionResponse &&\n 'Completion' in lastCompletion.completionResponse\n ? lastCompletion.completionResponse.Completion.value.offset\n : undefined\n\n if (maxAttempts <= 1) {\n throw new Error(\n `Completion for ${commandIdOrSubmissionId} not found`\n )\n }\n\n return awaitCompletion(\n ledgerClient,\n newLedgerEnd || ledgerEnd, // !newLedgerEnd implies response was empty\n partyId,\n userId,\n commandIdOrSubmissionId,\n maxAttempts - 1\n )\n }\n}\n\nexport type RetryableOptions = {\n retries: number\n delayMs: number\n cantonErrorKeys: string[]\n}\nexport const defaultRetryableOptions: RetryableOptions = {\n retries: 5,\n delayMs: 3000,\n cantonErrorKeys: [\n 'SEQUENCER_REQUEST_FAILED',\n 'SEQUENCER_BACKPRESSURE',\n 'SUBMISSION_ALREADY_IN_FLIGHT',\n 'LOCAL_VERDICT_TIMEOUT',\n 'NOT_SEQUENCED_TIMEOUT',\n 'NO_VIEW_WITH_VALID_RECIPIENTS',\n ],\n}\n\nexport async function retryable<T>(\n fn: () => Promise<T>,\n retryableOptions: RetryableOptions\n): Promise<T> {\n for (let attempts = 1; attempts <= retryableOptions.retries; attempts++) {\n try {\n return await fn()\n } catch (err: unknown) {\n const grpcError = asGrpcError(err)\n const message: string = grpcError.message\n const shouldRetry =\n retryableOptions.cantonErrorKeys.length === 0 ||\n retryableOptions.cantonErrorKeys.some((key) =>\n message.includes(key)\n )\n if (attempts < retryableOptions.retries && shouldRetry) {\n logger.warn(\n `Caught retryiable error: ${message}. Retrying attempt ${attempts} of ${retryableOptions.retries}...`\n )\n await new Promise((res) =>\n setTimeout(res, retryableOptions.delayMs)\n )\n // continue to next attempt\n } else {\n throw grpcError\n }\n }\n }\n throw new Error('retryable: Exceeded maximum retries without throwing.')\n}\n\n// Helper for differentiating ledger errors from others and satisfying TS when checking error properties\nexport const isJsCantonError = (e: unknown): e is JsCantonError =>\n typeof e === 'object' &&\n e !== null &&\n 'code' in e &&\n 'cause' in e &&\n 'errorCategory' in e\n\nexport const asJsCantonError = (e: unknown): JsCantonError => {\n if (isJsCantonError(e)) {\n return e\n } else {\n throw e\n }\n}\n\nexport const asGrpcError = (\n e: unknown\n): {\n code: number\n message: string\n errorInfo: ErrorInfo | undefined\n retryInfo: RetryInfo | undefined\n} => {\n let errorInfo: ErrorInfo | undefined\n let retryInfo: RetryInfo | undefined\n\n if (\n typeof e === 'object' &&\n e !== null &&\n 'code' in e &&\n 'message' in e &&\n 'details' in e &&\n Array.isArray(e.details)\n ) {\n const code = e.code as number\n const message = e.message as string\n\n for (const detail of e.details) {\n if (\n detail.typeUrl === 'type.googleapis.com/google.rpc.ErrorInfo' &&\n typeof detail.value === 'string'\n ) {\n try {\n errorInfo = ErrorInfo.fromBinary(\n Buffer.from(detail.value, 'base64')\n )\n } catch {\n //if parsing fails, we skip adding ErrorInfo\n }\n } else if (\n detail.typeUrl === 'type.googleapis.com/google.rpc.RetryInfo' &&\n typeof detail.value === 'string'\n ) {\n try {\n retryInfo = RetryInfo.fromBinary(\n Buffer.from(detail.value, 'base64')\n )\n } catch {\n //if parsing fails, we skip adding RetryInfo\n }\n }\n }\n return { code, message, errorInfo, retryInfo }\n }\n\n // Not a gRPC error, rethrow\n throw e\n}\n","// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n supportedLedgerApiVersions,\n type LedgerApiVersion,\n type LedgerCommonPaths,\n type LedgerCommonSchemas,\n LedgerGetRoutes,\n LedgerPostRoutes,\n} from '@canton-network/core-ledger-client-types'\nimport createClient, { type Client, type FetchOptions } from 'openapi-fetch'\nimport type { PartyId } from '@canton-network/core-types'\nimport {\n asJsCantonError,\n defaultRetryableOptions,\n retryable,\n type RetryableOptions,\n} from './ledger-api-utils.js'\nimport type { AccessTokenProvider } from '@canton-network/core-wallet-auth'\nimport { getLogger } from '@logtape/logtape'\n\nexport const supportedVersions = supportedLedgerApiVersions\n\nexport type SupportedVersions = LedgerApiVersion\n\ntype paths = LedgerCommonPaths\n\ntype SchemaByVersion<Name extends keyof LedgerCommonSchemas> =\n LedgerCommonSchemas[Name]\n\ntype ClientsByVersion = {\n [V in SupportedVersions]: Client<paths>\n}\n\nexport type UserSchema = SchemaByVersion<'User'>\n\nexport type Types = LedgerCommonSchemas\n\n// A conditional type that filters the set of OpenAPI path names to those that actually have a defined POST operation.\n// Any path without a POST is excluded via the `never` branch of the conditional\nexport type PatchEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n patch: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\n// Given a pathname (string) that has a POST, this helper type extracts the request body type from the OpenAPI definition.\nexport type PatchRequest<Path extends PatchEndpoint> = paths[Path] extends {\n patch: { requestBody: { content: { 'application/json': infer Req } } }\n}\n ? Req\n : never\n\n// Given a pathname (string) that has a POST, this helper type extracts the 200 response type from the OpenAPI definition.\nexport type PatchResponse<Path extends PatchEndpoint> = paths[Path] extends {\n patch: {\n responses: { 200: { content: { 'application/json': infer Res } } }\n }\n}\n ? Res\n : never\n\n// A conditional type that filters the set of OpenAPI path names to those that actually have a defined POST operation.\n// Any path without a POST is excluded via the `never` branch of the conditional\nexport type PostEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n post: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\n// Given a pathname (string) that has a POST, this helper type extracts the request body type from the OpenAPI definition.\nexport type PostRequest<Path extends PostEndpoint> = paths[Path] extends {\n post: { requestBody: { content: { 'application/json': infer Req } } }\n}\n ? Req\n : never\n\n// Given a pathname (string) that has a POST, this helper type extracts the 200 response type from the OpenAPI definition.\nexport type PostResponse<Path extends PostEndpoint> = paths[Path] extends {\n post: { responses: { 200: { content: { 'application/json': infer Res } } } }\n}\n ? Res\n : never\n\n// Similar as above, for GETs\nexport type GetEndpoint = {\n [Pathname in keyof paths]: paths[Pathname] extends {\n get: unknown\n }\n ? Pathname\n : never\n}[keyof paths]\n\nexport function isValidGetEndpoint(resource: string): resource is GetEndpoint {\n return LedgerGetRoutes.has(resource)\n}\n\nexport function isValidPostEndpoint(\n resource: string\n): resource is PostEndpoint {\n return LedgerPostRoutes.has(resource)\n}\n\n// Similar as above, for GETs\nexport type GetResponse<Path extends GetEndpoint> = paths[Path] extends {\n get: { responses: { 200: { content: { 'application/json': infer Res } } } }\n}\n ? Res\n : never\n\nexport type GenerateTransactionResponse =\n SchemaByVersion<'GenerateExternalPartyTopologyResponse'>\n\nexport type AllocateExternalPartyResponse =\n SchemaByVersion<'AllocateExternalPartyResponse'>\nexport type OnboardingTransactions = NonNullable<\n SchemaByVersion<'AllocateExternalPartyRequest'>['onboardingTransactions']\n>\n\nexport type MultiHashSignatures = NonNullable<\n SchemaByVersion<'AllocateExternalPartyRequest'>['multiHashSignatures']\n>\nexport type PrepareSubmissionResponse =\n SchemaByVersion<'JsPrepareSubmissionResponse'>\n\n// Any options the client accepts besides body/params\ntype ExtraPostOpts = Omit<FetchOptions<paths>, 'body' | 'params'>\n\nexport class LedgerClient {\n // privately manage the active connected version and associated client codegen\n private readonly clients: ClientsByVersion\n private clientVersion: SupportedVersions = '3.6'\n private initialized: boolean = false\n private accessTokenProvider: AccessTokenProvider\n private readonly logger = getLogger([\n 'core',\n 'ledger-client',\n 'LedgerClient',\n ])\n private synchronizerId: string | undefined\n baseUrl: URL\n\n constructor({\n baseUrl,\n accessTokenProvider,\n version,\n }: {\n baseUrl: URL\n accessTokenProvider: AccessTokenProvider\n version?: SupportedVersions\n }) {\n this.accessTokenProvider = accessTokenProvider\n\n const authenticatedFetch = async (\n url: RequestInfo,\n options: RequestInit = {}\n ) => {\n const accessToken = await this.accessTokenProvider.getAccessToken()\n const headers = new Headers(options.headers)\n if (accessToken) {\n headers.set('Authorization', `Bearer ${accessToken}`)\n }\n\n return fetch(url, { ...options, headers })\n }\n\n this.clients = supportedVersions.reduce((acc, version) => {\n acc[version] = createClient<paths>({\n baseUrl: baseUrl.href,\n fetch: authenticatedFetch,\n })\n return acc\n }, {} as ClientsByVersion)\n\n this.clientVersion = version ?? this.clientVersion\n this.baseUrl = baseUrl\n }\n\n private get currentClient(): Client<paths> {\n return this.clients[this.clientVersion] as unknown as Client<paths>\n }\n\n public async init() {\n if (!this.initialized) {\n //TODO: parse error response and escalate\n const versionFromClient =\n await this.currentClient.GET('/v2/version')\n\n this.logger.debug('getV2Version response', {\n data: versionFromClient.data,\n status: versionFromClient.response.status,\n })\n\n this.clientVersion = this.parseSupportedVersions(\n versionFromClient.data?.version\n )\n this.initialized = true\n\n this.logger.debug(\n `Initializing LedgerClient with version ${this.clientVersion} for url ${this.baseUrl.href} and setting initialized to true`\n )\n }\n }\n\n public getCurrentClientVersion(): SupportedVersions {\n return this.clientVersion\n }\n\n parseSupportedVersions(version: string | undefined): SupportedVersions {\n if (!version) {\n throw new Error('Client version missing from response')\n }\n\n const match = supportedVersions.find((v) => version.startsWith(v))\n if (!match) {\n this.logger.warn(\n `Unknown support of version ${version} (defaulting to ${this.clientVersion}) please check if a newer version is available that support this version of canton.`\n )\n return this.clientVersion\n }\n\n return match\n }\n\n /**\n * Check if a party exists\n *\n * @param partyId The ID of the party to look for\n * @returns A promise to resolves to a boolean.\n */\n public async checkIfPartyExists(partyId: PartyId): Promise<boolean> {\n try {\n const party = await this.get('/v2/parties/{party}', {\n path: { party: partyId },\n })\n return (\n party.partyDetails !== undefined &&\n party.partyDetails[0].party === partyId\n )\n } catch {\n return false\n }\n }\n\n /**\n * grant \"Master User\" rights to a user.\n *\n * this require running with an admin token.\n *\n * @param userId The ID of the user to grant rights to.\n * @param canReadAsAnyParty define if the user can read as any party.\n * @param canExecuteAsAnyParty define if the user can execute as any party.\n */\n public async grantMasterUserRights(\n userId: string,\n canReadAsAnyParty: boolean,\n canExecuteAsAnyParty: boolean\n ) {\n const rights = []\n if (canReadAsAnyParty) {\n rights.push({\n kind: {\n CanReadAsAnyParty: { value: {} as Record<string, never> },\n },\n })\n }\n if (canExecuteAsAnyParty) {\n rights.push({\n kind: {\n CanExecuteAsAnyParty: {\n value: {} as Record<string, never>,\n },\n },\n })\n }\n\n const result = await this.post(\n '/v2/users/{user-id}/rights',\n {\n identityProviderId: '',\n userId,\n rights,\n },\n {\n path: {\n 'user-id': userId,\n },\n }\n )\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n }\n\n /**\n * Create a new user.\n *\n * @param userId The ID of the user to create.\n * @param primaryParty The primary party of the user.\n */\n public async createUser(\n userId: string,\n primaryParty: PartyId\n ): Promise<UserSchema> {\n try {\n const existing = await this.get('/v2/users/{user-id}', {\n path: { 'user-id': userId },\n })\n\n if (existing && existing.user) {\n return existing.user!\n }\n } catch {\n //TODO: proper error handling based on daml code\n // we continue if code is:\n // code: 'USER_NOT_FOUND',\n // cause: 'getting user failed for unknown user \"master-user\"',\n }\n\n return (\n await this.post('/v2/users', {\n user: {\n identityProviderId: '',\n id: userId,\n isDeactivated: false,\n primaryParty: primaryParty,\n },\n rights: [\n {\n kind: {\n ParticipantAdmin: {\n value: {} as Record<string, never>,\n },\n },\n },\n ],\n })\n ).user!\n }\n\n /**\n * Grants a user the right to act as a party, while ensuring the party exists.\n *\n * @param userId The ID of the user to grant rights to.\n * @param partyId The ID of the party to grant rights for.\n * @param maxTries Optional max number of retries with default 30. May be increased if expecting heavy load.\n * @param retryIntervalMs Optional interval between retries to verify that party exists with default 2000ms. May be increased if expecting heavy load.\n * @returns A promise that resolves when the rights have been granted.\n */\n public async waitForPartyAndGrantUserRights(\n userId: string,\n partyId: PartyId,\n maxTries: number = 30,\n retryIntervalMs: number = 2000\n ) {\n await this.init()\n // Wait for party to appear on participant, only sleeping between checks\n let partyFound = await this.checkIfPartyExists(partyId)\n for (let tries = 1; !partyFound && tries < maxTries; tries++) {\n await new Promise((resolve) => setTimeout(resolve, retryIntervalMs))\n partyFound = await this.checkIfPartyExists(partyId)\n }\n\n if (!partyFound) {\n throw new Error(\n `timed out waiting for new party to appear after ${maxTries} tries`\n )\n }\n\n const result = await this.grantRights(userId, {\n actAs: [partyId],\n })\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n\n return\n }\n\n public async grantRights(\n userId: string,\n userRightsOptions: {\n canReadAsAnyParty?: boolean\n canExecuteAsAnyParty?: boolean\n readAs?: PartyId[]\n actAs?: PartyId[]\n }\n ) {\n await this.init()\n const rights = []\n\n for (const partyId of userRightsOptions.readAs ?? []) {\n rights.push({\n kind: {\n CanReadAs: {\n value: {\n party: partyId,\n },\n },\n },\n })\n }\n\n for (const partyId of userRightsOptions.actAs ?? []) {\n rights.push({\n kind: {\n CanActAs: {\n value: {\n party: partyId,\n },\n },\n },\n })\n }\n\n if (userRightsOptions.canReadAsAnyParty) {\n rights.push({\n kind: {\n CanReadAsAnyParty: { value: {} as Record<string, never> },\n },\n })\n }\n if (userRightsOptions.canExecuteAsAnyParty) {\n rights.push({\n kind: {\n CanExecuteAsAnyParty: {\n value: {} as Record<string, never>,\n },\n },\n })\n }\n\n const result = await this.post(\n '/v2/users/{user-id}/rights',\n {\n identityProviderId: '',\n userId,\n rights,\n },\n {\n path: {\n 'user-id': userId,\n },\n }\n )\n\n if (!result.newlyGrantedRights) {\n throw new Error('Failed to grant user rights')\n }\n\n return result\n }\n\n public async allocateExternalParty(\n synchronizerId: string,\n onboardingTransactions: OnboardingTransactions,\n multiHashSignatures: MultiHashSignatures\n ): Promise<AllocateExternalPartyResponse> {\n await this.init()\n const resp = await this.currentClient.POST(\n '/v2/parties/external/allocate',\n {\n body: {\n synchronizer: synchronizerId,\n identityProviderId: '',\n onboardingTransactions,\n multiHashSignatures,\n },\n }\n )\n\n return this.valueOrError(resp)\n }\n\n public async generateTopology(\n synchronizerId: string,\n publicKey: string,\n partyHint: string,\n localParticipantObservationOnly: boolean = false,\n confirmationThreshold: number = 1,\n otherConfirmingParticipantUids: string[] = [],\n observingParticipantUids: string[] = []\n ): Promise<GenerateTransactionResponse> {\n await this.init()\n\n const body = {\n synchronizer: synchronizerId,\n partyHint,\n publicKey: {\n format: 'CRYPTO_KEY_FORMAT_RAW',\n keyData: publicKey,\n keySpec: 'SIGNING_KEY_SPEC_EC_CURVE25519',\n },\n localParticipantObservationOnly,\n confirmationThreshold,\n otherConfirmingParticipantUids,\n observingParticipantUids,\n }\n\n this.logger.trace('generateTopology request body', { body })\n\n const resp = await this.currentClient.POST(\n '/v2/parties/external/generate-topology',\n { body }\n )\n\n return this.valueOrError(resp)\n }\n\n // Retrieve the default synchronizer id from the validator.\n // Prefers a synchronizer aliased 'global' over application-specific ones.\n // This synchronizer id is cached for the remainder of this object's life.\n public async getSynchronizerId(): Promise<string> {\n if (this.synchronizerId) return this.synchronizerId\n const response = await this.getWithRetry(\n '/v2/state/connected-synchronizers'\n )\n const synchronizers = response.connectedSynchronizers\n if (!synchronizers?.[0]) {\n throw new Error('No connected synchronizers found')\n }\n const defaultEntry =\n synchronizers.find((s) => s.synchronizerAlias === 'global') ??\n synchronizers.find(\n (s) => s.synchronizerAlias !== 'app-synchronizer'\n ) ??\n synchronizers[0]\n const synchronizerId = defaultEntry.synchronizerId\n if (synchronizers.length > 1) {\n this.logger.warn(\n `Found ${synchronizers.length} synchronizers, defaulting to ${synchronizerId}`\n )\n }\n this.synchronizerId = synchronizerId\n return synchronizerId\n }\n\n public async postWithRetry<Path extends PostEndpoint>(\n path: Path,\n body: PostRequest<Path>,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n },\n additionalOptions?: ExtraPostOpts\n ): Promise<PostResponse<Path>> {\n return await retryable(\n () => this.post(path, body, params, additionalOptions),\n retryOptions\n ).catch((e) => {\n this.logger.warn(`Error in postWithRetry for path {path}`, {\n path,\n options: retryOptions,\n })\n this.logger.debug({ body })\n throw asJsCantonError(e)\n })\n }\n\n public async getWithRetry<Path extends GetEndpoint>(\n path: Path,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n }\n ): Promise<GetResponse<Path>> {\n return await retryable(\n () => this.get(path, params),\n retryOptions\n ).catch((e) => {\n this.logger.warn(\n `Error in getWithRetry for path ${path} with retry options ${JSON.stringify(retryOptions)}`\n )\n\n throw asJsCantonError(e)\n })\n }\n\n public async patchWithRetry<Path extends PatchEndpoint>(\n path: Path,\n body: PatchRequest<Path>,\n retryOptions: RetryableOptions = defaultRetryableOptions,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n },\n additionalOptions?: ExtraPostOpts\n ): Promise<PatchResponse<Path>> {\n return await retryable(\n () => this.patch(path, body, params, additionalOptions),\n retryOptions\n ).catch((e) => {\n this.logger.warn(\n `Error in patchWithRetry for path ${path} with body retry options ${JSON.stringify(retryOptions)}`\n )\n throw asJsCantonError(e)\n })\n }\n\n public async patch<Path extends PatchEndpoint>(\n path: Path,\n body: PatchRequest<Path>,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string | number | boolean>\n },\n // needed when posting to /packages, so content type and jsonification of bytes can be overriden\n additionalOptions?: ExtraPostOpts\n ): Promise<PatchResponse<Path>> {\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { body, params, ...additionalOptions } as any\n\n const resp = await this.currentClient.PATCH(path, options)\n return this.valueOrError(resp)\n }\n\n public async post<Path extends PostEndpoint>(\n path: Path,\n body: PostRequest<Path>,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string | number | boolean>\n },\n // needed when posting to /packages, so content type and jsonification of bytes can be overriden\n additionalOptions?: ExtraPostOpts\n ): Promise<PostResponse<Path>> {\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { body, params, ...additionalOptions } as any\n\n const resp = await this.currentClient.POST(path, options)\n return this.valueOrError(resp)\n }\n\n public async get<Path extends GetEndpoint>(\n path: Path,\n params?: {\n path?: Record<string, string>\n query?: Record<string, string>\n }\n ): Promise<GetResponse<Path>> {\n await this.init()\n // oxlint-disable-next-line typescript/no-explicit-any -- (cant align this with openapi-fetch generics :shrug:)\n const options = { params } as any\n const resp = await this.currentClient.GET(path, options)\n return this.valueOrError(resp)\n }\n\n private async valueOrError<T>(response: {\n data?: T\n error?: unknown\n }): Promise<T> {\n if (response.data === undefined) {\n return Promise.reject(response.error)\n } else {\n return Promise.resolve(response.data)\n }\n }\n}\n"],"mappings":";;;;;AAeA,MAAM,oBAAoB;AAC1B,MAAM,qCAAqC;AAE3C,MAAM,SAAS,UAAU;CAAC;CAAQ;CAAiB;AAAkB,CAAC;;;;;;;;;AAUtE,eAAsB,gBAClB,cACA,WACA,SACA,QACA,yBACA,cAAc,UACK;CACnB,MAAM,YAAY,MAAM,aAAa,cACjC,4BACA;EACI;EACA,SAAS,CAAC,OAAO;EACjB,gBAAgB;CACpB,GACA,yBACA,EACI,OAAO;EACH,OAAO;EACP,wBAAwB;CAC5B,EACJ,CACJ;CAEA,MAAM,cAAc,UAAU,QACzB,MAAM,EAAE,sBAAsB,gBAAgB,EAAE,kBACrD;CAEA,MAAM,mBAAmB,UAAU,MAAM,MAAM;EAC3C,IAAI,EAAE,sBAAsB,gBAAgB,EAAE,oBAAoB;GAC9D,MAAM,aAAa,EAAE,mBAAmB,YAAY;GACpD,IAAI,CAAC,YACD,OAAO;GAEX,OACI,WAAW,WAAW,WACrB,WAAW,cAAc,2BACtB,WAAW,iBAAiB;EAExC;EACA,OAAO;CACX,CAAC;CAED,IACI,kBAAkB,sBAClB,gBAAgB,iBAAiB,oBACnC;EACE,MAAM,aAAa,iBAAiB,mBAAmB,WAAW;EAClE,MAAM,SAAS,WAAW;EAC1B,IAAI,UAAU,OAAO,SAAS,GAE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AK,MAAM,MAAM,MAAM,QAAQ,iBAAiB,GACtD,YACJ,CAAC,CAAC,OAAO,MAAM;GACX,KAAK,OAAO,KACR,oCAAoC,KAAK,2BAA2B,KAAK,UAAU,YAAY,GACnG;GACA,MAAM,gBAAgB,CAAC;EAC3B,CAAC;CACL;CAEA,MAAa,MACT,MACA,MACA,QAKA,mBAC4B;EAE5B,MAAM,UAAU;GAAE;GAAM;GAAQ,GAAG;EAAkB;EAErD,MAAM,OAAO,MAAM,KAAK,cAAc,MAAM,MAAM,OAAO;EACzD,OAAO,KAAK,aAAa,IAAI;CACjC;CAEA,MAAa,KACT,MACA,MACA,QAKA,mBAC2B;EAE3B,MAAM,UAAU;GAAE;GAAM;GAAQ,GAAG;EAAkB;EAErD,MAAM,OAAO,MAAM,KAAK,cAAc,KAAK,MAAM,OAAO;EACxD,OAAO,KAAK,aAAa,IAAI;CACjC;CAEA,MAAa,IACT,MACA,QAI0B;EAC1B,MAAM,KAAK,KAAK;EAEhB,MAAM,UAAU,EAAE,OAAO;EACzB,MAAM,OAAO,MAAM,KAAK,cAAc,IAAI,MAAM,OAAO;EACvD,OAAO,KAAK,aAAa,IAAI;CACjC;CAEA,MAAc,aAAgB,UAGf;EACX,IAAI,SAAS,SAAS,KAAA,GAClB,OAAO,QAAQ,OAAO,SAAS,KAAK;OAEpC,OAAO,QAAQ,QAAQ,SAAS,IAAI;CAE5C;AACJ"}
@@ -3,7 +3,7 @@ import { type FetchOptions } from 'openapi-fetch';
3
3
  import type { PartyId } from '@canton-network/core-types';
4
4
  import { type RetryableOptions } from './ledger-api-utils.js';
5
5
  import type { AccessTokenProvider } from '@canton-network/core-wallet-auth';
6
- export declare const supportedVersions: readonly ["3.5", "3.6"];
6
+ export declare const supportedVersions: readonly ["3.6", "3.7"];
7
7
  export type SupportedVersions = LedgerApiVersion;
8
8
  type paths = LedgerCommonPaths;
9
9
  type SchemaByVersion<Name extends keyof LedgerCommonSchemas> = LedgerCommonSchemas[Name];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@canton-network/core-ledger-client",
3
- "version": "2.2.0",
3
+ "version": "2.4.0",
4
4
  "type": "module",
5
5
  "description": "Provides a TypeScript Canton Network ledger client, generated by the OpenAPI spec",
6
6
  "license": "Apache-2.0",
@@ -22,16 +22,16 @@
22
22
  "@types/node": "^25.9.9",
23
23
  "@vitest/browser-playwright": "^5.0.5",
24
24
  "@vitest/coverage-v8": "^5.0.5",
25
- "playwright": "^1.64.1",
26
- "tsdown": "^0.23.2",
25
+ "playwright": "^1.65.0",
26
+ "tsdown": "^0.23.7",
27
27
  "typescript": "npm:@typescript/typescript6@^6.0.2",
28
28
  "vitest": "^5.0.5"
29
29
  },
30
30
  "dependencies": {
31
- "@canton-network/core-ledger-client-types": "2.2.0",
32
- "@canton-network/core-ledger-proto": "1.15.0",
33
- "@canton-network/core-types": "2.2.0",
34
- "@canton-network/core-wallet-auth": "2.2.0",
31
+ "@canton-network/core-ledger-client-types": "2.4.0",
32
+ "@canton-network/core-ledger-proto": "1.17.0",
33
+ "@canton-network/core-types": "2.4.0",
34
+ "@canton-network/core-wallet-auth": "2.4.0",
35
35
  "@logtape/logtape": "^2.4.1",
36
36
  "openapi-fetch": "^0.17.0"
37
37
  },