@canton-network/core-ledger-client 1.8.0 → 1.10.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.js CHANGED
@@ -1,527 +1,387 @@
1
- import { supportedLedgerApiVersions } from '@canton-network/core-ledger-client-types';
2
- import createClient from 'openapi-fetch';
3
- import { ErrorInfo, RetryInfo } from '@canton-network/core-ledger-proto';
4
-
5
- var __defProp = Object.defineProperty;
6
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
- var COMPLETIONS_LIMIT = "100";
9
- var COMPLETIONS_STREAM_IDLE_TIMEOUT_MS = "1000";
1
+ import { LedgerGetRoutes, LedgerPostRoutes, supportedLedgerApiVersions } from "@canton-network/core-ledger-client-types";
2
+ import createClient from "openapi-fetch";
3
+ import { ErrorInfo, RetryInfo } from "@canton-network/core-ledger-proto";
4
+ //#region src/ledger-api-utils.ts
5
+ const COMPLETIONS_LIMIT = "100";
6
+ const COMPLETIONS_STREAM_IDLE_TIMEOUT_MS = "1000";
7
+ /**
8
+ * Polls the completions endpoint until
9
+ * the completion with the given (userId, commandId, submissionId) is returned.
10
+ * Then returns the updateId, synchronizerId and recordTime of that completion.
11
+ */
10
12
  async function awaitCompletion(ledgerClient, ledgerEnd, partyId, userId, commandIdOrSubmissionId) {
11
- const responses = await ledgerClient.postWithRetry(
12
- "/v2/commands/completions",
13
- {
14
- userId,
15
- parties: [partyId],
16
- beginExclusive: ledgerEnd
17
- },
18
- defaultRetryableOptions,
19
- {
20
- query: {
21
- limit: COMPLETIONS_LIMIT,
22
- stream_idle_timeout_ms: COMPLETIONS_STREAM_IDLE_TIMEOUT_MS
23
- }
24
- }
25
- );
26
- const completions = responses.filter(
27
- (r) => r.completionResponse && "Completion" in r.completionResponse
28
- );
29
- const wantedCompletion = responses.find((r) => {
30
- if (r.completionResponse && "Completion" in r.completionResponse) {
31
- const completion = r.completionResponse.Completion?.value;
32
- if (!completion) {
33
- return false;
34
- }
35
- return completion.userId === userId && (completion.commandId === commandIdOrSubmissionId || completion.submissionId === commandIdOrSubmissionId);
36
- }
37
- return false;
38
- });
39
- if (wantedCompletion?.completionResponse && "Completion" in wantedCompletion.completionResponse) {
40
- const completion = wantedCompletion.completionResponse.Completion.value;
41
- const status = completion.status;
42
- if (status && status.code !== 0) {
43
- throw asGrpcError(status);
44
- }
45
- return completion;
46
- } else {
47
- const lastCompletion = completions[completions.length - 1];
48
- const newLedgerEnd = lastCompletion?.completionResponse && "Completion" in lastCompletion.completionResponse ? lastCompletion.completionResponse.Completion.value.offset : void 0;
49
- return awaitCompletion(
50
- ledgerClient,
51
- newLedgerEnd || ledgerEnd,
52
- // !newLedgerEnd implies response was empty
53
- partyId,
54
- userId,
55
- commandIdOrSubmissionId
56
- );
57
- }
13
+ const responses = await ledgerClient.postWithRetry("/v2/commands/completions", {
14
+ userId,
15
+ parties: [partyId],
16
+ beginExclusive: ledgerEnd
17
+ }, defaultRetryableOptions, { query: {
18
+ limit: COMPLETIONS_LIMIT,
19
+ stream_idle_timeout_ms: COMPLETIONS_STREAM_IDLE_TIMEOUT_MS
20
+ } });
21
+ const completions = responses.filter((r) => r.completionResponse && "Completion" in r.completionResponse);
22
+ const wantedCompletion = responses.find((r) => {
23
+ if (r.completionResponse && "Completion" in r.completionResponse) {
24
+ const completion = r.completionResponse.Completion?.value;
25
+ if (!completion) return false;
26
+ return completion.userId === userId && (completion.commandId === commandIdOrSubmissionId || completion.submissionId === commandIdOrSubmissionId);
27
+ }
28
+ return false;
29
+ });
30
+ if (wantedCompletion?.completionResponse && "Completion" in wantedCompletion.completionResponse) {
31
+ const completion = wantedCompletion.completionResponse.Completion.value;
32
+ const status = completion.status;
33
+ if (status && status.code !== 0) throw asGrpcError(status);
34
+ return completion;
35
+ } else {
36
+ const lastCompletion = completions[completions.length - 1];
37
+ return awaitCompletion(ledgerClient, (lastCompletion?.completionResponse && "Completion" in lastCompletion.completionResponse ? lastCompletion.completionResponse.Completion.value.offset : void 0) || ledgerEnd, partyId, userId, commandIdOrSubmissionId);
38
+ }
58
39
  }
