@canton-network/core-ledger-client 1.3.2 → 1.5.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
@@ -3,7 +3,6 @@
3
3
  var coreLedgerClientTypes = require('@canton-network/core-ledger-client-types');
4
4
  var createClient = require('openapi-fetch');
5
5
  var coreLedgerProto = require('@canton-network/core-ledger-proto');
6
- var typescriptLruCache = require('typescript-lru-cache');
7
6
 
8
7
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
8
 
@@ -148,482 +147,6 @@ var asGrpcError = (e) => {
148
147
  throw e;
149
148
  };
150
149
 
151
- // src/acs/acs-container.ts
152
- var ACS_UPDATE_CONFIG = {
153
- // How many events do we accumulate before we prune (compact) the ACS history - set to 0 to enable to compact all events, which is more efficient as long as application always ask for increasing (or equal) offsets
154
- maxEventsBeforePrune: 150,
155
- // When we compact the ACS history, we keep all events within this offset delta of the last seen update offset - set 0 to allow to compact everything
156
- safeOffsetDeltaForPrune: 200,
157
- // How many updates do we fetch at once when fetching updates - if there are more updates, we will fetch again until we have caught up (returned data is always complete to the requested endInclusive offset - even if that means multiple fetches)
158
- maxUpdatesToFetch: 100,
159
- // Timeout for receiving the first element from the WebSocket stream when reading the ACS - if this timeout is reached before the first element is returned, we fall back to HTTP
160
- // lower values will make the UI more responsive in case of problems, but may lead to unnecessary fallbacks
161
- wsTimeoutBeforeFirstElement: 1e4
162
- };
163
- if (typeof window !== "undefined") {
164
- window["ACS_UPDATE_CONFIG"] = ACS_UPDATE_CONFIG;
165
- }
166
- var ACSContainer = class _ACSContainer {
167
- constructor(orginalContainer = null, settings = { includeCreatedEventBlob: true }) {
168
- __publicField(this, "acsSet", null);
169
- __publicField(this, "settings");
170
- this.acsSet = orginalContainer ? orginalContainer.acsSet : null;
171
- this.settings = settings;
172
- }
173
- async update(offset, key, api, wsSupport) {
174
- if (this.acsSet === null) {
175
- const acs = await this.readACS(offset, key, api, wsSupport);
176
- this.acsSet = acs;
177
- return _ACSContainer.calculateAt(acs, offset);
178
- }
179
- if (this.acsSet.acsOffset > offset) {
180
- this.acsSet = null;
181
- return this.update(offset, key, api);
182
- }
183
- if (this.acsSet.updates.length >= ACS_UPDATE_CONFIG.maxEventsBeforePrune) {
184
- this.acsSet = await _ACSContainer.compact(this.acsSet);
185
- }
186
- const updates = await _ACSContainer.updateContracts(
187
- this.acsSet.lastUpdateOffset,
188
- offset,
189
- this.createEventFormat(key),
190
- api
191
- );
192
- const [newEvents, newOffset] = _ACSContainer.extractEvents(
193
- this.acsSet.lastUpdateOffset,
194
- updates
195
- );
196
- if (newOffset > this.acsSet.lastUpdateOffset) {
197
- this.acsSet = {
198
- ...this.acsSet,
199
- lastUpdateOffset: newOffset,
200
- updates: this.acsSet.updates.concat(newEvents)
201
- };
202
- }
203
- if (updates.length >= ACS_UPDATE_CONFIG.maxUpdatesToFetch) {
204
- return this.update(offset, key, api);
205
- }
206
- this.acsSet = {
207
- ...this.acsSet,
208
- lastUpdateOffset: offset
209
- // we have caught up
210
- };
211
- return _ACSContainer.calculateAt(this.acsSet, offset);
212
- }
213
- static calculateAt(acs, offset) {
214
- if (acs.acsOffset > offset) {
215
- return Promise.reject(
216
- Error(
217
- // This should never happen as we check this before calling calculateAt
218
- `Cannot calculate ACS at offset ${offset} when initial ACS is at ${acs.acsOffset}`
219
- )
220
- );
221
- }
222
- const addedContracts = [];
223
- const removedContractIds = /* @__PURE__ */ new Set();
224
- acs.updates.forEach((update) => {
225
- if (update.offset <= offset) {
226
- if (update.created) {
227
- const createdEv = update.created;
228
- const activeContract = {
229
- workflowId: update.workflowId ?? "",
230
- contractEntry: {
231
- JsActiveContract: {
232
- createdEvent: createdEv,
233
- synchronizerId: update.synchronizerId ?? "",
234
- reassignmentCounter: 0
235
- }
236
- }
237
- };
238
- addedContracts.push(activeContract);
239
- } else if (update.archivedContractId) {
240
- removedContractIds.add(update.archivedContractId);
241
- }
242
- }
243
- });
244
- const createdContracts = acs.initialAcs.concat(addedContracts);
245
- const result = createdContracts.filter(({ contractEntry }) => {
246
- if (!contractEntry) {
247
- return false;
248
- }
249
- const id = "JsActiveContract" in contractEntry ? contractEntry.JsActiveContract?.createdEvent?.contractId ?? "" : "";
250
- return !removedContractIds.has(id);
251
- });
252
- return Promise.resolve(result);
253
- }
254
- static extractEvents(fromOffset, updates) {
255
- const newEvents = [];
256
- let newOffset = fromOffset;
257
- updates.forEach((update) => {
258
- if (!update || !update.update) {
259
- return;
260
- }
261
- if ("Transaction" in update.update) {
262
- const transaction = update.update.Transaction;
263
- const trOffset = transaction?.value?.offset;
264
- if (trOffset && trOffset > newOffset) {
265
- const events = transaction?.value?.events ?? [];
266
- events.forEach((event) => {
267
- if (!event) {
268
- return;
269
- }
270
- if ("CreatedEvent" in event) {
271
- const acUpdate = {
272
- created: event.CreatedEvent,
273
- archivedContractId: null,
274
- offset: trOffset,
275
- workflowId: transaction?.value?.workflowId ?? null,
276
- synchronizerId: transaction?.value?.synchronizerId ?? null
277
- };
278
- newEvents.push(acUpdate);
279
- newOffset = trOffset;
280
- } else if ("ArchivedEvent" in event) {
281
- const archivedEvent = event.ArchivedEvent;
282
- const acUpdate = {
283
- created: null,
284
- archivedContractId: archivedEvent?.contractId ?? null,
285
- offset: trOffset,
286
- workflowId: transaction?.value?.workflowId ?? null,
287
- synchronizerId: transaction?.value?.synchronizerId ?? null
288
- };
289
- newEvents.push(acUpdate);
290
- newOffset = trOffset;
291
- }
292
- });
293
- }
294
- } else if ("OffsetCheckpoint" in update.update) {
295
- const checkpoint = update.update.OffsetCheckpoint;
296
- const offset = checkpoint?.value?.offset;
297
- if (offset) {
298
- newOffset = offset;
299
- }
300
- } else {
301
- console.log(
302
- `ACS Update got unknown update type: ${JSON.stringify(update.update)}`
303
- );
304
- }
305
- });
306
- return [newEvents, newOffset];
307
- }
308
- static async updateContracts(startOffset, endOffset, eventFormat, api) {
309
- const request = {
310
- beginExclusive: startOffset,
311
- endInclusive: endOffset,
312
- updateFormat: {
313
- includeTransactions: {
314
- eventFormat,
315
- transactionShape: "TRANSACTION_SHAPE_ACS_DELTA"
316
- }
317
- },
318
- verbose: false
319
- };
320
- const params = {
321
- query: {
322
- limit: ACS_UPDATE_CONFIG.maxUpdatesToFetch,
323
- stream_idle_timeout_ms: 1e3
324
- }
325
- };
326
- return api.postWithRetry(
327
- "/v2/updates/flats",
328
- request,
329
- defaultRetryableOptions,
330
- params
331
- );
332
- }
333
- static async compact(acs) {
334
- const newAcsOffset = Math.max(
335
- acs.acsOffset,
336
- acs.lastUpdateOffset - ACS_UPDATE_CONFIG.safeOffsetDeltaForPrune
337
- );
338
- if (newAcsOffset > acs.acsOffset) {
339
- const responses = await _ACSContainer.calculateAt(acs, newAcsOffset);
340
- return {
341
- acsOffset: newAcsOffset,
342
- initialAcs: responses,
343
- lastUpdateOffset: acs.lastUpdateOffset,
344
- updates: acs.updates.filter(
345
- (update) => update.offset > newAcsOffset
346
- )
347
- };
348
- }
349
- return acs;
350
- }
351
- async readACS(offset, key, api, wsSupport) {
352
- if (wsSupport && wsSupport.enabled()) {
353
- return this.readACSUsingWs(offset, key, wsSupport).catch(() => {
354
- console.log("Falling back to HTTP for ACS read");
355
- return this.readHttpACS(offset, key, api);
356
- });
357
- }
358
- return this.readHttpACS(offset, key, api);
359
- }
360
- async readHttpACS(offset, key, api) {
361
- const format = this.createEventFormat(key);
362
- const acs = await api.postWithRetry(
363
- "/v2/state/active-contracts",
364
- {
365
- activeAtOffset: offset,
366
- verbose: false,
367
- eventFormat: format
368
- },
369
- defaultRetryableOptions
370
- );
371
- return {
372
- acsOffset: offset,
373
- initialAcs: acs,
374
- lastUpdateOffset: offset,
375
- updates: []
376
- };
377
- }
378
- readACSUsingWs(offset, key, wsSupport) {
379
- const wsACSURL = `${wsSupport.baseUrl}/v2/state/active-contracts`;
380
- const format = this.createEventFormat(key);
381
- const request = {
382
- activeAtOffset: offset,
383
- verbose: false,
384
- eventFormat: format
385
- };
386
- return new Promise((resolve, reject) => {
387
- const ws = new WebSocket(wsACSURL, wsSupport.extractProtocols());
388
- const results = [];
389
- let finished = false;
390
- let error = null;
391
- setTimeout(() => {
392
- if (!finished && !error && results.length === 0) {
393
- error = Error(
394
- `No data received from WebSocket ${wsACSURL} within ${ACS_UPDATE_CONFIG.wsTimeoutBeforeFirstElement}ms`
395
- );
396
- wsSupport.reportError(error);
397
- reject(error);
398
- ws.close();
399
- }
400
- }, ACS_UPDATE_CONFIG.wsTimeoutBeforeFirstElement);
401
- ws.onopen = () => {
402
- ws.send(JSON.stringify(request));
403
- };
404
- ws.onmessage = (event) => {
405
- try {
406
- const data = JSON.parse(
407
- event.data
408
- );
409
- results.push(data);
410
- } catch (err) {
411
- console.error("Invalid JSON:", err);
412
- }
413
- };
414
- ws.onerror = () => {
415
- error = new Error("WebSocket error");
416
- wsSupport.reportError(error);
417
- reject(error);
418
- };
419
- ws.onclose = () => {
420
- finished = true;
421
- if (!error) {
422
- wsSupport.reportSuccess();
423
- resolve({
424
- acsOffset: offset,
425
- initialAcs: results,
426
- lastUpdateOffset: offset,
427
- updates: []
428
- });
429
- }
430
- };
431
- });
432
- }
433
- createInterfaceFilter(interfaceId) {
434
- return {
435
- cumulative: [
436
- {
437
- identifierFilter: {
438
- InterfaceFilter: {
439
- value: {
440
- interfaceId,
441
- includeInterfaceView: true,
442
- includeCreatedEventBlob: this.settings.includeCreatedEventBlob
443
- }
444
- }
445
- }
446
- }
447
- ]
448
- };
449
- }
450
- createTemplateFilter(templateId) {
451
- return {
452
- cumulative: [
453
- {
454
- identifierFilter: {
455
- TemplateFilter: {
456
- value: {
457
- templateId,
458
- includeCreatedEventBlob: this.settings.includeCreatedEventBlob
459
- }
460
- }
461
- }
462
- }
463
- ]
464
- };
465
- }
466
- createEventFormat(key) {
467
- const cumulativeFilter = key.templateId ? this.createTemplateFilter(key.templateId) : this.createInterfaceFilter(key.interfaceId ?? "");
468
- if (key.party) {
469
- if (!key.interfaceId && !key.templateId) {
470
- return {
471
- filtersByParty: {
472
- [key.party]: {}
473
- },
474
- verbose: false
475
- };
476
- }
477
- return {
478
- filtersByParty: {
479
- [key.party]: cumulativeFilter
480
- },
481
- verbose: false
482
- };
483
- }
484
- return {
485
- filtersForAnyParty: cumulativeFilter,
486
- verbose: false
487
- };
488
- }
489
- };
490
- var DEFAULT_MAX_CACHE_SIZE = 100;
491
- var DEFAULT_ENTRY_EXPIRATION_TIME = 10 * 60 * 1e3;
492
- var SharedACSCache = new typescriptLruCache.LRUCache({
493
- maxSize: DEFAULT_MAX_CACHE_SIZE,
494
- entryExpirationTimeInMS: DEFAULT_ENTRY_EXPIRATION_TIME,
495
- onEntryEvicted: (entry) => {
496
- console.debug(`${entry} has expired`);
497
- SharedACSCacheStats.evictions++;
498
- }
499
- });
500
- var SharedACSCacheStats = {
501
- hits: 0,
502
- misses: 0,
503
- evictions: 0,
504
- totalLookupTime: 0,
505
- totalCacheServeTime: 0
506
- };
507
-
508
- // src/acs/acs-helper.ts
509
- var ACSHelper = class _ACSHelper {
510
- constructor(apiInstance, _logger, options, sharedCache) {
511
- __publicField(this, "contractsSet");
512
- __publicField(this, "apiInstance");
513
- __publicField(this, "wsSupport");
514
- __publicField(this, "logger");
515
- __publicField(this, "includeCreatedEventBlob");
516
- __publicField(this, "totalCacheServeTime", 0);
517
- this.contractsSet = sharedCache ?? new typescriptLruCache.LRUCache({
518
- maxSize: options?.maxCacheSize ?? DEFAULT_MAX_CACHE_SIZE,
519
- entryExpirationTimeInMS: options?.entryExpirationTime ?? DEFAULT_ENTRY_EXPIRATION_TIME,
520
- // 10 minutes
521
- onEntryEvicted: (entry) => {
522
- this.logger.debug(
523
- `entry ${entry.key} isExpired = ${entry.isExpired}. evicting entry.`
524
- );
525
- SharedACSCacheStats.evictions++;
526
- }
527
- });
528
- this.apiInstance = apiInstance;
529
- this.wsSupport = options?.wsSupport;
530
- this.logger = _logger.child({ component: "ACSHelper" });
531
- this.includeCreatedEventBlob = options?.includeCreatedEventBlob ?? true;
532
- }
533
- getCacheStats() {
534
- const totalCalls = SharedACSCacheStats.hits + SharedACSCacheStats.misses;
535
- const hitRate = totalCalls ? SharedACSCacheStats.hits / totalCalls * 100 : 0;
536
- const avgLookupTime = totalCalls > 0 ? SharedACSCacheStats.totalLookupTime / totalCalls : 0;
537
- return {
538
- totalCalls,
539
- hits: SharedACSCacheStats.hits,
540
- misses: SharedACSCacheStats.misses,
541
- evictions: SharedACSCacheStats.evictions,
542
- cacheSize: this.contractsSet.size,
543
- hitRate: hitRate.toFixed(2) + "%",
544
- averageLookupTime: avgLookupTime.toFixed(3) + " ms",
545
- cacheServeTime: SharedACSCacheStats.totalCacheServeTime.toFixed(3)
546
- };
547
- }
548
- static createKey(party, templateId, interfaceId) {
549
- return { party, templateId, interfaceId };
550
- }
551
- static keyToString(key, ledgerBaseUrl) {
552
- return `${ledgerBaseUrl}_${key.party ? key.party : "ANY"}_T:${key.templateId ?? "()"}_I:${key.interfaceId ?? "()"}`;
553
- }
554
- findACSContainer(key) {
555
- const keyStr = _ACSHelper.keyToString(key, this.apiInstance.baseUrl.href);
556
- const start = performance.now();
557
- const existing = this.contractsSet.get(keyStr);
558
- const end = performance.now();
559
- SharedACSCacheStats.totalLookupTime += end - start;
560
- if (existing) {
561
- SharedACSCacheStats.hits++;
562
- this.logger.debug("cache hit");
563
- return existing;
564
- }
565
- this.logger.debug("cache miss");
566
- SharedACSCacheStats.misses++;
567
- const newContainer = new ACSContainer(void 0, {
568
- includeCreatedEventBlob: this.includeCreatedEventBlob
569
- });
570
- this.contractsSet.set(keyStr, newContainer);
571
- return newContainer;
572
- }
573
- async updateSingleKey(offset, key) {
574
- const start = performance.now();
575
- const container = this.findACSContainer(key);
576
- const result = await container.update(
577
- offset,
578
- key,
579
- this.apiInstance,
580
- this.wsSupport
581
- );
582
- const end = performance.now();
583
- const keyStr = _ACSHelper.keyToString(key, this.apiInstance.baseUrl.href);
584
- if (this.contractsSet.has(keyStr)) {
585
- SharedACSCacheStats.totalCacheServeTime += end - start;
586
- }
587
- return result;
588
- }
589
- async queryAcsByKeys(offset, keys) {
590
- const result = [];
591
- for (const key of keys) {
592
- const contracts = await this.updateSingleKey(offset, key);
593
- result.push(...contracts);
594
- }
595
- return result;
596
- }
597
- async activeContractsForTemplates(offset, parties, templateIds) {
598
- const keys = parties.flatMap(
599
- (party) => templateIds.map(
600
- (templateId) => _ACSHelper.createKey(party, templateId, void 0)
601
- )
602
- );
603
- return this.queryAcsByKeys(offset, keys);
604
- }
605
- async activeContractsForInterfaces(offset, parties, interfaceIds) {
606
- const keys = parties.flatMap(
607
- (party) => interfaceIds.map(
608
- (interfaceId) => _ACSHelper.createKey(party, void 0, interfaceId)
609
- )
610
- );
611
- return this.queryAcsByKeys(offset, keys);
612
- }
613
- async activeContractsForTemplate(offset, partyFilter, templateId) {
614
- return this.updateSingleKey(
615
- offset,
616
- _ACSHelper.createKey(partyFilter, templateId, void 0)
617
- );
618
- }
619
- async activeContractsForInterface(offset, partyFilter, interfaceId) {
620
- return this.updateSingleKey(
621
- offset,
622
- _ACSHelper.createKey(partyFilter, void 0, interfaceId)
623
- );
624
- }
625
- };
626
-
627
150
  // src/ledger-client.ts
