@canton-network/core-ledger-client 0.16.0 → 0.18.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
@@ -340,27 +340,6 @@ var AllKnownMetaKeys = [
340
340
  ReasonMetaKey,
341
341
  BurnedMetaKey
342
342
  ];
343
- function TransactionFilterBySetup(interfaceNames, options = { includeWildcard: false, isMasterUser: false }) {
344
- const interfaceArrayed = Array.isArray(interfaceNames) ? interfaceNames : [interfaceNames];
345
- if (options.isMasterUser)
346
- return {
347
- filtersByParty: {},
348
- filtersForAnyParty: filtersForAnyParty(
349
- interfaceArrayed,
350
- options.includeWildcard ?? false
351
- ) ?? {}
352
- };
353
- else if (!options.partyId || options.partyId === void 0)
354
- throw new Error("Party must be provided for non-master users");
355
- else
356
- return {
357
- filtersByParty: filtersByParty(
358
- options.partyId,
359
- interfaceArrayed,
360
- options.includeWildcard ?? false
361
- ) ?? {}
362
- };
363
- }
364
343
  function EventFilterBySetup(interfaceNames, options = { includeWildcard: false, isMasterUser: false }) {
365
344
  const interfaceArrayed = Array.isArray(interfaceNames) ? interfaceNames : [interfaceNames];
366
345
  if (options.isMasterUser)
@@ -695,15 +674,15 @@ var renderTransactionEvent = (e) => {
695
674
  );
696
675
  return {
697
676
  ...e,
698
- lockedHoldingsChange: lockedHoldingsChange ? { ...lockedHoldingsChange } : void 0,
699
- unlockedHoldingsChange: unlockedHoldingsChange ? { ...unlockedHoldingsChange } : void 0,
700
- lockedHoldingsChangeSummary: lockedHoldingsChangeSummary ? { ...lockedHoldingsChangeSummary } : void 0,
701
- unlockedHoldingsChangeSummary: unlockedHoldingsChangeSummary ? { ...unlockedHoldingsChangeSummary } : void 0
677
+ lockedHoldingsChange,
678
+ unlockedHoldingsChange,
679
+ lockedHoldingsChangeSummary,
680
+ unlockedHoldingsChangeSummary
702
681
  };
703
682
  };