59
40
  async function promiseWithTimeout(promise, timeoutMs, errorMessage) {
60
- let timeoutPid = null;
61
- const timeoutPromise = new Promise((_resolve, reject) => {
62
- timeoutPid = setTimeout(() => reject(errorMessage), timeoutMs);
63
- });
64
- try {
65
- return await Promise.race([promise, timeoutPromise]);
66
- } finally {
67
- if (timeoutPid) {
68
- clearTimeout(timeoutPid);
69
- }
70
- }
41
+ let timeoutPid = null;
42
+ const timeoutPromise = new Promise((_resolve, reject) => {
43
+ timeoutPid = setTimeout(() => reject(errorMessage), timeoutMs);
44
+ });
45
+ try {
46
+ return await Promise.race([promise, timeoutPromise]);
47
+ } finally {
48
+ if (timeoutPid) clearTimeout(timeoutPid);
49
+ }
71
50
  }
72
- var defaultRetryableOptions = {
73
- retries: 5,
74
- delayMs: 3e3,
75
- cantonErrorKeys: [
76
- "SEQUENCER_REQUEST_FAILED",
77
- "SEQUENCER_BACKPRESSURE",
78
- "SUBMISSION_ALREADY_IN_FLIGHT",
79
- "LOCAL_VERDICT_TIMEOUT",
80
- "NOT_SEQUENCED_TIMEOUT",
81
- "NO_VIEW_WITH_VALID_RECIPIENTS"
82
- ]
51
+ const defaultRetryableOptions = {
52
+ retries: 5,
53
+ delayMs: 3e3,
54
+ cantonErrorKeys: [
55
+ "SEQUENCER_REQUEST_FAILED",
56
+ "SEQUENCER_BACKPRESSURE",
57
+ "SUBMISSION_ALREADY_IN_FLIGHT",
58
+ "LOCAL_VERDICT_TIMEOUT",
59
+ "NOT_SEQUENCED_TIMEOUT",
60
+ "NO_VIEW_WITH_VALID_RECIPIENTS"
61
+ ]
83
62
  };
84
63
  async function retryable(fn, retryableOptions, logger) {
85
- for (let attempts = 1; attempts <= retryableOptions.retries; attempts++) {
86
- try {
87
- return await fn();
88
- } catch (err) {
89
- const grpcError = asGrpcError(err);
90
- const message = grpcError.message;
91
- const shouldRetry = retryableOptions.cantonErrorKeys.length === 0 || retryableOptions.cantonErrorKeys.some(
92
- (key) => message.includes(key)
93
- );
94
- if (attempts < retryableOptions.retries && shouldRetry) {
95
- logger?.warn(
96
- `Caught retryiable error: ${message}. Retrying attempt ${attempts} of ${retryableOptions.retries}...`
97
- );
98
- await new Promise(
99
- (res) => setTimeout(res, retryableOptions.delayMs)
100
- );
101
- } else {
102
- throw grpcError;
103
- }
104
- }
105
- }
106
- throw new Error("retryable: Exceeded maximum retries without throwing.");
64
+ for (let attempts = 1; attempts <= retryableOptions.retries; attempts++) try {
65
+ return await fn();
66
+ } catch (err) {
67
+ const grpcError = asGrpcError(err);
68
+ const message = grpcError.message;
69
+ const shouldRetry = retryableOptions.cantonErrorKeys.length === 0 || retryableOptions.cantonErrorKeys.some((key) => message.includes(key));
70
+ if (attempts < retryableOptions.retries && shouldRetry) {
71
+ logger?.warn(`Caught retryiable error: ${message}. Retrying attempt ${attempts} of ${retryableOptions.retries}...`);
72
+ await new Promise((res) => setTimeout(res, retryableOptions.delayMs));
73
+ } else throw grpcError;
74
+ }
75
+ throw new Error("retryable: Exceeded maximum retries without throwing.");
107
76
  }
108
- var isJsCantonError = (e) => typeof e === "object" && e !== null && "code" in e && "cause" in e && "errorCategory" in e;
109
- var asJsCantonError = (e) => {
110
- if (isJsCantonError(e)) {
111
- return e;
112
- } else {
113
- throw e;
114
- }
77
+ const isJsCantonError = (e) => typeof e === "object" && e !== null && "code" in e && "cause" in e && "errorCategory" in e;
78
+ const asJsCantonError = (e) => {
79
+ if (isJsCantonError(e)) return e;
80
+ else throw e;
115
81
  };
116
- var asGrpcError = (e) => {
117
- let errorInfo;
118
- let retryInfo;
119
- if (typeof e === "object" && e !== null && "code" in e && "message" in e && "details" in e && Array.isArray(e.details)) {
120
- const code = e.code;
121
- const message = e.message;
122
- for (const detail of e.details) {
123
- if (detail.typeUrl === "type.googleapis.com/google.rpc.ErrorInfo" && typeof detail.value === "string") {
124
- try {
125
- errorInfo = ErrorInfo.fromBinary(
126
- Buffer.from(detail.value, "base64")
127
- );
128
- } catch {
129
- }
130
- } else if (detail.typeUrl === "type.googleapis.com/google.rpc.RetryInfo" && typeof detail.value === "string") {
131
- try {
132
- retryInfo = RetryInfo.fromBinary(
133
- Buffer.from(detail.value, "base64")
134
- );
135
- } catch {
136
- }
137
- }
138
- }
139
- return { code, message, errorInfo, retryInfo };
140
- }
141
- throw e;
82
+ const asGrpcError = (e) => {
83
+ let errorInfo;
84
+ let retryInfo;
85
+ if (typeof e === "object" && e !== null && "code" in e && "message" in e && "details" in e && Array.isArray(e.details)) {
86
+ const code = e.code;
87
+ const message = e.message;
88
+ for (const detail of e.details) if (detail.typeUrl === "type.googleapis.com/google.rpc.ErrorInfo" && typeof detail.value === "string") try {
89
+ errorInfo = ErrorInfo.fromBinary(Buffer.from(detail.value, "base64"));
90
+ } catch {}
91
+ else if (detail.typeUrl === "type.googleapis.com/google.rpc.RetryInfo" && typeof detail.value === "string") try {
92
+ retryInfo = RetryInfo.fromBinary(Buffer.from(detail.value, "base64"));
93
+ } catch {}
94
+ return {
95
+ code,
96
+ message,
97
+ errorInfo,
98
+ retryInfo
99
+ };
100
+ }
101
+ throw e;
142
102
  };
143
-
144
- // src/ledger-client.ts
145
- var supportedVersions = supportedLedgerApiVersions;
103
+ //#endregion
104
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/typeof.js
105
+ function _typeof(o) {
106
+ "@babel/helpers - typeof";
107
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
108
+ return typeof o;
109
+ } : function(o) {
110
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
111
+ }, _typeof(o);
112
+ }
113
+ //#endregion
114
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPrimitive.js
115
+ function toPrimitive(t, r) {
116
+ if ("object" != _typeof(t) || !t) return t;
117
+ var e = t[Symbol.toPrimitive];
118
+ if (void 0 !== e) {
119
+ var i = e.call(t, r || "default");
120
+ if ("object" != _typeof(i)) return i;
121
+ throw new TypeError("@@toPrimitive must return a primitive value.");
122
+ }
123
+ return ("string" === r ? String : Number)(t);
124
+ }
125
+ //#endregion
126
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPropertyKey.js
127
+ function toPropertyKey(t) {
128
+ var i = toPrimitive(t, "string");
129
+ return "symbol" == _typeof(i) ? i : i + "";
130
+ }
131
+ //#endregion
132
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/defineProperty.js
133
+ function _defineProperty(e, r, t) {
134
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
135
+ value: t,
136
+ enumerable: !0,
137
+ configurable: !0,
138
+ writable: !0
139
+ }) : e[r] = t, e;
140
+ }
141
+ //#endregion
142
+ //#region src/ledger-client.ts
143
+ const supportedVersions = supportedLedgerApiVersions;
144
+ function isValidGetEndpoint(resource) {
145
+ return LedgerGetRoutes.has(resource);
146
+ }
147
+ function isValidPostEndpoint(resource) {
148
+ return LedgerPostRoutes.has(resource);
149
+ }
146
150
  var LedgerClient = class {
147
- constructor({
148
- baseUrl,
149
- logger,
150
- accessTokenProvider,
151
- version
152
- }) {
153
- // privately manage the active connected version and associated client codegen
154
- __publicField(this, "clients");
155
- __publicField(this, "clientVersion", "3.5");
156
- __publicField(this, "initialized", false);
157
- __publicField(this, "accessTokenProvider");
158
- __publicField(this, "logger");
159
- __publicField(this, "synchronizerId");
160
- __publicField(this, "baseUrl");
161
- this.logger = logger.child({ component: "LedgerClient" });
162
- this.accessTokenProvider = accessTokenProvider;
163
- const authenticatedFetch = async (url, options = {}) => {
164
- const token = await this.accessTokenProvider.getAccessToken();
165
- return fetch(url, {
166
- ...options,
167
- headers: {
168
- ...options.headers || {},
169
- ...token && { Authorization: `Bearer ${token}` }
170
- }
171
- });
172
- };
173
- this.clients = {
174
- ...supportedVersions.reduce((acc, version2) => {
175
- acc[version2] = createClient({
176
- baseUrl: baseUrl.href,
177
- fetch: authenticatedFetch
178
- });
179
- return acc;
180
- }, {})
181
- };
182
- this.clientVersion = version ?? this.clientVersion;
183
- this.baseUrl = baseUrl;
184
- }
185
- get currentClient() {
186
- return this.clients[this.clientVersion];
187
- }
188
- async init() {
189
- if (!this.initialized) {
190
- this.logger.debug(
191
- `Initializing LedgerClient with version ${this.clientVersion} for url ${this.baseUrl.href}`
192
- );
193
- const versionFromClient = await this.currentClient.GET("/v2/version");
194
- this.logger.debug(
195
- {
196
- data: versionFromClient.data,
197
- status: versionFromClient.response.status
198
- },
199
- "getV2Version response"
200
- );
201
- this.clientVersion = this.parseSupportedVersions(
202
- versionFromClient.data?.version
203
- );
204
- this.initialized = true;
205
- }
206
- }
207
- getCurrentClientVersion() {
208
- return this.clientVersion;
209
- }
210
- parseSupportedVersions(version) {
211
- if (!version) {
212
- throw new Error("Client version missing from response");
213
- }
214
- const match = supportedVersions.find((v) => version.startsWith(v));
215
- if (!match) {
216
- this.logger.warn(
217
- `Unknown support of version ${version} (defaulting to ${this.clientVersion}) please check if a newer version is available that support this version of canton.`
218
- );
219
- return this.clientVersion;
220
- }
221
- return match;
222
- }
223
- /**
224
- * Check if a party exists
225
- *
226
- * @param partyId The ID of the party to look for
227
- * @returns A promise to resolves to a boolean.
228
- */
229
- async checkIfPartyExists(partyId) {
230
- try {
231
- const party = await this.get("/v2/parties/{party}", {
232
- path: { party: partyId }
233
- });
234
- return party.partyDetails !== void 0 && party.partyDetails[0].party === partyId;
235
- } catch {
236
- return false;
237
- }
238
- }
239
- /**
240
- * grant "Master User" rights to a user.
241
- *
242
- * this require running with an admin token.
243
- *
244
- * @param userId The ID of the user to grant rights to.
245
- * @param canReadAsAnyParty define if the user can read as any party.
246
- * @param canExecuteAsAnyParty define if the user can execute as any party.
247
- */
248
- async grantMasterUserRights(userId, canReadAsAnyParty, canExecuteAsAnyParty) {
249
- const rights = [];
250
- if (canReadAsAnyParty) {
251
- rights.push({
252
- kind: {
253
- CanReadAsAnyParty: { value: {} }
254
- }
255
- });
256
- }
257
- if (canExecuteAsAnyParty) {
258
- rights.push({
259
- kind: {
260
- CanExecuteAsAnyParty: {
261
- value: {}
262
- }
263
- }
264
- });
265
- }
266
- const result = await this.post(
267
- "/v2/users/{user-id}/rights",
268
- {
269
- identityProviderId: "",
270
- userId,
271
- rights
272
- },
273
- {
274
- path: {
275
- "user-id": userId
276
- }
277
- }
278
- );
279
- if (!result.newlyGrantedRights) {
280
- throw new Error("Failed to grant user rights");
281
- }
282
- }
283
- /**
284
- * Create a new user.
285
- *
286
- * @param userId The ID of the user to create.
287
- * @param primaryParty The primary party of the user.
288
- */
289
- async createUser(userId, primaryParty) {
290
- try {
291
- const existing = await this.get("/v2/users/{user-id}", {
292
- path: { "user-id": userId }
293
- });
294
- if (existing && existing.user) {
295
- return existing.user;
296
- }
297
- } catch {
298
- }
299
- return (await this.post("/v2/users", {
300
- user: {
301
- identityProviderId: "",
302
- id: userId,
303
- isDeactivated: false,
304
- primaryParty
305
- },
306
- rights: [
307
- {
308
- kind: {
309
- ParticipantAdmin: {
310
- value: {}
311
- }
312
- }
313
- }
314
- ]
315
- })).user;
316
- }
317
- /**
318
- * Grants a user the right to act as a party, while ensuring the party exists.
319
- *
320
- * @param userId The ID of the user to grant rights to.
321
- * @param partyId The ID of the party to grant rights for.
322
- * @param maxTries Optional max number of retries with default 30. May be increased if expecting heavy load.
323
- * @param retryIntervalMs Optional interval between retries to verify that party exists with default 2000ms. May be increased if expecting heavy load.
324
- * @returns A promise that resolves when the rights have been granted.
325
- */
326
- async waitForPartyAndGrantUserRights(userId, partyId, maxTries = 30, retryIntervalMs = 2e3) {
327
- await this.init();
328
- let partyFound = false;
329
- let tries = 0;
330
- while (!partyFound && tries < maxTries) {
331
- partyFound = await this.checkIfPartyExists(partyId);
332
- await new Promise((resolve) => setTimeout(resolve, retryIntervalMs));
333
- tries++;
334
- }
335
- if (tries >= maxTries) {
336
- throw new Error(
337
- `timed out waiting for new party to appear after ${maxTries} tries`
338
- );
339
- }
340
- const result = await this.grantRights(userId, {
341
- actAs: [partyId]
342
- });
343
- if (!result.newlyGrantedRights) {
344
- throw new Error("Failed to grant user rights");
345
- }
346
- return;
347
- }
348
- async grantRights(userId, userRightsOptions) {
349
- await this.init();
350
- const rights = [];
351
- for (const partyId of userRightsOptions.readAs ?? []) {
352
- rights.push({
353
- kind: {
354
- CanReadAs: {
355
- value: {
356
- party: partyId
357
- }
358
- }
359
- }
360
- });
361
- }
362
- for (const partyId of userRightsOptions.actAs ?? []) {
363
- rights.push({
364
- kind: {
365
- CanActAs: {
366
- value: {
367
- party: partyId
368
- }
369
- }
370
- }
371
- });
372
- }
373
- if (userRightsOptions.canReadAsAnyParty) {
374
- rights.push({
375
- kind: {
376
- CanReadAsAnyParty: { value: {} }
377
- }
378
- });
379
- }
380
- if (userRightsOptions.canExecuteAsAnyParty) {
381
- rights.push({
382
- kind: {
383
- CanExecuteAsAnyParty: {
384
- value: {}
385
- }
386
- }
387
- });
388
- }
389
- const result = await this.post(
390
- "/v2/users/{user-id}/rights",
391
- {
392
- identityProviderId: "",
393
- userId,
394
- rights
395
- },
396
- {
397
- path: {
398
- "user-id": userId
399
- }
400
- }
401
- );
402
- if (!result.newlyGrantedRights) {
403
- throw new Error("Failed to grant user rights");
404
- }
405
- return result;
406
- }
407
- async allocateExternalParty(synchronizerId, onboardingTransactions, multiHashSignatures) {
408
- await this.init();
409
- const resp = await this.currentClient.POST(
410
- "/v2/parties/external/allocate",
411
- {
412
- body: {
413
- synchronizer: synchronizerId,
414
- identityProviderId: "",
415
- onboardingTransactions,
416
- multiHashSignatures
417
- }
418
- }
419
- );
420
- return this.valueOrError(resp);
421
- }
422
- async generateTopology(synchronizerId, publicKey, partyHint, localParticipantObservationOnly = false, confirmationThreshold = 1, otherConfirmingParticipantUids = [], observingParticipantUids = []) {
423
- await this.init();
424
- const body = {
425
- synchronizer: synchronizerId,
426
- partyHint,
427
- publicKey: {
428
- format: "CRYPTO_KEY_FORMAT_RAW",
429
- keyData: publicKey,
430
- keySpec: "SIGNING_KEY_SPEC_EC_CURVE25519"
431
- },
432
- localParticipantObservationOnly,
433
- confirmationThreshold,
434
- otherConfirmingParticipantUids,
435
- observingParticipantUids
436
- };
437
- this.logger.debug(body, "generateTopology request body");
438
- const resp = await this.currentClient.POST(
439
- "/v2/parties/external/generate-topology",
440
- { body }
441
- );
442
- return this.valueOrError(resp);
443
- }
444
- // Retrieve an (arbitrary) synchronizer id from the validator.
445
- // This synchronizer id is cached for the remainder of this object's life.
446
- async getSynchronizerId() {
447
- if (this.synchronizerId) return this.synchronizerId;
448
- const response = await this.getWithRetry(
449
- "/v2/state/connected-synchronizers"
450
- );
451
- if (!response.connectedSynchronizers?.[0]) {
452
- throw new Error("No connected synchronizers found");
453
- }
454
- const synchronizerId = response.connectedSynchronizers[0].synchronizerId;
455
- if (response.connectedSynchronizers.length > 1) {
456
- this.logger.warn(
457
- `Found ${response.connectedSynchronizers.length} synchronizers, defaulting to ${synchronizerId}`
458
- );
459
- }
460
- this.synchronizerId = synchronizerId;
461
- return synchronizerId;
462
- }
463
- async postWithRetry(path, body, retryOptions = defaultRetryableOptions, params, additionalOptions) {
464
- return await retryable(
465
- () => this.post(path, body, params, additionalOptions),
466
- retryOptions,
467
- this.logger
468
- ).catch((e) => {
469
- this.logger.warn(
470
- `Error in postWithRetry for path ${path} with body retry options ${JSON.stringify(retryOptions)}`
471
- );
472
- this.logger.debug(JSON.stringify(body));
473
- throw asJsCantonError(e);
474
- });
475
- }
476
- async getWithRetry(path, retryOptions = defaultRetryableOptions, params) {
477
- return await retryable(
478
- () => this.get(path, params),
479
- retryOptions,
480
- this.logger
481
- ).catch((e) => {
482
- this.logger.warn(
483
- `Error in getWithRetry for path ${path} with retry options ${JSON.stringify(retryOptions)}`
484
- );
485
- throw asJsCantonError(e);
486
- });
487
- }
488
- async patchWithRetry(path, body, retryOptions = defaultRetryableOptions, params, additionalOptions) {
489
- return await retryable(
490
- () => this.patch(path, body, params, additionalOptions),
491
- retryOptions,
492
- this.logger
493
- ).catch((e) => {
494
- this.logger.warn(
495
- `Error in patchWithRetry for path ${path} with body retry options ${JSON.stringify(retryOptions)}`
496
- );
497
- throw asJsCantonError(e);
498
- });
499
- }
500
- async patch(path, body, params, additionalOptions) {
501
- const options = { body, params, ...additionalOptions };
502
- const resp = await this.currentClient.PATCH(path, options);
503
- return this.valueOrError(resp);
504
- }
505
- async post(path, body, params, additionalOptions) {
506
- const options = { body, params, ...additionalOptions };
507
- const resp = await this.currentClient.POST(path, options);
508
- return this.valueOrError(resp);
509
- }
510
- async get(path, params) {
511
- await this.init();
512
- const options = { params };
513
- const resp = await this.currentClient.GET(path, options);
514
- return this.valueOrError(resp);
515
- }
516
- async valueOrError(response) {
517
- if (response.data === void 0) {
518
- return Promise.reject(response.error);
519
- } else {
520
- return Promise.resolve(response.data);
521
- }
522
- }
151
+ constructor({ baseUrl, logger, accessTokenProvider, version }) {
152
+ _defineProperty(this, "clients", void 0);
153
+ _defineProperty(this, "clientVersion", "3.5");
154
+ _defineProperty(this, "initialized", false);
155
+ _defineProperty(this, "accessTokenProvider", void 0);
156
+ _defineProperty(this, "logger", void 0);
157
+ _defineProperty(this, "synchronizerId", void 0);
158
+ _defineProperty(this, "baseUrl", void 0);
159
+ this.logger = logger.child({ component: "LedgerClient" });
160
+ this.accessTokenProvider = accessTokenProvider;
161
+ const authenticatedFetch = async (url, options = {}) => {
162
+ const token = await this.accessTokenProvider.getAccessToken();
163
+ return fetch(url, {
164
+ ...options,
165
+ headers: {
166
+ ...options.headers || {},
167
+ ...token && { Authorization: `Bearer ${token}` }
168
+ }
169
+ });
170
+ };
171
+ this.clients = { ...supportedVersions.reduce((acc, version) => {
172
+ acc[version] = createClient({
173
+ baseUrl: baseUrl.href,
174
+ fetch: authenticatedFetch
175
+ });
176
+ return acc;
177
+ }, {}) };
178
+ this.clientVersion = version ?? this.clientVersion;
179
+ this.baseUrl = baseUrl;
180
+ }
181
+ get currentClient() {
182
+ return this.clients[this.clientVersion];
183
+ }
184
+ async init() {
185
+ if (!this.initialized) {
186
+ this.logger.debug(`Initializing LedgerClient with version ${this.clientVersion} for url ${this.baseUrl.href}`);
187
+ const versionFromClient = await this.currentClient.GET("/v2/version");
188
+ this.logger.debug({
189
+ data: versionFromClient.data,
190
+ status: versionFromClient.response.status
191
+ }, "getV2Version response");
192
+ this.clientVersion = this.parseSupportedVersions(versionFromClient.data?.version);
193
+ this.initialized = true;
194
+ }
195
+ }
196
+ getCurrentClientVersion() {
197
+ return this.clientVersion;
198
+ }
199
+ parseSupportedVersions(version) {
200
+ if (!version) throw new Error("Client version missing from response");
201
+ const match = supportedVersions.find((v) => version.startsWith(v));
202
+ if (!match) {
203
+ this.logger.warn(`Unknown support of version ${version} (defaulting to ${this.clientVersion}) please check if a newer version is available that support this version of canton.`);
204
+ return this.clientVersion;
205
+ }
206
+ return match;
207
+ }
208
+ /**
209
+ * Check if a party exists
210
+ *
211
+ * @param partyId The ID of the party to look for
212
+ * @returns A promise to resolves to a boolean.
213
+ */
214
+ async checkIfPartyExists(partyId) {
215
+ try {
216
+ const party = await this.get("/v2/parties/{party}", { path: { party: partyId } });
217
+ return party.partyDetails !== void 0 && party.partyDetails[0].party === partyId;
218
+ } catch {
219
+ return false;
220
+ }
221
+ }
222
+ /**
223
+ * grant "Master User" rights to a user.
224
+ *
225
+ * this require running with an admin token.
226
+ *
227
+ * @param userId The ID of the user to grant rights to.
228
+ * @param canReadAsAnyParty define if the user can read as any party.
229
+ * @param canExecuteAsAnyParty define if the user can execute as any party.
230
+ */
231
+ async grantMasterUserRights(userId, canReadAsAnyParty, canExecuteAsAnyParty) {
232
+ const rights = [];
233
+ if (canReadAsAnyParty) rights.push({ kind: { CanReadAsAnyParty: { value: {} } } });
234
+ if (canExecuteAsAnyParty) rights.push({ kind: { CanExecuteAsAnyParty: { value: {} } } });
235
+ if (!(await this.post("/v2/users/{user-id}/rights", {
236
+ identityProviderId: "",
237
+ userId,
238
+ rights
239
+ }, { path: { "user-id": userId } })).newlyGrantedRights) throw new Error("Failed to grant user rights");
240
+ }
241
+ /**
242
+ * Create a new user.
243
+ *
244
+ * @param userId The ID of the user to create.
245
+ * @param primaryParty The primary party of the user.
246
+ */
247
+ async createUser(userId, primaryParty) {
248
+ try {
249
+ const existing = await this.get("/v2/users/{user-id}", { path: { "user-id": userId } });
250
+ if (existing && existing.user) return existing.user;
251
+ } catch {}
252
+ return (await this.post("/v2/users", {
253
+ user: {
254
+ identityProviderId: "",
255
+ id: userId,
256
+ isDeactivated: false,
257
+ primaryParty
258
+ },
259
+ rights: [{ kind: { ParticipantAdmin: { value: {} } } }]
260
+ })).user;
261
+ }
262
+ /**
263
+ * Grants a user the right to act as a party, while ensuring the party exists.
264
+ *
265
+ * @param userId The ID of the user to grant rights to.
266
+ * @param partyId The ID of the party to grant rights for.
267
+ * @param maxTries Optional max number of retries with default 30. May be increased if expecting heavy load.
268
+ * @param retryIntervalMs Optional interval between retries to verify that party exists with default 2000ms. May be increased if expecting heavy load.
269
+ * @returns A promise that resolves when the rights have been granted.
270
+ */
271
+ async waitForPartyAndGrantUserRights(userId, partyId, maxTries = 30, retryIntervalMs = 2e3) {
272
+ await this.init();
273
+ let partyFound = false;
274
+ let tries = 0;
275
+ while (!partyFound && tries < maxTries) {
276
+ partyFound = await this.checkIfPartyExists(partyId);
277
+ await new Promise((resolve) => setTimeout(resolve, retryIntervalMs));
278
+ tries++;
279
+ }
280
+ if (tries >= maxTries) throw new Error(`timed out waiting for new party to appear after ${maxTries} tries`);
281
+ if (!(await this.grantRights(userId, { actAs: [partyId] })).newlyGrantedRights) throw new Error("Failed to grant user rights");
282
+ }
283
+ async grantRights(userId, userRightsOptions) {
284
+ await this.init();
285
+ const rights = [];
286
+ for (const partyId of userRightsOptions.readAs ?? []) rights.push({ kind: { CanReadAs: { value: { party: partyId } } } });
287
+ for (const partyId of userRightsOptions.actAs ?? []) rights.push({ kind: { CanActAs: { value: { party: partyId } } } });
288
+ if (userRightsOptions.canReadAsAnyParty) rights.push({ kind: { CanReadAsAnyParty: { value: {} } } });
289
+ if (userRightsOptions.canExecuteAsAnyParty) rights.push({ kind: { CanExecuteAsAnyParty: { value: {} } } });
290
+ const result = await this.post("/v2/users/{user-id}/rights", {
291
+ identityProviderId: "",
292
+ userId,
293
+ rights
294
+ }, { path: { "user-id": userId } });
295
+ if (!result.newlyGrantedRights) throw new Error("Failed to grant user rights");
296
+ return result;
297
+ }
298
+ async allocateExternalParty(synchronizerId, onboardingTransactions, multiHashSignatures) {
299
+ await this.init();
300
+ const resp = await this.currentClient.POST("/v2/parties/external/allocate", { body: {
301
+ synchronizer: synchronizerId,
302
+ identityProviderId: "",
303
+ onboardingTransactions,
304
+ multiHashSignatures
305
+ } });
306
+ return this.valueOrError(resp);
307
+ }
308
+ async generateTopology(synchronizerId, publicKey, partyHint, localParticipantObservationOnly = false, confirmationThreshold = 1, otherConfirmingParticipantUids = [], observingParticipantUids = []) {
309
+ await this.init();
310
+ const body = {
311
+ synchronizer: synchronizerId,
312
+ partyHint,
313
+ publicKey: {
314
+ format: "CRYPTO_KEY_FORMAT_RAW",
315
+ keyData: publicKey,
316
+ keySpec: "SIGNING_KEY_SPEC_EC_CURVE25519"
317
+ },
318
+ localParticipantObservationOnly,
319
+ confirmationThreshold,
320
+ otherConfirmingParticipantUids,
321
+ observingParticipantUids
322
+ };
323
+ this.logger.debug(body, "generateTopology request body");
324
+ const resp = await this.currentClient.POST("/v2/parties/external/generate-topology", { body });
325
+ return this.valueOrError(resp);
326
+ }
327
+ async getSynchronizerId() {
328
+ if (this.synchronizerId) return this.synchronizerId;
329
+ const response = await this.getWithRetry("/v2/state/connected-synchronizers");
330
+ if (!response.connectedSynchronizers?.[0]) throw new Error("No connected synchronizers found");
331
+ const synchronizerId = response.connectedSynchronizers[0].synchronizerId;
332
+ if (response.connectedSynchronizers.length > 1) this.logger.warn(`Found ${response.connectedSynchronizers.length} synchronizers, defaulting to ${synchronizerId}`);
333
+ this.synchronizerId = synchronizerId;
334
+ return synchronizerId;
335
+ }
336
+ async postWithRetry(path, body, retryOptions = defaultRetryableOptions, params, additionalOptions) {
337
+ return await retryable(() => this.post(path, body, params, additionalOptions), retryOptions, this.logger).catch((e) => {
338
+ this.logger.warn(`Error in postWithRetry for path ${path} with body retry options ${JSON.stringify(retryOptions)}`);
339
+ this.logger.debug(JSON.stringify(body));
340
+ throw asJsCantonError(e);
341
+ });
342
+ }
343
+ async getWithRetry(path, retryOptions = defaultRetryableOptions, params) {
344
+ return await retryable(() => this.get(path, params), retryOptions, this.logger).catch((e) => {
345
+ this.logger.warn(`Error in getWithRetry for path ${path} with retry options ${JSON.stringify(retryOptions)}`);
346
+ throw asJsCantonError(e);
347
+ });
348
+ }
349
+ async patchWithRetry(path, body, retryOptions = defaultRetryableOptions, params, additionalOptions) {
350
+ return await retryable(() => this.patch(path, body, params, additionalOptions), retryOptions, this.logger).catch((e) => {
351
+ this.logger.warn(`Error in patchWithRetry for path ${path} with body retry options ${JSON.stringify(retryOptions)}`);
352
+ throw asJsCantonError(e);
353
+ });
354
+ }
355
+ async patch(path, body, params, additionalOptions) {
356
+ const options = {
357
+ body,
358
+ params,
359
+ ...additionalOptions
360
+ };
361
+ const resp = await this.currentClient.PATCH(path, options);
362
+ return this.valueOrError(resp);
363
+ }
364
+ async post(path, body, params, additionalOptions) {
365
+ const options = {
366
+ body,
367
+ params,
368
+ ...additionalOptions
369
+ };
370
+ const resp = await this.currentClient.POST(path, options);
371
+ return this.valueOrError(resp);
372
+ }
373
+ async get(path, params) {
374
+ await this.init();
375
+ const options = { params };
376
+ const resp = await this.currentClient.GET(path, options);
377
+ return this.valueOrError(resp);
378
+ }
379
+ async valueOrError(response) {
380
+ if (response.data === void 0) return Promise.reject(response.error);
381
+ else return Promise.resolve(response.data);
382
+ }
523
383
  };
384
+ //#endregion
385
+ export { LedgerClient, asJsCantonError, awaitCompletion, defaultRetryableOptions, isJsCantonError, isValidGetEndpoint, isValidPostEndpoint, promiseWithTimeout, supportedVersions };
524
386
 
525
- export { LedgerClient, asJsCantonError, awaitCompletion, defaultRetryableOptions, isJsCantonError, promiseWithTimeout, supportedVersions };
526
- //# sourceMappingURL=index.js.map
527
387
  //# sourceMappingURL=index.js.map