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