704
683
  var renderHoldingsChangeSummary = (s) => {
705
684
  if (s.numInputs === 0 && s.numOutputs === 0 && s.inputAmount === "0" && s.outputAmount === "0" && s.amountChange === "0") {
706
- return void 0;
685
+ return null;
707
686
  }
708
687
  return {
709
688
  ...s.numInputs !== 0 && { numInputs: s.numInputs },
@@ -715,13 +694,37 @@ var renderHoldingsChangeSummary = (s) => {
715
694
  };
716
695
  var renderHoldingsChange = (c) => {
717
696
  if (c.creates.length === 0 && c.archives.length === 0) {
718
- return void 0;
697
+ return null;
719
698
  }
720
699
  return {
721
700
  ...c.creates.length !== 0 && { creates: c.creates },
722
701
  ...c.archives.length !== 0 && { archives: c.archives }
723
702
  };
724
703
  };
704
+ function currentStatusFromChoiceOrResult(choice, resultTag) {
705
+ if (resultTag === "TransferInstructionResult_Failed") return "Failed";
706
+ if (resultTag === "TransferInstructionResult_Completed") return "Completed";
707
+ switch (choice) {
708
+ case "TransferInstruction_Reject":
709
+ return "Rejected";
710
+ case "TransferInstruction_Withdraw":
711
+ return "Withdrawn";
712
+ case "TransferInstruction_Accept":
713
+ case "TransferInstruction_Update":
714
+ return "Pending";
715
+ default:
716
+ return "Pending";
717
+ }
718
+ }
719
+ function getCorrelationIdFromTransferInstruction(currentInstructionCid, originalInstructionCid) {
720
+ return originalInstructionCid ?? currentInstructionCid;
721
+ }
722
+ function getPendingTransferInstructionCid(exercisedEvent) {
723
+ const output = exercisedEvent.exerciseResult?.output;
724
+ if (output?.tag !== "TransferInstructionResult_Pending") return void 0;
725
+ const cid = output.value?.transferInstructionCid;
726
+ return cid ?? void 0;
727
+ }
725
728
  var TransactionParser = class {
726
729
  constructor(transaction, ledgerClient, partyId, isMasterUser) {
727
730
  __publicField(this, "ledgerClient");
@@ -866,9 +869,24 @@ var TransactionParser = class {
866
869
  ].some((stakeholder) => stakeholder === this.partyId)) {
867
870
  result = null;
868
871
  } else {
872
+ const multiStepCorrelationId = getCorrelationIdFromTransferInstruction(
873
+ originalCreate.contractId,
874
+ transferInstructionView.originalInstructionCid ?? null
875
+ );
869
876
  result = {
870
877
  payload: transferInstructionView,
871
- transferInstruction: transferInstructionView,
878
+ transferInstruction: {
879
+ originalInstructionCid: transferInstructionView.originalInstructionCid,
880
+ transfer: transferInstructionView.transfer,
881
+ meta: transferInstructionView.meta,
882
+ status: {
883
+ before: transferInstructionView.status,
884
+ // raw DAML pending sub-state
885
+ current: { tag: "Pending", value: {} }
886
+ // normalized
887
+ },
888
+ multiStepCorrelationId
889
+ },
872
890
  unlockedHoldingsChange: { creates: [], archives: [] },
873
891
  lockedHoldingsChange: { creates: [], archives: [] },
874
892
  unlockedHoldingsChangeSummary: EmptyHoldingsChangeSummary,
@@ -1002,6 +1020,12 @@ var TransactionParser = class {
1002
1020
  );
1003
1021
  return null;
1004
1022
  }
1023
+ const resultTag = exercisedEvent.exerciseResult?.output?.tag || void 0;
1024
+ const pendingCid = getPendingTransferInstructionCid(exercisedEvent);
1025
+ const currentTag = currentStatusFromChoiceOrResult(
1026
+ exercisedEvent.choice,
1027
+ resultTag
1028
+ );
1005
1029
  const children = await this.getChildren(exercisedEvent);
1006
1030
  const receiverAmounts = /* @__PURE__ */ new Map();
1007
1031
  children.creates.filter((h) => h.owner !== sender).forEach(
@@ -1045,13 +1069,25 @@ var TransactionParser = class {
1045
1069
  meta
1046
1070
  };
1047
1071
  }
1072
+ if (transferInstructions) {
1073
+ transferInstructions.status.current = transferInstructions.status.current || { tag: currentTag, value: {} };
1074
+ return {
1075
+ label,
1076
+ children,
1077
+ transferInstruction: transferInstructions
1078
+ };
1079
+ }
1048
1080
  const transferInstruction = {
1049
1081
  originalInstructionCid: null,
1050
- transfer: choiceArgumentTransfer,
1082
+ ...choiceArgumentTransfer !== void 0 && {
1083
+ transfer: choiceArgumentTransfer
1084
+ },
1051
1085
  status: {
1052
- before: null
1086
+ before: null,
1087
+ current: { tag: currentTag, value: {} }
1053
1088
  },
1054
- meta: null
1089
+ meta: null,
1090
+ ...pendingCid ? { multiStepCorrelationId: pendingCid } : {}
1055
1091
  };
1056
1092
  return {
1057
1093
  label,
@@ -1089,6 +1125,7 @@ var TransactionParser = class {
1089
1125
  };
1090
1126
  }
1091
1127
  async buildFromTransferInstructionExercise(exercisedEvent, tokenStandardChoice) {
1128
+ const instructionCid = exercisedEvent.contractId;
1092
1129
  const transferInstructionEvents = await this.getEventsForArchive(exercisedEvent);
1093
1130
  if (!transferInstructionEvents) {
1094
1131
  return null;
@@ -1097,15 +1134,26 @@ var TransactionParser = class {
1097
1134
  transferInstructionEvents.created.createdEvent,
1098
1135
  coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID
1099
1136
  ).viewValue;
1137
+ const multiStepCorrelationId = getCorrelationIdFromTransferInstruction(
1138
+ instructionCid,
1139
+ transferInstructionView.originalInstructionCid ?? null
1140
+ );
1141
+ const resultTag = exercisedEvent.exerciseResult?.output?.tag || void 0;
1142
+ const currentTag = currentStatusFromChoiceOrResult(
1143
+ exercisedEvent.choice,
1144
+ resultTag
1145
+ );
1100
1146
  const transferInstruction = {
1101
1147
  originalInstructionCid: transferInstructionView.originalInstructionCid,
1148
+ multiStepCorrelationId,
1102
1149
  transfer: transferInstructionView.transfer,
1103
1150
  meta: transferInstructionView.meta,
1104
1151
  status: {
1105
- before: transferInstructionView.status
1152
+ before: transferInstructionView.status,
1153
+ current: { tag: currentTag, value: {} }
1106
1154
  }
1107
1155
  };
1108
- const exerciseResultOutputTag = exercisedEvent.exerciseResult.output.tag;
1156
+ const exerciseResultOutputTag = resultTag;
1109
1157
  let result = null;
1110
1158
  switch (exerciseResultOutputTag) {
1111
1159
  case "TransferInstructionResult_Failed":
@@ -1350,7 +1398,7 @@ function holdingChangesNonEmpty(event) {
1350
1398
  var MEMO_KEY = "splice.lfdecentralizedtrust.org/reason";
1351
1399
  var REQUESTED_AT_SKEW_MS = 6e4;
1352
1400
  var EMPTY_META = { values: {} };
1353
- var CoreService = class {
1401
+ var CoreService = class _CoreService {
1354
1402
  constructor(ledgerClient, scanProxyClient, logger, accessTokenProvider, isMasterUser, isAdmin = false, accessToken = "") {
1355
1403
  this.ledgerClient = ledgerClient;
1356
1404
  this.scanProxyClient = scanProxyClient;
@@ -1369,7 +1417,7 @@ var CoreService = class {
1369
1417
  this.accessTokenProvider
1370
1418
  );
1371
1419
  }
1372
- async getInputHoldingsCids(sender, inputUtxos) {
1420
+ async getInputHoldingsCids(sender, inputUtxos, amount) {
1373
1421
  const now = /* @__PURE__ */ new Date();
1374
1422
  if (inputUtxos && inputUtxos.length > 0) {
1375
1423
  return inputUtxos;
@@ -1383,35 +1431,77 @@ var CoreService = class {
1383
1431
  "Sender has no holdings, so transfer can't be executed."
1384
1432
  );
1385
1433
  }
1386
- return senderHoldings.filter((utxo) => {
1434
+ const unlockedSenderHoldings = senderHoldings.filter((utxo) => {
1387
1435
  const lock = utxo.interfaceViewValue.lock;
1388
1436
  if (!lock) return true;
1389
1437
  const expiresAt = lock.expiresAt;
1390
1438
  if (!expiresAt) return false;
1391
1439
  const expiresAtDate = new Date(expiresAt);
1392
1440
  return expiresAtDate <= now;
1393
- }).map((h) => h.contractId);
1441
+ });
1442
+ if (unlockedSenderHoldings.length > 100) {
1443
+ this.logger.warn(`Sender has more than 100 unlocked utxos.`);
1444
+ }
1445
+ if (amount) {
1446
+ return _CoreService.getInputHoldingsCidsForAmount(
1447
+ amount,
1448
+ unlockedSenderHoldings
1449
+ );
1450
+ } else {
1451
+ return unlockedSenderHoldings.map((h) => h.contractId);
1452
+ }
1453
+ }
1454
+ static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
1455
+ const exactAmount = unlockedSenderHoldings.find(
1456
+ (holding) => parseFloat(holding.interfaceViewValue.amount) === amount
1457
+ );
1458
+ if (exactAmount) {
1459
+ return [exactAmount.contractId];
1460
+ }
1461
+ const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted(
1462
+ (a, b) => parseFloat(a.interfaceViewValue.amount) - parseFloat(b.interfaceViewValue.amount)
1463
+ );
1464
+ const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
1465
+ if (!largestHoldingAmount) {
1466
+ throw new Error(`Sender doesn't have any unlocked holdings`);
1467
+ }
1468
+ let currentSum = parseFloat(
1469
+ largestHoldingAmount.interfaceViewValue.amount
1470
+ );
1471
+ const cIds = [largestHoldingAmount.contractId];
1472
+ for (const h of sortedUnlockedSenderHoldings) {
1473
+ if (currentSum >= amount) {
1474
+ break;
1475
+ }
1476
+ const currentHoldingAmount = parseFloat(h.interfaceViewValue.amount);
1477
+ currentSum += currentHoldingAmount;
1478
+ cIds.push(h.contractId);
1479
+ }
1480
+ if (currentSum < amount) {
1481
+ throw new Error(
1482
+ `Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount - currentSum}`
1483
+ );
1484
+ }
1485
+ if (cIds.length > 100) {
1486
+ throw new Error(
1487
+ `Exceeded the maximum of 100 utxos in 1 transaction`
1488
+ );
1489
+ }
1490
+ return cIds;
1394
1491
  }
1395
1492
  async listContractsByInterface(interfaceId, partyId, limit) {
1396
1493
  try {
1397
1494
  const ledgerEnd = await this.ledgerClient.getWithRetry(
1398
1495
  "/v2/state/ledger-end"
1399
1496
  );
1400
- const acsResponses = await this.ledgerClient.postWithRetry(
1401
- "/v2/state/active-contracts",
1402
- {
1403
- filter: TransactionFilterBySetup(interfaceId, {
1404
- isMasterUser: this.isMasterUser,
1405
- partyId
1406
- }),
1407
- verbose: false,
1408
- activeAtOffset: ledgerEnd.offset
1409
- },
1410
- defaultRetryableOptions,
1411
- {
1412
- query: limit ? { limit: limit.toString() } : {}
1413
- }
1414
- );
1497
+ const options = {
1498
+ offset: ledgerEnd.offset,
1499
+ interfaceIds: [interfaceId],
1500
+ parties: [partyId],
1501
+ filterByParty: true,
1502
+ limit: limit ?? 100
1503
+ };
1504
+ const acsResponses = await this.ledgerClient.activeContracts(options);
1415
1505
  const isActiveContractEntry = (acsResponse) => !!acsResponse.contractEntry.JsActiveContract?.createdEvent;
1416
1506
  const activeContractEntries = acsResponses.filter(
1417
1507
  isActiveContractEntry
@@ -1493,22 +1583,6 @@ var CoreService = class {
1493
1583
  ).viewValue
1494
1584
  };
1495
1585
  }
1496
- async getActiveOpenMiningRound() {
1497
- const openMiningRounds = await this.scanProxyClient.getOpenMiningRounds();
1498
- if (!(Array.isArray(openMiningRounds) && openMiningRounds.length)) {
1499
- throw new Error("OpenMiningRound contract not found");
1500
- }
1501
- const nowForOpenMiningRounds = Date.now();
1502
- const latestOpenMiningRound = openMiningRounds.findLast(
1503
- (openMiningRound) => {
1504
- const { opensAt, targetClosesAt } = openMiningRound.payload;
1505
- const opensAtMs = Number(new Date(opensAt));
1506
- const targetClosesAtMs = Number(new Date(targetClosesAt));
1507
- return opensAtMs <= nowForOpenMiningRounds && targetClosesAtMs > nowForOpenMiningRounds;
1508
- }
1509
- );
1510
- return latestOpenMiningRound ?? null;
1511
- }
1512
1586
  };
1513
1587
  var AllocationService = class {
1514
1588
  constructor(core, logger) {
@@ -1764,7 +1838,8 @@ var TransferService = class {
1764
1838
  async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta) {
1765
1839
  const inputHoldingCids = await this.core.getInputHoldingsCids(
1766
1840
  sender,
1767
- inputUtxos
1841
+ inputUtxos,
1842
+ parseFloat(amount)
1768
1843
  );
1769
1844
  return {
1770
1845
  expectedAdmin: instrumentAdmin,
@@ -2148,11 +2223,77 @@ var TokenStandardService = class {
2148
2223
  );
2149
2224
  }
2150
2225
  }
2226
+ async buyMemberTraffic(dso, provider, trafficAmount, synchronizerId, memberId, migrationId, inputUtxos) {
2227
+ const amuletRules = await this.scanProxyClient.getAmuletRules();
2228
+ const activeRound = await this.scanProxyClient.getActiveOpenMiningRound();
2229
+ const inputHoldings = await this.core.getInputHoldingsCids(
2230
+ provider,
2231
+ inputUtxos,
2232
+ trafficAmount
2233
+ );
2234
+ if (!amuletRules) {
2235
+ throw new Error("AmuletRules contract not found");
2236
+ }
2237
+ if (!activeRound) {
2238
+ throw new Error(
2239
+ "OpenMiningRound active at current moment not found"
2240
+ );
2241
+ }
2242
+ const disclosed = [
2243
+ {
2244
+ templateId: amuletRules.template_id,
2245
+ contractId: amuletRules.contract_id,
2246
+ createdEventBlob: amuletRules.created_event_blob,
2247
+ synchronizerId
2248
+ },
2249
+ {
2250
+ templateId: activeRound.template_id,
2251
+ contractId: activeRound.contract_id,
2252
+ createdEventBlob: activeRound.created_event_blob,
2253
+ synchronizerId
2254
+ }
2255
+ ];
2256
+ const context = {
2257
+ openMiningRound: activeRound.contract_id,
2258
+ issuingMiningRounds: [],
2259
+ validatorRights: [],
2260
+ featuredAppRight: null
2261
+ };
2262
+ const choiceArgs = {
2263
+ context,
2264
+ inputs: inputHoldings.map((cid) => ({
2265
+ tag: "InputAmulet",
2266
+ value: cid
2267
+ })),
2268
+ provider,
2269
+ memberId,
2270
+ synchronizerId,
2271
+ migrationId,
2272
+ trafficAmount,
2273
+ expectedDso: dso
2274
+ };
2275
+ const exercise = {
2276
+ templateId: "#splice-amulet:Splice.AmuletRules:AmuletRules",
2277
+ contractId: amuletRules.contract_id,
2278
+ choice: "AmuletRules_BuyMemberTraffic",
2279
+ choiceArgument: choiceArgs
2280
+ };
2281
+ return [exercise, disclosed];
2282
+ }
2151
2283
  async getInstrumentAdmin(registryUrl) {
2152
2284
  const client = this.core.getTokenStandardClient(registryUrl);
2153
2285
  const info = await client.get("/registry/metadata/v1/info");
2154
2286
  return info.adminId;
2155
2287
  }
2288
+ async listInstruments(registryUrl, pageSize, pageToken) {
2289
+ const client = this.core.getTokenStandardClient(registryUrl);
2290
+ return client.get("/registry/metadata/v1/instruments", {
2291
+ query: {
2292
+ ...pageSize && { pageSize },
2293
+ ...pageToken && { pageToken }
2294
+ }
2295
+ });
2296
+ }
2156
2297
  // <T> is shape of viewValue related to queried interface.
2157
2298
  // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
2158
2299
  async listContractsByInterface(interfaceId, partyId, limit) {
@@ -2295,7 +2436,7 @@ var TokenStandardService = class {
2295
2436
  if (!amuletRules) {
2296
2437
  throw new Error("AmuletRules contract not found");
2297
2438
  }
2298
- const latestOpenMiningRound = await this.core.getActiveOpenMiningRound();
2439
+ const latestOpenMiningRound = await this.scanProxyClient.getActiveOpenMiningRound();
2299
2440
  if (!latestOpenMiningRound) {
2300
2441
  throw new Error(
2301
2442
  "OpenMiningRound active at current moment not found"
@@ -2346,7 +2487,7 @@ var TokenStandardService = class {
2346
2487
  }
2347
2488
  async renewTransferPreapproval(contractId, templateId, provider, synchronizerId, newExpiresAt, inputUtxos) {
2348
2489
  const amuletRules = await this.scanProxyClient.getAmuletRules();
2349
- const activeRound = await this.core.getActiveOpenMiningRound();
2490
+ const activeRound = await this.scanProxyClient.getActiveOpenMiningRound();
2350
2491
  if (!amuletRules) {
2351
2492
  throw new Error("AmuletRules contract not found");
2352
2493
  }
@@ -2444,13 +2585,15 @@ if (typeof window !== "undefined") {
2444
2585
  window["ACS_UPDATE_CONFIG"] = ACS_UPDATE_CONFIG;
2445
2586
  }
2446
2587
  var ACSContainer = class _ACSContainer {
2447
- constructor(orginalContainer = null) {
2588
+ constructor(orginalContainer = null, settings = { includeCreatedEventBlob: true }) {
2448
2589
  __publicField(this, "acsSet", null);
2590
+ __publicField(this, "settings");
2449
2591
  this.acsSet = orginalContainer ? orginalContainer.acsSet : null;
2592
+ this.settings = settings;
2450
2593
  }
2451
2594
  async update(offset, key, api, wsSupport) {
2452
2595
  if (this.acsSet === null) {
2453
- const acs = await _ACSContainer.readACS(offset, key, api, wsSupport);
2596
+ const acs = await this.readACS(offset, key, api, wsSupport);
2454
2597
  this.acsSet = acs;
2455
2598
  return _ACSContainer.calculateAt(acs, offset);
2456
2599
  }
@@ -2464,7 +2607,7 @@ var ACSContainer = class _ACSContainer {
2464
2607
  const updates = await _ACSContainer.updateContracts(
2465
2608
  this.acsSet.lastUpdateOffset,
2466
2609
  offset,
2467
- _ACSContainer.createEventFormat(key),
2610
+ this.createEventFormat(key),
2468
2611
  api
2469
2612
  );
2470
2613
  const [newEvents, newOffset] = _ACSContainer.extractEvents(
@@ -2615,19 +2758,17 @@ var ACSContainer = class _ACSContainer {
2615
2758
  }
2616
2759
  return acs;
2617
2760
  }
2618
- static async readACS(offset, key, api, wsSupport) {
2761
+ async readACS(offset, key, api, wsSupport) {
2619
2762
  if (wsSupport && wsSupport.enabled()) {
2620
- return _ACSContainer.readACSUsingWs(offset, key, wsSupport).catch(
2621
- () => {
2622
- console.log("Falling back to HTTP for ACS read");
2623
- return _ACSContainer.readHttpACS(offset, key, api);
2624
- }
2625
- );
2763
+ return this.readACSUsingWs(offset, key, wsSupport).catch(() => {
2764
+ console.log("Falling back to HTTP for ACS read");
2765
+ return this.readHttpACS(offset, key, api);
2766
+ });
2626
2767
  }
2627
- return _ACSContainer.readHttpACS(offset, key, api);
2768
+ return this.readHttpACS(offset, key, api);
2628
2769
  }
2629
- static async readHttpACS(offset, key, api) {
2630
- const format = _ACSContainer.createEventFormat(key);
2770
+ async readHttpACS(offset, key, api) {
2771
+ const format = this.createEventFormat(key);
2631
2772
  const acs = await api.postWithRetry("/v2/state/active-contracts", {
2632
2773
  activeAtOffset: offset,
2633
2774
  verbose: false,
@@ -2640,9 +2781,9 @@ var ACSContainer = class _ACSContainer {
2640
2781
  updates: []
2641
2782
  };
2642
2783
  }
2643
- static readACSUsingWs(offset, key, wsSupport) {
2784
+ readACSUsingWs(offset, key, wsSupport) {
2644
2785
  const wsACSURL = `${wsSupport.baseUrl}/v2/state/active-contracts`;
2645
- const format = _ACSContainer.createEventFormat(key);
2786
+ const format = this.createEventFormat(key);
2646
2787
  const request = {
2647
2788
  activeAtOffset: offset,
2648
2789
  verbose: false,
@@ -2695,7 +2836,7 @@ var ACSContainer = class _ACSContainer {
2695
2836
  };
2696
2837
  });
2697
2838
  }
2698
- static createInterfaceFilter(interfaceId) {
2839
+ createInterfaceFilter(interfaceId) {
2699
2840
  return {
2700
2841
  cumulative: [
2701
2842
  {
@@ -2704,7 +2845,7 @@ var ACSContainer = class _ACSContainer {
2704
2845
  value: {
2705
2846
  interfaceId,
2706
2847
  includeInterfaceView: true,
2707
- includeCreatedEventBlob: false
2848
+ includeCreatedEventBlob: this.settings.includeCreatedEventBlob
2708
2849
  }
2709
2850
  }
2710
2851
  }
@@ -2712,7 +2853,7 @@ var ACSContainer = class _ACSContainer {
2712
2853
  ]
2713
2854
  };
2714
2855
  }
2715
- static createTemplateFilter(templateId) {
2856
+ createTemplateFilter(templateId) {
2716
2857
  return {
2717
2858
  cumulative: [
2718
2859
  {
@@ -2720,7 +2861,7 @@ var ACSContainer = class _ACSContainer {
2720
2861
  TemplateFilter: {
2721
2862
  value: {
2722
2863
  templateId,
2723
- includeCreatedEventBlob: false
2864
+ includeCreatedEventBlob: this.settings.includeCreatedEventBlob
2724
2865
  }
2725
2866
  }
2726
2867
  }
@@ -2728,8 +2869,8 @@ var ACSContainer = class _ACSContainer {
2728
2869
  ]
2729
2870
  };
2730
2871
  }
2731
- static createEventFormat(key) {
2732
- const cumulativeFilter = key.templateId ? _ACSContainer.createTemplateFilter(key.templateId) : _ACSContainer.createInterfaceFilter(key.interfaceId ?? "");
2872
+ createEventFormat(key) {
2873
+ const cumulativeFilter = key.templateId ? this.createTemplateFilter(key.templateId) : this.createInterfaceFilter(key.interfaceId ?? "");
2733
2874
  const baseFormat = {
2734
2875
  filtersByParty: {},
2735
2876
  verbose: false
@@ -2748,22 +2889,34 @@ var ACSContainer = class _ACSContainer {
2748
2889
  };
2749
2890
  }
2750
2891
  };
2892
+ var DEFAULT_MAX_CACHE_SIZE = 100;
2893
+ var DEFAULT_ENTRY_EXPIRATION_TIME = 10 * 60 * 1e3;
2894
+ var SharedACSCache = new typescriptLruCache.LRUCache({
2895
+ maxSize: DEFAULT_MAX_CACHE_SIZE,
2896
+ entryExpirationTimeInMS: DEFAULT_ENTRY_EXPIRATION_TIME,
2897
+ onEntryEvicted: (entry) => {
2898
+ console.debug(`${entry} has expired`);
2899
+ SharedACSCacheStats.evictions++;
2900
+ }
2901
+ });
2902
+ var SharedACSCacheStats = {
2903
+ hits: 0,
2904
+ misses: 0,
2905
+ evictions: 0,
2906
+ totalLookupTime: 0,
2907
+ totalCacheServeTime: 0
2908
+ };
2751
2909
 
2752
2910
  // src/acs/acs-helper.ts
2753
- var DEFAULT_MAX_CACHE_SIZE = 50;
2754
- var DEFAULT_ENTRY_EXPIRATION_TIME = 10 * 60 * 1e3;
2755
2911
  var ACSHelper = class _ACSHelper {
2756
- constructor(apiInstance, _logger, options) {
2912
+ constructor(apiInstance, _logger, options, sharedCache) {
2757
2913
  __publicField(this, "contractsSet");
2758
2914
  __publicField(this, "apiInstance");
2759
2915
  __publicField(this, "wsSupport");
2760
2916
  __publicField(this, "logger");
2761
- __publicField(this, "hits", 0);
2762
- __publicField(this, "misses", 0);
2763
- __publicField(this, "evictions", 0);
2764
- __publicField(this, "totalLookuptime", 0);
2917
+ __publicField(this, "includeCreatedEventBlob");
2765
2918
  __publicField(this, "totalCacheServeTime", 0);
2766
- this.contractsSet = new typescriptLruCache.LRUCache({
2919
+ this.contractsSet = sharedCache ?? new typescriptLruCache.LRUCache({
2767
2920
  maxSize: options?.maxCacheSize ?? DEFAULT_MAX_CACHE_SIZE,
2768
2921
  entryExpirationTimeInMS: options?.entryExpirationTime ?? DEFAULT_ENTRY_EXPIRATION_TIME,
2769
2922
  // 10 minutes
@@ -2771,22 +2924,23 @@ var ACSHelper = class _ACSHelper {
2771
2924
  this.logger.debug(
2772
2925
  `entry ${entry.key} isExpired = ${entry.isExpired}. evicting entry.`
2773
2926
  );
2774
- this.evictions++;
2927
+ SharedACSCacheStats.evictions++;
2775
2928
  }
2776
2929
  });
2777
2930
  this.apiInstance = apiInstance;
2778
2931
  this.wsSupport = options?.wsSupport;
2779
2932
  this.logger = _logger.child({ component: "ACSHelper" });
2933
+ this.includeCreatedEventBlob = options?.includeCreatedEventBlob ?? true;
2780
2934
  }
2781
2935
  getCacheStats() {
2782
- const totalCalls = this.hits + this.misses;
2783
- const hitRate = totalCalls ? this.hits / totalCalls * 100 : 0;
2784
- const avgLookupTime = totalCalls > 0 ? this.totalLookuptime / totalCalls : 0;
2936
+ const totalCalls = SharedACSCacheStats.hits + SharedACSCacheStats.misses;
2937
+ const hitRate = totalCalls ? SharedACSCacheStats.hits / totalCalls * 100 : 0;
2938
+ const avgLookupTime = totalCalls > 0 ? SharedACSCacheStats.totalLookupTime / totalCalls : 0;
2785
2939
  return {
2786
2940
  totalCalls,
2787
- hits: this.hits,
2788
- misses: this.misses,
2789
- evictions: this.evictions,
2941
+ hits: SharedACSCacheStats.hits,
2942
+ misses: SharedACSCacheStats.misses,
2943
+ evictions: SharedACSCacheStats.evictions,
2790
2944
  cacheSize: this.contractsSet.size,
2791
2945
  hitRate: hitRate.toFixed(2) + "%",
2792
2946
  averageLookupTime: avgLookupTime.toFixed(3) + " ms",
@@ -2796,23 +2950,25 @@ var ACSHelper = class _ACSHelper {
2796
2950
  static createKey(party, templateId, interfaceId) {
2797
2951
  return { party, templateId, interfaceId };
2798
2952
  }
2799
- static keyToString(key) {
2800
- return `${key.party ? key.party : "ANY"}_T:${key.templateId ?? "()"}_I:${key.interfaceId ?? "()"}`;
2953
+ static keyToString(key, ledgerBaseUrl) {
2954
+ return `${ledgerBaseUrl}_${key.party ? key.party : "ANY"}_T:${key.templateId ?? "()"}_I:${key.interfaceId ?? "()"}`;
2801
2955
  }
2802
2956
  findACSContainer(key) {
2803
- const keyStr = _ACSHelper.keyToString(key);
2957
+ const keyStr = _ACSHelper.keyToString(key, this.apiInstance.baseUrl.href);
2804
2958
  const start = performance.now();
2805
2959
  const existing = this.contractsSet.get(keyStr);
2806
2960
  const end = performance.now();
2807
- this.totalLookuptime += end - start;
2961
+ SharedACSCacheStats.totalLookupTime += end - start;
2808
2962
  if (existing) {
2809
- this.hits++;
2963
+ SharedACSCacheStats.hits++;
2810
2964
  this.logger.debug("cache hit");
2811
2965
  return existing;
2812
2966
  }
2813
2967
  this.logger.debug("cache miss");
2814
- this.misses++;
2815
- const newContainer = new ACSContainer();
2968
+ SharedACSCacheStats.misses++;
2969
+ const newContainer = new ACSContainer(void 0, {
2970
+ includeCreatedEventBlob: this.includeCreatedEventBlob
2971
+ });
2816
2972
  this.contractsSet.set(keyStr, newContainer);
2817
2973
  return newContainer;
2818
2974
  }
@@ -2827,8 +2983,10 @@ var ACSHelper = class _ACSHelper {
2827
2983
  this.wsSupport
2828
2984
  );
2829
2985
  const end = performance.now();
2830
- if (this.contractsSet.has(_ACSHelper.keyToString(key))) {
2831
- this.totalCacheServeTime += end - start;
2986
+ if (this.contractsSet.has(
2987
+ _ACSHelper.keyToString(key, this.apiInstance.baseUrl.href)
2988
+ )) {
2989
+ SharedACSCacheStats.totalCacheServeTime += end - start;
2832
2990
  }
2833
2991
  return result;
2834
2992
  }
@@ -2843,8 +3001,10 @@ var ACSHelper = class _ACSHelper {
2843
3001
  this.wsSupport
2844
3002
  );
2845
3003
  const end = performance.now();
2846
- if (this.contractsSet.has(_ACSHelper.keyToString(key))) {
2847
- this.totalCacheServeTime += end - start;
3004
+ if (this.contractsSet.has(
3005
+ _ACSHelper.keyToString(key, this.apiInstance.baseUrl.href)
3006
+ )) {
3007
+ SharedACSCacheStats.totalCacheServeTime += end - start;
2848
3008
  }
2849
3009
  return result;
2850
3010
  }
@@ -2856,13 +3016,14 @@ var LedgerClient = class {
2856
3016
  constructor(baseUrl, _logger, isAdmin = false, accessToken, accessTokenProvider, version, acsHelperOptions) {
2857
3017
  // privately manage the active connected version and associated client codegen
2858
3018
  __publicField(this, "clients");
2859
- __publicField(this, "clientVersion", "3.3");
2860
- // default to 3.3 if not provided
3019
+ __publicField(this, "clientVersion", "3.4");
3020
+ // default to 3.4 if not provided
2861
3021
  __publicField(this, "currentClient");
2862
3022
  __publicField(this, "initialized", false);
2863
3023
  __publicField(this, "accessTokenProvider");
2864
3024
  __publicField(this, "acsHelper");
2865
3025
  __publicField(this, "logger");
3026
+ __publicField(this, "baseUrl");
2866
3027
  this.logger = _logger.child({ component: "LedgerClient" });
2867
3028
  this.accessTokenProvider = accessTokenProvider;
2868
3029
  this.clients = {
@@ -2899,7 +3060,13 @@ var LedgerClient = class {
2899
3060
  };
2900
3061
  this.clientVersion = version ?? this.clientVersion;
2901
3062
  this.currentClient = this.clients[this.clientVersion];
2902
- this.acsHelper = new ACSHelper(this, _logger, acsHelperOptions);
3063
+ this.baseUrl = baseUrl;
3064
+ this.acsHelper = new ACSHelper(
3065
+ this,
3066
+ _logger,
3067
+ acsHelperOptions,
3068
+ SharedACSCache
3069
+ );
2903
3070
  }
2904
3071
  async init() {
2905
3072
  if (!this.initialized) {
@@ -2907,6 +3074,7 @@ var LedgerClient = class {
2907
3074
  this.clientVersion = this.parseSupportedVersions(
2908
3075
  versionFromClient.data?.version
2909
3076
  );
3077
+ this.currentClient = this.clients[this.clientVersion];
2910
3078
  this.initialized = true;
2911
3079
  }
2912
3080
  }
@@ -3107,52 +3275,86 @@ var LedgerClient = class {
3107
3275
  /** TODO: simplify once 3.4 snapshot contains this endpoint */
3108
3276
  async allocateExternalParty(synchronizerId, onboardingTransactions, multiHashSignatures) {
3109
3277
  await this.init();
3110
- if (this.clientVersion !== "3.3") {
3111
- throw new Error(
3112
- "allocateExternalParty is only supported on 3.3 clients"
3113
- );
3278
+ if (this.clientVersion == "3.3") {
3279
+ const client = this.clients["3.3"];
3280
+ const resp = await client.POST("/v2/parties/external/allocate", {
3281
+ body: {
3282
+ synchronizer: synchronizerId,
3283
+ identityProviderId: "",
3284
+ onboardingTransactions,
3285
+ multiHashSignatures
3286
+ }
3287
+ });
3288
+ return this.valueOrError(resp);
3289
+ } else {
3290
+ const client = this.clients["3.4"];
3291
+ const resp = await client.POST("/v2/parties/external/allocate", {
3292
+ body: {
3293
+ synchronizer: synchronizerId,
3294
+ identityProviderId: "",
3295
+ onboardingTransactions,
3296
+ multiHashSignatures
3297
+ }
3298
+ });
3299
+ return this.valueOrError(resp);
3114
3300
  }
3115
- const client = this.clients["3.3"];
3116
- const resp = await client.POST("/v2/parties/external/allocate", {
3117
- body: {
3118
- synchronizer: synchronizerId,
3119
- identityProviderId: "",
3120
- onboardingTransactions,
3121
- multiHashSignatures
3122
- }
3123
- });
3124
- return this.valueOrError(resp);
3125
3301
  }
3126
3302
  /** TODO: simplify once 3.4 snapshot contains this endpoint */
3127
- async generateTopology(synchronizerId, publicKey, partyHint, localParticipantObservationOnly = false, confirmationThreshold = 1, otherConfirmingParticipantUids = []) {
3303
+ async generateTopology(synchronizerId, publicKey, partyHint, localParticipantObservationOnly = false, confirmationThreshold = 1, otherConfirmingParticipantUids = [], observingParticipantUids = []) {
3128
3304
  await this.init();
3129
- if (this.clientVersion !== "3.3") {
3130
- throw new Error(
3131
- "allocateExternalParty is only supported on 3.3 clients"
3305
+ if (this.clientVersion == "3.3") {
3306
+ const client = this.clients["3.3"];
3307
+ const body = {
3308
+ synchronizer: synchronizerId,
3309
+ partyHint,
3310
+ publicKey: {
3311
+ format: "CRYPTO_KEY_FORMAT_RAW",
3312
+ keyData: publicKey,
3313
+ keySpec: "SIGNING_KEY_SPEC_EC_CURVE25519"
3314
+ },
3315
+ localParticipantObservationOnly,
3316
+ confirmationThreshold,
3317
+ otherConfirmingParticipantUids,
3318
+ observingParticipantUids
3319
+ };
3320
+ this.logger.debug(body, "generateTopology request body");
3321
+ const resp = await client.POST(
3322
+ "/v2/parties/external/generate-topology",
3323
+ { body }
3132
3324
  );
3325
+ return this.valueOrError(resp);
3326
+ } else {
3327
+ const client = this.clients["3.4"];
3328
+ const body = {
3329
+ synchronizer: synchronizerId,
3330
+ partyHint,
3331
+ publicKey: {
3332
+ format: "CRYPTO_KEY_FORMAT_RAW",
3333
+ keyData: publicKey,
3334
+ keySpec: "SIGNING_KEY_SPEC_EC_CURVE25519"
3335
+ },
3336
+ localParticipantObservationOnly,
3337
+ confirmationThreshold,
3338
+ otherConfirmingParticipantUids,
3339
+ observingParticipantUids
3340
+ };
3341
+ this.logger.debug(body, "generateTopology request body");
3342
+ const resp = await client.POST(
3343
+ "/v2/parties/external/generate-topology",
3344
+ { body }
3345
+ );
3346
+ return this.valueOrError(resp);
3133
3347
  }
3134
- const client = this.clients["3.3"];
3135
- const body = {
3136
- synchronizer: synchronizerId,
3137
- partyHint,
3138
- publicKey: {
3139
- format: "CRYPTO_KEY_FORMAT_RAW",
3140
- keyData: publicKey,
3141
- keySpec: "SIGNING_KEY_SPEC_EC_CURVE25519"
3142
- },
3143
- localParticipantObservationOnly,
3144
- confirmationThreshold,
3145
- otherConfirmingParticipantUids
3146
- };
3147
- this.logger.debug(body, "generateTopology request body");
3148
- const resp = await client.POST(
3149
- "/v2/parties/external/generate-topology",
3150
- { body }
3151
- );
3152
- return this.valueOrError(resp);
3153
3348
  }
3154
3349
  async activeContracts(options) {
3155
- const { offset, templateIds, parties, filterByParty } = options;
3350
+ const {
3351
+ offset,
3352
+ templateIds,
3353
+ parties,
3354
+ filterByParty,
3355
+ interfaceIds,
3356
+ limit
3357
+ } = options;
3156
3358
  this.logger.debug(options, "options for active contracts");
3157
3359
  if (templateIds?.length === 1 && parties?.length === 1) {
3158
3360
  const party = parties[0];
@@ -3163,21 +3365,36 @@ var LedgerClient = class {
3163
3365
  templateId
3164
3366
  );
3165
3367
  }
3166
- if (filterByParty && !templateIds?.length && parties?.length === 1) {
3368
+ if (interfaceIds?.length === 1 && parties?.length === 1) {
3369
+ const party = parties[0];
3370
+ const interfaceId = interfaceIds[0];
3371
+ return this.acsHelper.activeContractsForInterface(
3372
+ offset,
3373
+ party,
3374
+ interfaceId
3375
+ );
3376
+ }
3377
+ if (filterByParty && !templateIds?.length && !interfaceIds?.length && parties?.length === 1) {
3167
3378
  const party = parties[0];
3168
3379
  const r = this.acsHelper.activeContractsForInterface(
3169
3380
  offset,
3170
3381
  party,
3171
3382
  ""
3172
3383
  );
3173
- this.logger.info(r);
3174
3384
  return r;
3175
3385
  }
3176
- const filter = this.buildActiveContractsFilter(options);
3386
+ const filter = this.buildActiveContractFilter(options);
3177
3387
  this.logger.debug("falling back to post request");
3178
- return await this.postWithRetry("/v2/state/active-contracts", filter);
3388
+ return await this.postWithRetry(
3389
+ "/v2/state/active-contracts",
3390
+ filter,
3391
+ defaultRetryableOptions,
3392
+ {
3393
+ query: limit ? { limit: limit.toString() } : {}
3394
+ }
3395
+ );
3179
3396
  }
3180
- buildActiveContractsFilter(options) {
3397
+ buildActiveContractFilter(options) {
3181
3398
  const filter = {
3182
3399
  filter: {
3183
3400
  filtersByParty: {}
@@ -3201,16 +3418,46 @@ var LedgerClient = class {
3201
3418
  }
3202
3419
  ];
3203
3420
  };
3421
+ const buildInterfaceFilter = (interfaceIds) => {
3422
+ if (!interfaceIds) return [];
3423
+ return [
3424
+ {
3425
+ identifierFilter: {
3426
+ InterfaceFilter: {
3427
+ value: {
3428
+ interfaceId: interfaceIds[0],
3429
+ includeCreatedEventBlob: true,
3430
+ //TODO: figure out if this should be configurable
3431
+ includeInterfaceView: true
3432
+ }
3433
+ }
3434
+ }
3435
+ }
3436
+ ];
3437
+ };
3438
+ this.logger.info(options, "active contract query options");
3204
3439
  if (options?.filterByParty && options.parties && options.parties.length > 0) {
3205
- for (const party of options.parties) {
3206
- filter.filter.filtersByParty[party] = {
3207
- cumulative: options.templateIds ? buildTemplateFilter(options.templateIds) : []
3208
- };
3440
+ if (options?.templateIds && !options?.interfaceIds) {
3441
+ for (const party of options.parties) {
3442
+ filter.filter.filtersByParty[party] = {
3443
+ cumulative: options.templateIds ? buildTemplateFilter(options.templateIds) : []
3444
+ };
3445
+ }
3446
+ } else if (options?.interfaceIds && !options?.templateIds) {
3447
+ for (const party of options.parties) {
3448
+ filter.filter.filtersByParty[party] = {
3449
+ cumulative: options.interfaceIds ? buildInterfaceFilter(options.interfaceIds) : []
3450
+ };
3451
+ }
3209
3452
  }
3210
3453
  } else if (options?.templateIds) {
3211
3454
  filter.filter.filtersForAnyParty = {
3212
3455
  cumulative: buildTemplateFilter(options.templateIds)
3213
3456
  };
3457
+ } else if (options?.interfaceIds) {
3458
+ filter.filter.filtersForAnyParty = {
3459
+ cumulative: buildInterfaceFilter(options.templateIds)
3460
+ };
3214
3461
  }
3215
3462
  return filter;
3216
3463
  }