628
151
  var supportedVersions = coreLedgerClientTypes.supportedLedgerApiVersions;
629
152
  var LedgerClient = class {
@@ -631,15 +154,13 @@ var LedgerClient = class {
631
154
  baseUrl,
632
155
  logger,
633
156
  accessTokenProvider,
634
- version,
635
- acsHelperOptions
157
+ version
636
158
  }) {
637
159
  // privately manage the active connected version and associated client codegen
638
160
  __publicField(this, "clients");
639
161
  __publicField(this, "clientVersion", "3.5");
640
162
  __publicField(this, "initialized", false);
641
163
  __publicField(this, "accessTokenProvider");
642
- __publicField(this, "acsHelper");
643
164
  __publicField(this, "logger");
644
165
  __publicField(this, "synchronizerId");
645
166
  __publicField(this, "baseUrl");
@@ -666,12 +187,6 @@ var LedgerClient = class {
666
187
  };
667
188
  this.clientVersion = version ?? this.clientVersion;
668
189
  this.baseUrl = baseUrl;
669
- this.acsHelper = new ACSHelper(
670
- this,
671
- logger,
672
- acsHelperOptions,
673
- SharedACSCache
674
- );
675
190
  }
676
191
  get currentClient() {
677
192
  return this.clients[this.clientVersion];
@@ -926,199 +441,6 @@ var LedgerClient = class {
926
441
  );
927
442
  return this.valueOrError(resp);
928
443
  }
