@canton-network/core-tx-parser 1.15.0 → 1.16.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,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -20,12 +20,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- //#endregion
24
23
  let _canton_network_core_token_standard = require("@canton-network/core-token-standard");
25
24
  let _canton_network_core_ledger_client_types = require("@canton-network/core-ledger-client-types");
26
25
  let bignumber_js = require("bignumber.js");
27
26
  bignumber_js = __toESM(bignumber_js, 1);
28
- //#region src/constants.ts
27
+ let _canton_network_core_token_standard_v2 = require("@canton-network/core-token-standard-v2");
28
+ // src/constants.ts
29
29
  function splitInterfaceId(interfaceId) {
30
30
  const match = /^#?([^:]+):([^:]+):([^:]+)$/.exec(interfaceId);
31
31
  if (!match) return null;
@@ -61,8 +61,7 @@ const AllKnownMetaKeys = [
61
61
  ReasonMetaKey,
62
62
  BurnedMetaKey
63
63
  ];
64
- //#endregion
65
- //#region src/utils.ts
64
+ // src/utils.ts
66
65
  function hasInterface(interfaceId, event) {
67
66
  return (event.implementedInterfaces || []).some((id) => matchInterfaceIds(id, interfaceId));
68
67
  }
@@ -122,8 +121,7 @@ function getMetaKeyValue(key, meta) {
122
121
  function removeParsedMetaKeys(meta) {
123
122
  return { values: Object.fromEntries(Object.entries(meta?.values || {}).filter(([k]) => !AllKnownMetaKeys.includes(k))) };
124
123
  }
125
- //#endregion
126
- //#region src/types.ts
124
+ // src/types.ts
127
125
  const renderTransaction = (t) => {
128
126
  return {
129
127
  ...t,
@@ -163,8 +161,7 @@ const renderHoldingsChange = (c) => {
163
161
  ...c.archives.length !== 0 && { archives: c.archives }
164
162
  };
165
163
  };
166
- //#endregion
167
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/typeof.js
164
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
168
165
  function _typeof(o) {
169
166
  "@babel/helpers - typeof";
170
167
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -173,8 +170,7 @@ function _typeof(o) {
173
170
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
174
171
  }, _typeof(o);
175
172
  }
176
- //#endregion
177
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPrimitive.js
173
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPrimitive.js
178
174
  function toPrimitive(t, r) {
179
175
  if ("object" != _typeof(t) || !t) return t;
180
176
  var e = t[Symbol.toPrimitive];
@@ -185,14 +181,12 @@ function toPrimitive(t, r) {
185
181
  }
186
182
  return ("string" === r ? String : Number)(t);
187
183
  }
188
- //#endregion
189
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPropertyKey.js
184
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/toPropertyKey.js
190
185
  function toPropertyKey(t) {
191
186
  var i = toPrimitive(t, "string");
192
187
  return "symbol" == _typeof(i) ? i : i + "";
193
188
  }
194
- //#endregion
195
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/defineProperty.js
189
+ // \0@oxc-project+runtime@0.155.0/helpers/esm/defineProperty.js
196
190
  function _defineProperty(e, r, t) {
197
191
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
198
192
  value: t,
@@ -201,8 +195,7 @@ function _defineProperty(e, r, t) {
201
195
  writable: !0
202
196
  }) : e[r] = t, e;
203
197
  }
204
- //#endregion
205
- //#region src/instrumentmap.ts
198
+ // src/instrumentmap.ts
206
199
  /** InstrumentMap is a helper for when you want to group values by instrument. */
207
200
  var InstrumentMap = class {
208
201
  encodeKey(instrumentId) {
@@ -235,8 +228,132 @@ var InstrumentMap = class {
235
228
  for (const [key, value] of this.map.entries()) yield [this.decodeKey(key), value];
236
229
  }
237
230
  };
238
- //#endregion
239
- //#region src/parser.ts
231
+ // src/v2-events.ts
232
+ const MINT_ACCOUNT_ID = "cip-112/mint";
233
+ const BURN_ACCOUNT_ID = "cip-112/burn";
234
+ function extractHoldingsChange(exercised) {
235
+ if (exercised.choice !== "EventLog_HoldingsChange" || !exercised.interfaceId || !matchInterfaceIds(_canton_network_core_token_standard_v2.EVENT_LOG_INTERFACE_ID, exercised.interfaceId)) return null;
236
+ return exercised.choiceArgument;
237
+ }
238
+ function getHoldingViewV2(createdEvent) {
239
+ return (createdEvent.interfaceViews?.find((v) => v.interfaceId && matchInterfaceIds(_canton_network_core_token_standard_v2.HOLDING_INTERFACE_ID_V2, v.interfaceId)))?.viewValue ?? null;
240
+ }
241
+ function sameAccount(a, b) {
242
+ return (a.owner ?? null) === (b.owner ?? null) && (a.provider ?? null) === (b.provider ?? null) && a.id === b.id;
243
+ }
244
+ function netChangeCids(change) {
245
+ const inputs = change.inputHoldingCids;
246
+ const outputs = change.outputHoldingCids;
247
+ return {
248
+ inputs: inputs.filter((cid) => !outputs.includes(cid)),
249
+ outputs: outputs.filter((cid) => !inputs.includes(cid))
250
+ };
251
+ }
252
+ /**
253
+ * Holding cids an EventLog_HoldingsChange refers to
254
+ */
255
+ function holdingCidsOf(change) {
256
+ return [...change.inputHoldingCids, ...change.outputHoldingCids];
257
+ }
258
+ function toHolding(cid, view) {
259
+ return {
260
+ contractId: cid,
261
+ owner: view.account.owner ?? "",
262
+ account: view.account,
263
+ instrumentId: view.instrumentId,
264
+ amount: view.amount,
265
+ lock: view.lock ?? null,
266
+ meta: view.meta
267
+ };
268
+ }
269
+ const isSpecialAccount = (account, id) => account.owner == null && account.id === id;
270
+ const sumAmounts = (legs) => legs.reduce((sum, leg) => sum.plus(leg.amount), new bignumber_js.default(0));
271
+ function deriveV2Label(opts) {
272
+ const { change, parentChoice, tokenStandardChoice, onlyUnlocks } = opts;
273
+ const meta = change.extraArgs.meta;
274
+ const legReasons = [...new Set(change.transferLegSides.map((l) => getMetaKeyValue(ReasonMetaKey, l.meta)).filter((r) => !!r))];
275
+ const reason = getMetaKeyValue("splice.lfdecentralizedtrust.org/reason", meta) ?? (legReasons.length === 1 ? legReasons[0] : null);
276
+ const v2 = {
277
+ admin: change.admin,
278
+ account: change.account,
279
+ transferLegSides: change.transferLegSides,
280
+ parentChoice
281
+ };
282
+ const external = change.transferLegSides.filter((l) => !sameAccount(l.otherside, change.account));
283
+ const sent = external.filter((l) => l.side === "SenderSide");
284
+ const received = external.filter((l) => l.side === "ReceiverSide");
285
+ const burned = sent.filter((l) => isSpecialAccount(l.otherside, BURN_ACCOUNT_ID));
286
+ const minted = received.filter((l) => isSpecialAccount(l.otherside, MINT_ACCOUNT_ID));
287
+ const transfersOut = sent.filter((l) => !burned.includes(l));
288
+ const transfersIn = received.filter((l) => !minted.includes(l));
289
+ const common = {
290
+ burnAmount: sumAmounts(burned).toString(),
291
+ mintAmount: sumAmounts(minted).toString(),
292
+ tokenStandardChoice,
293
+ reason,
294
+ meta,
295
+ v2
296
+ };
297
+ const noTransferType = () => burned.length > 0 && minted.length === 0 ? "Burn" : minted.length > 0 && burned.length === 0 ? "Mint" : change.transferLegSides.length === 0 && onlyUnlocks ? "Unlock" : "MergeSplit";
298
+ if (transfersOut.length === 0 && transfersIn.length === 0) return {
299
+ ...common,
300
+ type: noTransferType()
301
+ };
302
+ const net = /* @__PURE__ */ new Map();
303
+ for (const l of [...transfersOut, ...transfersIn]) {
304
+ const counterparty = l.otherside.owner ?? l.otherside.id;
305
+ const key = JSON.stringify([counterparty, l.instrumentId]);
306
+ const entry = net.get(key) ?? {
307
+ counterparty,
308
+ instrumentId: l.instrumentId,
309
+ amount: new bignumber_js.default(0)
310
+ };
311
+ entry.amount = l.side === "SenderSide" ? entry.amount.plus(l.amount) : entry.amount.minus(l.amount);
312
+ net.set(key, entry);
313
+ }
314
+ const outs = [...net.values()].filter((e) => e.amount.gt(0));
315
+ const ins = [...net.values()].filter((e) => e.amount.lt(0));
316
+ const instrument = (id) => ({
317
+ admin: change.admin,
318
+ id
319
+ });
320
+ if (outs.length === 0 && ins.length === 0) return {
321
+ ...common,
322
+ type: noTransferType()
323
+ };
324
+ if (outs.length > 0 && ins.length > 0) return {
325
+ ...common,
326
+ type: "Settlement",
327
+ netTransfers: [...outs, ...ins].map((e) => ({
328
+ counterparty: e.counterparty,
329
+ amount: e.amount.toString(),
330
+ instrumentId: instrument(e.instrumentId)
331
+ }))
332
+ };
333
+ if (outs.length > 0) return {
334
+ ...common,
335
+ type: "TransferOut",
336
+ receiverAmounts: outs.map((e) => ({
337
+ receiver: e.counterparty,
338
+ amount: e.amount.toString(),
339
+ instrumentId: instrument(e.instrumentId)
340
+ }))
341
+ };
342
+ const senders = [...new Set(ins.map((l) => l.counterparty))];
343
+ return {
344
+ ...common,
345
+ type: "TransferIn",
346
+ burnAmount: "0",
347
+ mintAmount: "0",
348
+ sender: senders.length === 1 ? senders[0] : senders.join(","),
349
+ senderAmounts: ins.map((l) => ({
350
+ sender: l.counterparty,
351
+ amount: l.amount.negated().toString(),
352
+ instrumentId: instrument(l.instrumentId)
353
+ }))
354
+ };
355
+ }
356
+ // src/parser.ts
240
357
  function currentStatusFromChoiceOrResult(choice, resultTag) {
241
358
  if (resultTag === "TransferInstructionResult_Failed") return "Failed";
242
359
  if (resultTag === "TransferInstructionResult_Completed") return "Completed";
@@ -269,6 +386,7 @@ var TransactionParser = class {
269
386
  _defineProperty(this, "partyId", void 0);
270
387
  _defineProperty(this, "transaction", void 0);
271
388
  _defineProperty(this, "isMasterUser", void 0);
389
+ _defineProperty(this, "explainedCids", /* @__PURE__ */ new Set());
272
390
  this.ledgerProvider = ledgerProvider;
273
391
  this.partyId = partyId;
274
392
  this.transaction = transaction;
@@ -331,9 +449,12 @@ var TransactionParser = class {
331
449
  };
332
450
  }
333
451
  async parseEvents(eventsStack) {
452
+ const v2 = await this.collectV2Events();
453
+ this.explainedCids = v2.explained;
454
+ const v1Events = [];
455
+ const contextOnly = [];
334
456
  let callStack = [];
335
457
  let continueAfterNodeId = -1;
336
- const result = [];
337
458
  while (eventsStack.length > 0) {
338
459
  const currentEvent = eventsStack.pop();
339
460
  const { nodeId, createdEvent, archivedEvent, exercisedEvent } = getNodeIdAndEvent(currentEvent);
@@ -346,22 +467,56 @@ var TransactionParser = class {
346
467
  else if (exercisedEvent) parsed = await this.parseExercise(exercisedEvent);
347
468
  else throw new Error(`Impossible event: ${JSON.stringify(currentEvent)}`);
348
469
  if (parsed && isLeafEventNode(parsed)) {
349
- if (holdingChangesNonEmpty(parsed.event) || parsed.event.transferInstruction?.transfer != null) result.push({
350
- ...parsed.event,
351
- label: {
352
- ...parsed.event.label,
353
- meta: removeParsedMetaKeys(parsed.event.label.meta)
470
+ const emittedV1 = {
471
+ nodeId,
472
+ lastNodeId: parsed.continueAfterNodeId,
473
+ event: {
474
+ ...parsed.event,
475
+ label: {
476
+ ...parsed.event.label,
477
+ meta: removeParsedMetaKeys(parsed.event.label.meta)
478
+ }
354
479
  }
355
- });
480
+ };
481
+ if (holdingChangesNonEmpty(parsed.event) || parsed.event.transferInstruction?.transfer != null) v1Events.push(emittedV1);
482
+ else if (choiceOf(emittedV1)) contextOnly.push(emittedV1);
356
483
  continueAfterNodeId = parsed.continueAfterNodeId;
357
484
  } else if (parsed) callStack.push({
358
485
  parentChoiceName: parsed.parentChoiceName,
359
486
  untilNodeId: parsed.lastDescendantNodeId
360
487
  });
361
488
  }
362
- return result;
489
+ for (const v1 of [...v1Events, ...contextOnly]) {
490
+ const choice = choiceOf(v1);
491
+ if (!choice) continue;
492
+ for (const e of v2.events) if (e.nodeId >= v1.nodeId && e.nodeId <= v1.lastNodeId) e.event.label.tokenStandardChoice = choice;
493
+ }
494
+ const kept = [];
495
+ for (const v1 of v1Events) {
496
+ const ti = v1.event.transferInstruction;
497
+ if (holdingChangesNonEmpty(v1.event) || ti?.transfer == null) {
498
+ kept.push(v1);
499
+ continue;
500
+ }
501
+ const inRange = v2.events.filter((e) => e.nodeId >= v1.nodeId && e.nodeId <= v1.lastNodeId && e.event.transferInstruction == null);
502
+ const target = inRange.find(hasExternalLegs) ?? inRange[0];
503
+ if (target) target.event.transferInstruction = ti;
504
+ else kept.push(v1);
505
+ }
506
+ const cleanupV2 = v2.events.map((e) => ({
507
+ ...e,
508
+ event: {
509
+ ...e.event,
510
+ label: {
511
+ ...e.event.label,
512
+ meta: removeParsedMetaKeys(e.event.label.meta)
513
+ }
514
+ }
515
+ }));
516
+ return [...kept, ...cleanupV2].sort((a, b) => a.nodeId - b.nodeId).map((e) => e.event);
363
517
  }
364
518
  parseRawCreate(create, parentChoice) {
519
+ if (this.explainedCids.has(create.contractId)) return null;
365
520
  return this.buildRawEvent(create, create.nodeId, (result) => {
366
521
  return {
367
522
  type: Number(result.lockedHoldingsChangeSummaries[0]?.amountChange) > 0 ? "Lock" : "Create",
@@ -376,6 +531,7 @@ var TransactionParser = class {
376
531
  });
377
532
  }
378
533
  async parseRawArchive(archive, parentChoice) {
534
+ if (this.explainedCids.has(archive.contractId)) return null;
379
535
  const events = await this.getEventsForArchive(archive);
380
536
  if (!events) return null;
381
537
  return this.buildRawEvent(events.created.createdEvent, archive.nodeId, (result) => {
@@ -739,9 +895,10 @@ var TransactionParser = class {
739
895
  mutatingResult.archives.push(toHoldingWithContractId(holdingView, archivedEvent?.contractId || exercisedEvent.contractId));
740
896
  }
741
897
  }
898
+ const unxplained = (h) => !this.explainedCids.has(h.contractId);
742
899
  return {
743
- creates: mutatingResult.creates.filter((create) => !mutatingResult.archives.some((archive) => create.contractId === archive.contractId)),
744
- archives: mutatingResult.archives.filter((archive) => !mutatingResult.creates.some((create) => create.contractId === archive.contractId))
900
+ creates: mutatingResult.creates.filter((create) => !mutatingResult.archives.some((archive) => create.contractId === archive.contractId)).filter(unxplained),
901
+ archives: mutatingResult.archives.filter((archive) => !mutatingResult.creates.some((create) => create.contractId === archive.contractId)).filter(unxplained)
745
902
  };
746
903
  }
747
904
  async getEventsForArchive(archivedEvent) {
@@ -756,6 +913,84 @@ var TransactionParser = class {
756
913
  archived
757
914
  };
758
915
  }
916
+ async collectV2Events() {
917
+ const views = /* @__PURE__ */ new Map();
918
+ const emitted = [];
919
+ const explained = /* @__PURE__ */ new Set();
920
+ let stack = [];
921
+ for (const raw of this.transaction.events ?? []) {
922
+ const { nodeId, createdEvent, exercisedEvent } = getNodeIdAndEvent(raw);
923
+ stack = stack.filter((s) => s.until >= nodeId);
924
+ const parentChoice = stack.at(-1)?.choice ?? "none (root node)";
925
+ if (createdEvent) {
926
+ const view = getHoldingViewV2(createdEvent);
927
+ if (view) views.set(createdEvent.contractId, view);
928
+ }
929
+ if (!exercisedEvent) continue;
930
+ stack.push({
931
+ choice: exercisedEvent.choice,
932
+ until: exercisedEvent.lastDescendantNodeId
933
+ });
934
+ const change = extractHoldingsChange(exercisedEvent);
935
+ if (!change || change.account.owner !== this.partyId) continue;
936
+ const { inputs, outputs } = netChangeCids(change);
937
+ const resolve = (cid) => this.resolveV2Holding(cid, views);
938
+ const ins = (await Promise.all(inputs.map(resolve))).filter((h) => h !== null);
939
+ const outs = (await Promise.all(outputs.map(resolve))).filter((h) => h !== null);
940
+ if ([...ins, ...outs].some((h) => h.instrumentId.admin !== change.admin || !sameAccount(h.account, change.account))) {
941
+ console.warn(`Ignoring EventLog_holdingsChange at node ${nodeId}: holdings do not match admin/account`);
942
+ continue;
943
+ }
944
+ const lockedHoldingsChange = {
945
+ creates: outs.filter((h) => !!h.lock),
946
+ archives: ins.filter((h) => !!h.lock)
947
+ };
948
+ const unlockedHoldingsChange = {
949
+ creates: outs.filter((h) => !h.lock),
950
+ archives: ins.filter((h) => !h.lock)
951
+ };
952
+ const lockedHoldingsChangeSummaries = computeSummaries(lockedHoldingsChange, this.partyId);
953
+ const unlockedHoldingsChangeSummaries = computeSummaries(unlockedHoldingsChange, this.partyId);
954
+ const event = {
955
+ label: deriveV2Label({
956
+ change,
957
+ parentChoice,
958
+ tokenStandardChoice: {
959
+ name: exercisedEvent.choice,
960
+ choiceArgument: exercisedEvent.choiceArgument,
961
+ exerciseResult: exercisedEvent.exerciseResult
962
+ },
963
+ onlyUnlocks: lockedHoldingsChange.creates.length === 0 && lockedHoldingsChange.archives.length > 0
964
+ }),
965
+ lockedHoldingsChange,
966
+ lockedHoldingsChangeSummaries,
967
+ lockedHoldingsChangeSummary: lockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
968
+ unlockedHoldingsChange,
969
+ unlockedHoldingsChangeSummaries,
970
+ unlockedHoldingsChangeSummary: unlockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
971
+ transferInstruction: null
972
+ };
973
+ holdingCidsOf(change).forEach((cid) => explained.add(cid));
974
+ if (holdingChangesNonEmpty(event) || change.transferLegSides.length > 0) emitted.push({
975
+ nodeId,
976
+ lastNodeId: nodeId,
977
+ event
978
+ });
979
+ }
980
+ return {
981
+ events: emitted,
982
+ explained
983
+ };
984
+ }
985
+ async resolveV2Holding(cid, views) {
986
+ const cached = views.get(cid);
987
+ if (cached) return toHolding(cid, cached);
988
+ const events = await this.fetchContractEvents(cid, [_canton_network_core_token_standard_v2.HOLDING_INTERFACE_ID_V2]);
989
+ const view = events?.created?.createdEvent && getHoldingViewV2(events.created.createdEvent);
990
+ if (!view) return null;
991
+ views.set(cid, view);
992
+ return toHolding(cid, view);
993
+ }
759
994
  };
760
995
  function isLeafEventNode(result) {
761
996
  return !!result.event;
@@ -867,7 +1102,13 @@ const emptyHoldingsChangeSummary = {
867
1102
  outputAmount: "0",
868
1103
  amountChange: "0"
869
1104
  };
870
- //#endregion
1105
+ function hasExternalLegs(e) {
1106
+ const v2Label = e.event.label.v2;
1107
+ return !!v2Label?.transferLegSides.some((l) => !sameAccount(l.otherside, v2Label.account));
1108
+ }
1109
+ function choiceOf(e) {
1110
+ return e.event.label.tokenStandardChoice ?? null;
1111
+ }
871
1112
  exports.AllKnownMetaKeys = AllKnownMetaKeys;
872
1113
  exports.BurnedMetaKey = BurnedMetaKey;
873
1114
  exports.ReasonMetaKey = ReasonMetaKey;