@canton-network/core-tx-parser 1.15.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { ALLOCATION_FACTORY_INTERFACE_ID, ALLOCATION_INSTRUCTION_INTERFACE_ID, ALLOCATION_INTERFACE_ID, ALLOCATION_REQUEST_INTERFACE_ID, HOLDING_INTERFACE_ID, TRANSFER_FACTORY_INTERFACE_ID, TRANSFER_INSTRUCTION_INTERFACE_ID } from "@canton-network/core-token-standard";
2
2
  import { EventFilterBySetup } from "@canton-network/core-ledger-client-types";
3
3
  import BigNumber from "bignumber.js";
4
- //#region src/constants.ts
4
+ import { EVENT_LOG_INTERFACE_ID, HOLDING_INTERFACE_ID_V2 } from "@canton-network/core-token-standard-v2";
5
+ // src/constants.ts
5
6
  function splitInterfaceId(interfaceId) {
6
7
  const match = /^#?([^:]+):([^:]+):([^:]+)$/.exec(interfaceId);
7
8
  if (!match) return null;
@@ -37,8 +38,7 @@ const AllKnownMetaKeys = [
37
38
  ReasonMetaKey,
38
39
  BurnedMetaKey
39
40
  ];
40
- //#endregion
41
- //#region src/utils.ts
41
+ // src/utils.ts
42
42
  function hasInterface(interfaceId, event) {
43
43
  return (event.implementedInterfaces || []).some((id) => matchInterfaceIds(id, interfaceId));
44
44
  }
@@ -98,8 +98,7 @@ function getMetaKeyValue(key, meta) {
98
98
  function removeParsedMetaKeys(meta) {
99
99
  return { values: Object.fromEntries(Object.entries(meta?.values || {}).filter(([k]) => !AllKnownMetaKeys.includes(k))) };
100
100
  }
101
- //#endregion
102
- //#region src/types.ts
101
+ // src/types.ts
103
102
  const renderTransaction = (t) => {
104
103
  return {
105
104
  ...t,
@@ -139,8 +138,7 @@ const renderHoldingsChange = (c) => {
139
138
  ...c.archives.length !== 0 && { archives: c.archives }
140
139
  };
141
140
  };
142
- //#endregion
143
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/typeof.js
141
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/typeof.js
144
142
  function _typeof(o) {
145
143
  "@babel/helpers - typeof";
146
144
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -149,8 +147,7 @@ function _typeof(o) {
149
147
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
150
148
  }, _typeof(o);
151
149
  }
152
- //#endregion
153
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPrimitive.js
150
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/toPrimitive.js
154
151
  function toPrimitive(t, r) {
155
152
  if ("object" != _typeof(t) || !t) return t;
156
153
  var e = t[Symbol.toPrimitive];
@@ -161,14 +158,12 @@ function toPrimitive(t, r) {
161
158
  }
162
159
  return ("string" === r ? String : Number)(t);
163
160
  }
164
- //#endregion
165
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPropertyKey.js
161
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/toPropertyKey.js
166
162
  function toPropertyKey(t) {
167
163
  var i = toPrimitive(t, "string");
168
164
  return "symbol" == _typeof(i) ? i : i + "";
169
165
  }
170
- //#endregion
171
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/defineProperty.js
166
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/defineProperty.js
172
167
  function _defineProperty(e, r, t) {
173
168
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
174
169
  value: t,
@@ -177,8 +172,7 @@ function _defineProperty(e, r, t) {
177
172
  writable: !0
178
173
  }) : e[r] = t, e;
179
174
  }
180
- //#endregion
181
- //#region src/instrumentmap.ts
175
+ // src/instrumentmap.ts
182
176
  /** InstrumentMap is a helper for when you want to group values by instrument. */
183
177
  var InstrumentMap = class {
184
178
  encodeKey(instrumentId) {
@@ -211,8 +205,132 @@ var InstrumentMap = class {
211
205
  for (const [key, value] of this.map.entries()) yield [this.decodeKey(key), value];
212
206
  }
213
207
  };
214
- //#endregion
215
- //#region src/parser.ts
208
+ // src/v2-events.ts
209
+ const MINT_ACCOUNT_ID = "cip-112/mint";
210
+ const BURN_ACCOUNT_ID = "cip-112/burn";
211
+ function extractHoldingsChange(exercised) {
212
+ if (exercised.choice !== "EventLog_HoldingsChange" || !exercised.interfaceId || !matchInterfaceIds(EVENT_LOG_INTERFACE_ID, exercised.interfaceId)) return null;
213
+ return exercised.choiceArgument;
214
+ }
215
+ function getHoldingViewV2(createdEvent) {
216
+ return (createdEvent.interfaceViews?.find((v) => v.interfaceId && matchInterfaceIds(HOLDING_INTERFACE_ID_V2, v.interfaceId)))?.viewValue ?? null;
217
+ }
218
+ function sameAccount(a, b) {
219
+ return (a.owner ?? null) === (b.owner ?? null) && (a.provider ?? null) === (b.provider ?? null) && a.id === b.id;
220
+ }
221
+ function netChangeCids(change) {
222
+ const inputs = change.inputHoldingCids;
223
+ const outputs = change.outputHoldingCids;
224
+ return {
225
+ inputs: inputs.filter((cid) => !outputs.includes(cid)),
226
+ outputs: outputs.filter((cid) => !inputs.includes(cid))
227
+ };
228
+ }
229
+ /**
230
+ * Holding cids an EventLog_HoldingsChange refers to
231
+ */
232
+ function holdingCidsOf(change) {
233
+ return [...change.inputHoldingCids, ...change.outputHoldingCids];
234
+ }
235
+ function toHolding(cid, view) {
236
+ return {
237
+ contractId: cid,
238
+ owner: view.account.owner ?? "",
239
+ account: view.account,
240
+ instrumentId: view.instrumentId,
241
+ amount: view.amount,
242
+ lock: view.lock ?? null,
243
+ meta: view.meta
244
+ };
245
+ }
246
+ const isSpecialAccount = (account, id) => account.owner == null && account.id === id;
247
+ const sumAmounts = (legs) => legs.reduce((sum, leg) => sum.plus(leg.amount), new BigNumber(0));
248
+ function deriveV2Label(opts) {
249
+ const { change, parentChoice, tokenStandardChoice, onlyUnlocks } = opts;
250
+ const meta = change.extraArgs.meta;
251
+ const legReasons = [...new Set(change.transferLegSides.map((l) => getMetaKeyValue(ReasonMetaKey, l.meta)).filter((r) => !!r))];
252
+ const reason = getMetaKeyValue("splice.lfdecentralizedtrust.org/reason", meta) ?? (legReasons.length === 1 ? legReasons[0] : null);
253
+ const v2 = {
254
+ admin: change.admin,
255
+ account: change.account,
256
+ transferLegSides: change.transferLegSides,
257
+ parentChoice
258
+ };
259
+ const external = change.transferLegSides.filter((l) => !sameAccount(l.otherside, change.account));
260
+ const sent = external.filter((l) => l.side === "SenderSide");
261
+ const received = external.filter((l) => l.side === "ReceiverSide");
262
+ const burned = sent.filter((l) => isSpecialAccount(l.otherside, BURN_ACCOUNT_ID));
263
+ const minted = received.filter((l) => isSpecialAccount(l.otherside, MINT_ACCOUNT_ID));
264
+ const transfersOut = sent.filter((l) => !burned.includes(l));
265
+ const transfersIn = received.filter((l) => !minted.includes(l));
266
+ const common = {
267
+ burnAmount: sumAmounts(burned).toString(),
268
+ mintAmount: sumAmounts(minted).toString(),
269
+ tokenStandardChoice,
270
+ reason,
271
+ meta,
272
+ v2
273
+ };
274
+ const noTransferType = () => burned.length > 0 && minted.length === 0 ? "Burn" : minted.length > 0 && burned.length === 0 ? "Mint" : change.transferLegSides.length === 0 && onlyUnlocks ? "Unlock" : "MergeSplit";
275
+ if (transfersOut.length === 0 && transfersIn.length === 0) return {
276
+ ...common,
277
+ type: noTransferType()
278
+ };
279
+ const net = /* @__PURE__ */ new Map();
280
+ for (const l of [...transfersOut, ...transfersIn]) {
281
+ const counterparty = l.otherside.owner ?? l.otherside.id;
282
+ const key = JSON.stringify([counterparty, l.instrumentId]);
283
+ const entry = net.get(key) ?? {
284
+ counterparty,
285
+ instrumentId: l.instrumentId,
286
+ amount: new BigNumber(0)
287
+ };
288
+ entry.amount = l.side === "SenderSide" ? entry.amount.plus(l.amount) : entry.amount.minus(l.amount);
289
+ net.set(key, entry);
290
+ }
291
+ const outs = [...net.values()].filter((e) => e.amount.gt(0));
292
+ const ins = [...net.values()].filter((e) => e.amount.lt(0));
293
+ const instrument = (id) => ({
294
+ admin: change.admin,
295
+ id
296
+ });
297
+ if (outs.length === 0 && ins.length === 0) return {
298
+ ...common,
299
+ type: noTransferType()
300
+ };
301
+ if (outs.length > 0 && ins.length > 0) return {
302
+ ...common,
303
+ type: "Settlement",
304
+ netTransfers: [...outs, ...ins].map((e) => ({
305
+ counterparty: e.counterparty,
306
+ amount: e.amount.toString(),
307
+ instrumentId: instrument(e.instrumentId)
308
+ }))
309
+ };
310
+ if (outs.length > 0) return {
311
+ ...common,
312
+ type: "TransferOut",
313
+ receiverAmounts: outs.map((e) => ({
314
+ receiver: e.counterparty,
315
+ amount: e.amount.toString(),
316
+ instrumentId: instrument(e.instrumentId)
317
+ }))
318
+ };
319
+ const senders = [...new Set(ins.map((l) => l.counterparty))];
320
+ return {
321
+ ...common,
322
+ type: "TransferIn",
323
+ burnAmount: "0",
324
+ mintAmount: "0",
325
+ sender: senders.length === 1 ? senders[0] : senders.join(","),
326
+ senderAmounts: ins.map((l) => ({
327
+ sender: l.counterparty,
328
+ amount: l.amount.negated().toString(),
329
+ instrumentId: instrument(l.instrumentId)
330
+ }))
331
+ };
332
+ }
333
+ // src/parser.ts
216
334
  function currentStatusFromChoiceOrResult(choice, resultTag) {
217
335
  if (resultTag === "TransferInstructionResult_Failed") return "Failed";
218
336
  if (resultTag === "TransferInstructionResult_Completed") return "Completed";
@@ -245,6 +363,7 @@ var TransactionParser = class {
245
363
  _defineProperty(this, "partyId", void 0);
246
364
  _defineProperty(this, "transaction", void 0);
247
365
  _defineProperty(this, "isMasterUser", void 0);
366
+ _defineProperty(this, "explainedCids", /* @__PURE__ */ new Set());
248
367
  this.ledgerProvider = ledgerProvider;
249
368
  this.partyId = partyId;
250
369
  this.transaction = transaction;
@@ -307,9 +426,12 @@ var TransactionParser = class {
307
426
  };
308
427
  }
309
428
  async parseEvents(eventsStack) {
429
+ const v2 = await this.collectV2Events();
430
+ this.explainedCids = v2.explained;
431
+ const v1Events = [];
432
+ const contextOnly = [];
310
433
  let callStack = [];
311
434
  let continueAfterNodeId = -1;
312
- const result = [];
313
435
  while (eventsStack.length > 0) {
314
436
  const currentEvent = eventsStack.pop();
315
437
  const { nodeId, createdEvent, archivedEvent, exercisedEvent } = getNodeIdAndEvent(currentEvent);
@@ -322,22 +444,56 @@ var TransactionParser = class {
322
444
  else if (exercisedEvent) parsed = await this.parseExercise(exercisedEvent);
323
445
  else throw new Error(`Impossible event: ${JSON.stringify(currentEvent)}`);
324
446
  if (parsed && isLeafEventNode(parsed)) {
325
- if (holdingChangesNonEmpty(parsed.event) || parsed.event.transferInstruction?.transfer != null) result.push({
326
- ...parsed.event,
327
- label: {
328
- ...parsed.event.label,
329
- meta: removeParsedMetaKeys(parsed.event.label.meta)
447
+ const emittedV1 = {
448
+ nodeId,
449
+ lastNodeId: parsed.continueAfterNodeId,
450
+ event: {
451
+ ...parsed.event,
452
+ label: {
453
+ ...parsed.event.label,
454
+ meta: removeParsedMetaKeys(parsed.event.label.meta)
455
+ }
330
456
  }
331
- });
457
+ };
458
+ if (holdingChangesNonEmpty(parsed.event) || parsed.event.transferInstruction?.transfer != null) v1Events.push(emittedV1);
459
+ else if (choiceOf(emittedV1)) contextOnly.push(emittedV1);
332
460
  continueAfterNodeId = parsed.continueAfterNodeId;
333
461
  } else if (parsed) callStack.push({
334
462
  parentChoiceName: parsed.parentChoiceName,
335
463
  untilNodeId: parsed.lastDescendantNodeId
336
464
  });
337
465
  }
338
- return result;
466
+ for (const v1 of [...v1Events, ...contextOnly]) {
467
+ const choice = choiceOf(v1);
468
+ if (!choice) continue;
469
+ for (const e of v2.events) if (e.nodeId >= v1.nodeId && e.nodeId <= v1.lastNodeId) e.event.label.tokenStandardChoice = choice;
470
+ }
471
+ const kept = [];
472
+ for (const v1 of v1Events) {
473
+ const ti = v1.event.transferInstruction;
474
+ if (holdingChangesNonEmpty(v1.event) || ti?.transfer == null) {
475
+ kept.push(v1);
476
+ continue;
477
+ }
478
+ const inRange = v2.events.filter((e) => e.nodeId >= v1.nodeId && e.nodeId <= v1.lastNodeId && e.event.transferInstruction == null);
479
+ const target = inRange.find(hasExternalLegs) ?? inRange[0];
480
+ if (target) target.event.transferInstruction = ti;
481
+ else kept.push(v1);
482
+ }
483
+ const cleanupV2 = v2.events.map((e) => ({
484
+ ...e,
485
+ event: {
486
+ ...e.event,
487
+ label: {
488
+ ...e.event.label,
489
+ meta: removeParsedMetaKeys(e.event.label.meta)
490
+ }
491
+ }
492
+ }));
493
+ return [...kept, ...cleanupV2].sort((a, b) => a.nodeId - b.nodeId).map((e) => e.event);
339
494
  }
340
495
  parseRawCreate(create, parentChoice) {
496
+ if (this.explainedCids.has(create.contractId)) return null;
341
497
  return this.buildRawEvent(create, create.nodeId, (result) => {
342
498
  return {
343
499
  type: Number(result.lockedHoldingsChangeSummaries[0]?.amountChange) > 0 ? "Lock" : "Create",
@@ -352,6 +508,7 @@ var TransactionParser = class {
352
508
  });
353
509
  }
354
510
  async parseRawArchive(archive, parentChoice) {
511
+ if (this.explainedCids.has(archive.contractId)) return null;
355
512
  const events = await this.getEventsForArchive(archive);
356
513
  if (!events) return null;
357
514
  return this.buildRawEvent(events.created.createdEvent, archive.nodeId, (result) => {
@@ -715,9 +872,10 @@ var TransactionParser = class {
715
872
  mutatingResult.archives.push(toHoldingWithContractId(holdingView, archivedEvent?.contractId || exercisedEvent.contractId));
716
873
  }
717
874
  }
875
+ const unxplained = (h) => !this.explainedCids.has(h.contractId);
718
876
  return {
719
- creates: mutatingResult.creates.filter((create) => !mutatingResult.archives.some((archive) => create.contractId === archive.contractId)),
720
- archives: mutatingResult.archives.filter((archive) => !mutatingResult.creates.some((create) => create.contractId === archive.contractId))
877
+ creates: mutatingResult.creates.filter((create) => !mutatingResult.archives.some((archive) => create.contractId === archive.contractId)).filter(unxplained),
878
+ archives: mutatingResult.archives.filter((archive) => !mutatingResult.creates.some((create) => create.contractId === archive.contractId)).filter(unxplained)
721
879
  };
722
880
  }
723
881
  async getEventsForArchive(archivedEvent) {
@@ -732,6 +890,84 @@ var TransactionParser = class {
732
890
  archived
733
891
  };
734
892
  }
893
+ async collectV2Events() {
894
+ const views = /* @__PURE__ */ new Map();
895
+ const emitted = [];
896
+ const explained = /* @__PURE__ */ new Set();
897
+ let stack = [];
898
+ for (const raw of this.transaction.events ?? []) {
899
+ const { nodeId, createdEvent, exercisedEvent } = getNodeIdAndEvent(raw);
900
+ stack = stack.filter((s) => s.until >= nodeId);
901
+ const parentChoice = stack.at(-1)?.choice ?? "none (root node)";
902
+ if (createdEvent) {
903
+ const view = getHoldingViewV2(createdEvent);
904
+ if (view) views.set(createdEvent.contractId, view);
905
+ }
906
+ if (!exercisedEvent) continue;
907
+ stack.push({
908
+ choice: exercisedEvent.choice,
909
+ until: exercisedEvent.lastDescendantNodeId
910
+ });
911
+ const change = extractHoldingsChange(exercisedEvent);
912
+ if (!change || change.account.owner !== this.partyId) continue;
913
+ const { inputs, outputs } = netChangeCids(change);
914
+ const resolve = (cid) => this.resolveV2Holding(cid, views);
915
+ const ins = (await Promise.all(inputs.map(resolve))).filter((h) => h !== null);
916
+ const outs = (await Promise.all(outputs.map(resolve))).filter((h) => h !== null);
917
+ if ([...ins, ...outs].some((h) => h.instrumentId.admin !== change.admin || !sameAccount(h.account, change.account))) {
918
+ console.warn(`Ignoring EventLog_holdingsChange at node ${nodeId}: holdings do not match admin/account`);
919
+ continue;
920
+ }
921
+ const lockedHoldingsChange = {
922
+ creates: outs.filter((h) => !!h.lock),
923
+ archives: ins.filter((h) => !!h.lock)
924
+ };
925
+ const unlockedHoldingsChange = {
926
+ creates: outs.filter((h) => !h.lock),
927
+ archives: ins.filter((h) => !h.lock)
928
+ };
929
+ const lockedHoldingsChangeSummaries = computeSummaries(lockedHoldingsChange, this.partyId);
930
+ const unlockedHoldingsChangeSummaries = computeSummaries(unlockedHoldingsChange, this.partyId);
931
+ const event = {
932
+ label: deriveV2Label({
933
+ change,
934
+ parentChoice,
935
+ tokenStandardChoice: {
936
+ name: exercisedEvent.choice,
937
+ choiceArgument: exercisedEvent.choiceArgument,
938
+ exerciseResult: exercisedEvent.exerciseResult
939
+ },
940
+ onlyUnlocks: lockedHoldingsChange.creates.length === 0 && lockedHoldingsChange.archives.length > 0
941
+ }),
942
+ lockedHoldingsChange,
943
+ lockedHoldingsChangeSummaries,
944
+ lockedHoldingsChangeSummary: lockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
945
+ unlockedHoldingsChange,
946
+ unlockedHoldingsChangeSummaries,
947
+ unlockedHoldingsChangeSummary: unlockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
948
+ transferInstruction: null
949
+ };
950
+ holdingCidsOf(change).forEach((cid) => explained.add(cid));
951
+ if (holdingChangesNonEmpty(event) || change.transferLegSides.length > 0) emitted.push({
952
+ nodeId,
953
+ lastNodeId: nodeId,
954
+ event
955
+ });
956
+ }
957
+ return {
958
+ events: emitted,
959
+ explained
960
+ };
961
+ }
962
+ async resolveV2Holding(cid, views) {
963
+ const cached = views.get(cid);
964
+ if (cached) return toHolding(cid, cached);
965
+ const events = await this.fetchContractEvents(cid, [HOLDING_INTERFACE_ID_V2]);
966
+ const view = events?.created?.createdEvent && getHoldingViewV2(events.created.createdEvent);
967
+ if (!view) return null;
968
+ views.set(cid, view);
969
+ return toHolding(cid, view);
970
+ }
735
971
  };
736
972
  function isLeafEventNode(result) {
737
973
  return !!result.event;
@@ -843,7 +1079,13 @@ const emptyHoldingsChangeSummary = {
843
1079
  outputAmount: "0",
844
1080
  amountChange: "0"
845
1081
  };
846
- //#endregion
1082
+ function hasExternalLegs(e) {
1083
+ const v2Label = e.event.label.v2;
1084
+ return !!v2Label?.transferLegSides.some((l) => !sameAccount(l.otherside, v2Label.account));
1085
+ }
1086
+ function choiceOf(e) {
1087
+ return e.event.label.tokenStandardChoice ?? null;
1088
+ }
847
1089
  export { AllKnownMetaKeys, BurnedMetaKey, ReasonMetaKey, SenderMetaKey, TokenStandardTransactionInterfaces, TransactionParser, TxKindMetaKey, ensureInterfaceViewIsPresent, getInterfaceView, getKnownInterfaceView, getMetaKeyValue, hasInterface, isContractEventsNotFoundError, matchInterfaceIds, mergeMetas, removeParsedMetaKeys, renderTransaction, splitInterfaceId };
848
1090
 
849
1091
  //# sourceMappingURL=index.js.map