929
- /*
930
- if limit is provided, this function performs a one-time query. Automatically splits into multiple `/v2/updates` calls with `continueUntilCompletion` on.
931
- if limit is omitted, results may be served from the ACS cache
932
- current cache design doesn't support limiting queries because updates/deltas for the acs at offset x will be incorrect
933
- TODO: expose query mode vs subscribe mode to call queryActiveContracts vs subscribeActiveContracts
934
- */
935
- async activeContracts(options) {
936
- const {
937
- offset,
938
- templateIds,
939
- parties,
940
- interfaceIds,
941
- limit,
942
- continueUntilCompletion
943
- } = options;
944
- if (continueUntilCompletion) {
945
- const filter2 = this.buildActiveContractFilter(options);
946
- return await this.fetchActiveContractsUntilComplete(
947
- filter2,
948
- limit ?? 200
949
- );
950
- }
951
- const hasLimit = typeof limit === "number";
952
- if (hasLimit) {
953
- const filter2 = this.buildActiveContractFilter(options);
954
- return await this.postWithRetry(
955
- "/v2/state/active-contracts",
956
- filter2,
957
- defaultRetryableOptions,
958
- { query: { limit: limit.toString() } }
959
- );
960
- }
961
- this.logger.debug(options, "options for active contracts");
962
- const hasParties = Array.isArray(parties) && parties.length > 0;
963
- if (templateIds?.length && hasParties) {
964
- return this.acsHelper.activeContractsForTemplates(
965
- offset,
966
- parties,
967
- templateIds
968
- );
969
- }
970
- if (interfaceIds?.length && hasParties) {
971
- return this.acsHelper.activeContractsForInterfaces(
972
- offset,
973
- parties,
974
- interfaceIds
975
- );
976
- }
977
- const filter = this.buildActiveContractFilter(options);
978
- this.logger.debug("falling back to post request");
979
- return await this.postWithRetry(
980
- "/v2/state/active-contracts",
981
- filter,
982
- defaultRetryableOptions
983
- );
984
- }
985
- /**
986
- * Fetches active contracts by splitting requests into multiple `/v2/updates` calls.
987
- * Should only be used when the number of contracts exceeds http-list-max-elements-limit (200 by default).
988
- * For limits at or below http-list-max-elements-limit, use a single `/v2/state/active-contracts` call instead.
989
- * @param activeContractsArgs The request parameters for active contracts query
990
- * @returns A promise that resolves to an array of active contract responses
991
- * @private
992
- */
993
- async fetchActiveContractsUntilComplete(activeContractsArgs, limit) {
994
- const ledgerEnd = await this.getWithRetry("/v2/state/ledger-end");
995
- const bodyRequest = {
996
- beginExclusive: 0,
997
- endInclusive: ledgerEnd.offset,
998
- verbose: false,
999
- updateFormat: {}
1000
- };
1001
- if (!activeContractsArgs.filter)
1002
- bodyRequest.filter = activeContractsArgs.filter;
1003
- let currentOffset = 0;
1004
- const allContractsData = /* @__PURE__ */ new Map();
1005
- const exercisedContracts = /* @__PURE__ */ new Set();
1006
- while (currentOffset < ledgerEnd.offset) {
1007
- bodyRequest.beginExclusive = currentOffset;
1008
- const results = (await this.postWithRetry(
1009
- "/v2/updates",
1010
- bodyRequest,
1011
- defaultRetryableOptions,
1012
- {
1013
- query: { limit: limit.toString() }
1014
- }
1015
- )).filter(({ update }) => update && "Transaction" in update).map(({ update }) => {
1016
- if (update && "Transaction" in update) {
1017
- return update.Transaction.value;
1018
- }
1019
- throw new Error("Expected Transaction update");
1020
- }).map((data) => {
1021
- const exercisedEvents = data.events?.filter(
1022
- (event) => !!event && "ExercisedEvent" in event
1023
- ).map(
1024
- (event) => event.ExercisedEvent
1025
- ).filter((event) => !!event).filter((event) => !!event.consuming);
1026
- const createdEvents = data.events?.filter((event) => !!event && "CreatedEvent" in event).map(
1027
- (event) => event.CreatedEvent
1028
- ).filter((event) => !!event).filter(
1029
- (event) => Object.keys(
1030
- activeContractsArgs.filter?.filtersByParty ?? {}
1031
- ).includes(
1032
- event.createArgument?.owner ?? ""
1033
- )
1034
- );
1035
- exercisedEvents?.forEach((event) => {
1036
- if (event.contractId)
1037
- exercisedContracts.add(event.contractId);
1038
- });
1039
- createdEvents?.forEach((event) => {
1040
- if (!event.contractId) return;
1041
- allContractsData.set(event.contractId, {
1042
- workflowId: data.workflowId,
1043
- contractEntry: {
1044
- JsActiveContract: {
1045
- synchronizerId: data.synchronizerId,
1046
- createdEvent: event,
1047
- reassignmentCounter: data.offset
1048
- }
1049
- }
1050
- });
1051
- });
1052
- currentOffset = Math.max(currentOffset, data.offset);
1053
- return true;
1054
- });
1055
- if (!results.length) currentOffset++;
1056
- }
1057
- exercisedContracts.forEach((cid) => {
1058
- allContractsData.delete(cid);
1059
- });
1060
- return Array.from(allContractsData.values());
1061
- }
1062
- buildActiveContractFilter(options) {
1063
- const filter = {
1064
- eventFormat: {
1065
- filtersByParty: {},
1066
- verbose: false
1067
- },
1068
- activeAtOffset: options?.offset
1069
- };
1070
- const buildTemplateFilter = (templateIds) => {
1071
- if (!templateIds) return [];
1072
- return [
1073
- {
1074
- identifierFilter: {
1075
- TemplateFilter: {
1076
- value: {
1077
- templateId: templateIds[0],
1078
- includeCreatedEventBlob: true
1079
- //TODO: figure out if this should be configurable
1080
- }
1081
- }
1082
- }
1083
- }
1084
- ];
1085
- };
1086
- const buildInterfaceFilter = (interfaceIds) => {
1087
- if (!interfaceIds) return [];
1088
- return [
1089
- {
1090
- identifierFilter: {
1091
- InterfaceFilter: {
1092
- value: {
1093
- interfaceId: interfaceIds[0],
1094
- includeCreatedEventBlob: true,
1095
- //TODO: figure out if this should be configurable
1096
- includeInterfaceView: true
1097
- }
1098
- }
1099
- }
1100
- }
1101
- ];
1102
- };
1103
- this.logger.info(options, "active contract query options");
1104
- if (options?.filterByParty && options.parties && options.parties.length > 0) {
1105
- const cumulativeFilter = options?.templateIds && !options?.interfaceIds ? buildTemplateFilter(options.templateIds) : options?.interfaceIds && !options?.templateIds ? buildInterfaceFilter(options.interfaceIds) : [];
1106
- for (const party of options.parties) {
1107
- filter.filter.filtersByParty[party] = {
1108
- cumulative: cumulativeFilter
1109
- };
1110
- }
1111
- } else if (options?.templateIds) {
1112
- filter.filter.filtersForAnyParty = {
1113
- cumulative: buildTemplateFilter(options.templateIds)
1114
- };
1115
- } else if (options?.interfaceIds) {
1116
- filter.filter.filtersForAnyParty = {
1117
- cumulative: buildInterfaceFilter(options.templateIds)
1118
- };
1119
- }
1120
- return filter;
1121
- }
1122
444
  // Retrieve an (arbitrary) synchronizer id from the validator.
1123
445
  // This synchronizer id is cached for the remainder of this object's life.
1124
446
  async getSynchronizerId() {
@@ -1175,9 +497,6 @@ var LedgerClient = class {
1175
497
  throw asJsCantonError(e);
1176
498
  });
1177
499
  }
1178
- getCacheStats() {
1179
- return this.acsHelper.getCacheStats();
1180
- }
1181
500
  async patch(path, body, params, additionalOptions) {
1182
501
  const options = { body, params, ...additionalOptions };
1183
502
  const resp = await this.currentClient.PATCH(path, options);
@@ -1203,49 +522,7 @@ var LedgerClient = class {
1203
522
  }
1204
523
  };
1205
524
 
1206
- // src/acs/ws-support.ts
1207
- var INITIAL_BACKOFF_MS = 1e3;
1208
- var MAX_BACKOFF_MS = 10 * 60 * 1e3;
1209
- var WSSupportWithBackOffSwitch = class {
1210
- constructor(extractProtocols, baseUrl) {
1211
- this.extractProtocols = extractProtocols;
1212
- this.baseUrl = baseUrl;
1213
- __publicField(this, "backOffUntil", null);
1214
- __publicField(this, "backOffDurationMs", INITIAL_BACKOFF_MS);
1215
- }
1216
- enabled() {
1217
- if (this.backOffUntil === null) {
1218
- return true;
1219
- }
1220
- const now = Date.now();
1221
- if (now >= this.backOffUntil) {
1222
- this.backOffUntil = null;
1223
- return true;
1224
- }
1225
- return false;
1226
- }
1227
- reportError(error) {
1228
- console.error("WebSocket error reported:", error);
1229
- const now = Date.now();
1230
- if (this.backOffUntil !== null && now - this.backOffUntil < 500) {
1231
- return;
1232
- }
1233
- this.backOffUntil = Date.now() + this.backOffDurationMs;
1234
- this.backOffDurationMs = Math.min(
1235
- this.backOffDurationMs * 1.6,
1236
- MAX_BACKOFF_MS
1237
- );
1238
- }
1239
- reportSuccess() {
1240
- this.backOffUntil = null;
1241
- this.backOffDurationMs = INITIAL_BACKOFF_MS;
1242
- }
1243
- };
1244
-
1245
- exports.ACSContainer = ACSContainer;
1246
- exports.ACS_UPDATE_CONFIG = ACS_UPDATE_CONFIG;
1247
525
  exports.LedgerClient = LedgerClient;
1248
- exports.WSSupportWithBackOffSwitch = WSSupportWithBackOffSwitch;
1249
526
  exports.asJsCantonError = asJsCantonError;
1250
527
  exports.awaitCompletion = awaitCompletion;
1251
528
  exports.defaultRetryableOptions = defaultRetryableOptions;