@canton-network/core-tx-parser 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1002 +1,856 @@
1
- import { HOLDING_INTERFACE_ID, TRANSFER_FACTORY_INTERFACE_ID, TRANSFER_INSTRUCTION_INTERFACE_ID, ALLOCATION_FACTORY_INTERFACE_ID, ALLOCATION_INSTRUCTION_INTERFACE_ID, ALLOCATION_INTERFACE_ID, ALLOCATION_REQUEST_INTERFACE_ID } from '@canton-network/core-token-standard';
2
- import { EventFilterBySetup } from '@canton-network/core-ledger-client-types';
3
- import BigNumber from 'bignumber.js';
4
-
5
- var __defProp = Object.defineProperty;
6
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
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
+ import { EventFilterBySetup } from "@canton-network/core-ledger-client-types";
3
+ import BigNumber from "bignumber.js";
4
+ //#region src/constants.ts
8
5
  function splitInterfaceId(interfaceId) {
9
- const regExp = /^#?([^:]+):([^:]+):([^:]+)$/;
10
- const match = regExp.exec(interfaceId);
11
- if (!match) return null;
12
- const [, packageName, moduleName, entityName] = match;
13
- return {
14
- packageName,
15
- moduleName,
16
- entityName
17
- };
6
+ const match = /^#?([^:]+):([^:]+):([^:]+)$/.exec(interfaceId);
7
+ if (!match) return null;
8
+ const [, packageName, moduleName, entityName] = match;
9
+ return {
10
+ packageName,
11
+ moduleName,
12
+ entityName
13
+ };
18
14
  }
19
15
  function matchInterfaceIds(a, b) {
20
- const aParts = splitInterfaceId(a);
21
- const bParts = splitInterfaceId(b);
22
- return aParts !== null && bParts !== null && aParts.moduleName === bParts.moduleName && aParts.entityName === bParts.entityName;
16
+ const aParts = splitInterfaceId(a);
17
+ const bParts = splitInterfaceId(b);
18
+ return aParts !== null && bParts !== null && aParts.moduleName === bParts.moduleName && aParts.entityName === bParts.entityName;
23
19
  }
24
- var TokenStandardTransactionInterfaces = [
25
- HOLDING_INTERFACE_ID,
26
- TRANSFER_FACTORY_INTERFACE_ID,
27
- TRANSFER_INSTRUCTION_INTERFACE_ID,
28
- ALLOCATION_FACTORY_INTERFACE_ID,
29
- ALLOCATION_INSTRUCTION_INTERFACE_ID,
30
- ALLOCATION_INTERFACE_ID,
31
- ALLOCATION_REQUEST_INTERFACE_ID
20
+ const TokenStandardTransactionInterfaces = [
21
+ HOLDING_INTERFACE_ID,
22
+ TRANSFER_FACTORY_INTERFACE_ID,
23
+ TRANSFER_INSTRUCTION_INTERFACE_ID,
24
+ ALLOCATION_FACTORY_INTERFACE_ID,
25
+ ALLOCATION_INSTRUCTION_INTERFACE_ID,
26
+ ALLOCATION_INTERFACE_ID,
27
+ ALLOCATION_REQUEST_INTERFACE_ID
32
28
  ];
33
- var SpliceMetaKeyPrefix = "splice.lfdecentralizedtrust.org/";
34
- var TxKindMetaKey = `${SpliceMetaKeyPrefix}tx-kind`;
35
- var SenderMetaKey = `${SpliceMetaKeyPrefix}sender`;
36
- var ReasonMetaKey = `${SpliceMetaKeyPrefix}reason`;
37
- var BurnedMetaKey = `${SpliceMetaKeyPrefix}burned`;
38
- var AllKnownMetaKeys = [
39
- TxKindMetaKey,
40
- SenderMetaKey,
41
- ReasonMetaKey,
42
- BurnedMetaKey
29
+ const SpliceMetaKeyPrefix = "splice.lfdecentralizedtrust.org/";
30
+ const TxKindMetaKey = `${SpliceMetaKeyPrefix}tx-kind`;
31
+ const SenderMetaKey = `${SpliceMetaKeyPrefix}sender`;
32
+ const ReasonMetaKey = `${SpliceMetaKeyPrefix}reason`;
33
+ const BurnedMetaKey = `${SpliceMetaKeyPrefix}burned`;
34
+ const AllKnownMetaKeys = [
35
+ TxKindMetaKey,
36
+ SenderMetaKey,
37
+ ReasonMetaKey,
38
+ BurnedMetaKey
43
39
  ];
40
+ //#endregion
41
+ //#region src/utils.ts
44
42
  function hasInterface(interfaceId, event) {
45
- return (event.implementedInterfaces || []).some(
46
- (id) => matchInterfaceIds(id, interfaceId)
47
- );
43
+ return (event.implementedInterfaces || []).some((id) => matchInterfaceIds(id, interfaceId));
48
44
  }
49
45
  function getInterfaceView(createdEvent) {
50
- const interfaceViews = createdEvent.interfaceViews || null;
51
- return interfaceViews && interfaceViews[0] || null;
46
+ const interfaceViews = createdEvent.interfaceViews || null;
47
+ return interfaceViews && interfaceViews[0] || null;
52
48
  }
53
49
  function getKnownInterfaceView(createdEvent) {
54
- const interfaceView = getInterfaceView(createdEvent);
55
- if (!interfaceView || !interfaceView.interfaceId) {
56
- return null;
57
- } else if (matchInterfaceIds(HOLDING_INTERFACE_ID, interfaceView.interfaceId)) {
58
- return {
59
- type: "Holding",
60
- viewValue: interfaceView.viewValue
61
- };
62
- } else if (matchInterfaceIds(
63
- TRANSFER_INSTRUCTION_INTERFACE_ID,
64
- interfaceView.interfaceId
65
- )) {
66
- return {
67
- type: "TransferInstruction",
68
- viewValue: interfaceView.viewValue
69
- };
70
- } else {
71
- return null;
72
- }
50
+ const interfaceView = getInterfaceView(createdEvent);
51
+ if (!interfaceView || !interfaceView.interfaceId) return null;
52
+ else if (matchInterfaceIds(HOLDING_INTERFACE_ID, interfaceView.interfaceId)) return {
53
+ type: "Holding",
54
+ viewValue: interfaceView.viewValue
55
+ };
56
+ else if (matchInterfaceIds(TRANSFER_INSTRUCTION_INTERFACE_ID, interfaceView.interfaceId)) return {
57
+ type: "TransferInstruction",
58
+ viewValue: interfaceView.viewValue
59
+ };
60
+ else return null;
73
61
  }
62
+ /**
63
+ * Use this when `createdEvent` is guaranteed to have an interface view because the ledger api filters
64
+ * include it, and thus is guaranteed to be returned by the API.
65
+ */
74
66
  function ensureInterfaceViewIsPresent(createdEvent, interfaceId) {
75
- const interfaceView = getInterfaceView(createdEvent);
76
- if (!interfaceView) {
77
- throw new Error(
78
- `Expected to have interface views, but didn't: ${JSON.stringify(
79
- createdEvent
80
- )}`
81
- );
82
- }
83
- if (!interfaceView.interfaceId || !matchInterfaceIds(interfaceId, interfaceView.interfaceId)) {
84
- throw new Error(
85
- `Not a ${interfaceId} but a ${interfaceView.interfaceId}: ${JSON.stringify(createdEvent)}`
86
- );
87
- }
88
- return interfaceView;
67
+ const interfaceView = getInterfaceView(createdEvent);
68
+ if (!interfaceView) throw new Error(`Expected to have interface views, but didn't: ${JSON.stringify(createdEvent)}`);
69
+ if (!interfaceView.interfaceId || !matchInterfaceIds(interfaceId, interfaceView.interfaceId)) throw new Error(`Not a ${interfaceId} but a ${interfaceView.interfaceId}: ${JSON.stringify(createdEvent)}`);
70
+ return interfaceView;
89
71
  }
90
72
  function mergeMetas(event, extra) {
91
- const choiceArgument = event.choiceArgument;
92
- const lastWriteWins = [
93
- choiceArgument?.transfer?.meta,
94
- choiceArgument?.extraArgs?.meta,
95
- choiceArgument?.meta,
96
- extra,
97
- event.exerciseResult?.meta
98
- ];
99
- const result = {};
100
- lastWriteWins.forEach((meta) => {
101
- const values = meta?.values || {};
102
- Object.entries(values).forEach(([k, v]) => {
103
- result[k] = v;
104
- });
105
- });
106
- if (Object.keys(result).length === 0) {
107
- return void 0;
108
- } else {
109
- return { values: result };
110
- }
73
+ const choiceArgument = event.choiceArgument;
74
+ const lastWriteWins = [
75
+ choiceArgument?.transfer?.meta,
76
+ choiceArgument?.extraArgs?.meta,
77
+ choiceArgument?.meta,
78
+ extra,
79
+ event.exerciseResult?.meta
80
+ ];
81
+ const result = {};
82
+ lastWriteWins.forEach((meta) => {
83
+ const values = meta?.values || {};
84
+ Object.entries(values).forEach(([k, v]) => {
85
+ result[k] = v;
86
+ });
87
+ });
88
+ if (Object.keys(result).length === 0) return;
89
+ else return { values: result };
111
90
  }
112
91
  function getMetaKeyValue(key, meta) {
113
- return (meta?.values || {})[key] || null;
92
+ return (meta?.values || {})[key] || null;
114
93
  }
94
+ /**
95
+ * From the view of making it easy to build the display for the wallet,
96
+ * we remove all metadata fields that were fully parsed, and whose content is reflected in the TypeScript structure.
97
+ * Otherwise, the display code has to do so, overloading the user with superfluous metadata entries.
98
+ */
115
99
  function removeParsedMetaKeys(meta) {
116
- return {
117
- values: Object.fromEntries(
118
- Object.entries(meta?.values || {}).filter(
119
- ([k]) => !AllKnownMetaKeys.includes(k)
120
- )
121
- )
122
- };
100
+ return { values: Object.fromEntries(Object.entries(meta?.values || {}).filter(([k]) => !AllKnownMetaKeys.includes(k))) };
123
101
  }
124
-
125
- // src/types.ts
126
- var renderTransaction = (t) => {
127
- return { ...t, events: t.events.map(renderTransactionEvent) };
102
+ //#endregion
103
+ //#region src/types.ts
104
+ const renderTransaction = (t) => {
105
+ return {
106
+ ...t,
107
+ events: t.events.map(renderTransactionEvent)
108
+ };
128
109
  };
129
- var renderTransactionEvent = (e) => {
130
- const lockedHoldingsChangeSummaries = e.lockedHoldingsChangeSummaries.map(renderHoldingsChangeSummary).filter((s) => s !== null);
131
- const unlockedHoldingsChangeSummaries = e.unlockedHoldingsChangeSummaries.map(renderHoldingsChangeSummary).filter((s) => s !== null);
132
- const lockedHoldingsChange = renderHoldingsChange(e.lockedHoldingsChange);
133
- const unlockedHoldingsChange = renderHoldingsChange(
134
- e.unlockedHoldingsChange
135
- );
136
- return {
137
- ...e,
138
- lockedHoldingsChange,
139
- unlockedHoldingsChange,
140
- lockedHoldingsChangeSummaries,
141
- // Deprecated
142
- lockedHoldingsChangeSummary: renderHoldingsChangeSummary(
143
- e.lockedHoldingsChangeSummary
144
- ),
145
- unlockedHoldingsChangeSummaries,
146
- // Deprecated
147
- unlockedHoldingsChangeSummary: renderHoldingsChangeSummary(
148
- e.unlockedHoldingsChangeSummary
149
- )
150
- };
110
+ const renderTransactionEvent = (e) => {
111
+ const lockedHoldingsChangeSummaries = e.lockedHoldingsChangeSummaries.map(renderHoldingsChangeSummary).filter((s) => s !== null);
112
+ const unlockedHoldingsChangeSummaries = e.unlockedHoldingsChangeSummaries.map(renderHoldingsChangeSummary).filter((s) => s !== null);
113
+ const lockedHoldingsChange = renderHoldingsChange(e.lockedHoldingsChange);
114
+ const unlockedHoldingsChange = renderHoldingsChange(e.unlockedHoldingsChange);
115
+ return {
116
+ ...e,
117
+ lockedHoldingsChange,
118
+ unlockedHoldingsChange,
119
+ lockedHoldingsChangeSummaries,
120
+ lockedHoldingsChangeSummary: renderHoldingsChangeSummary(e.lockedHoldingsChangeSummary),
121
+ unlockedHoldingsChangeSummaries,
122
+ unlockedHoldingsChangeSummary: renderHoldingsChangeSummary(e.unlockedHoldingsChangeSummary)
123
+ };
151
124
  };
152
- var renderHoldingsChangeSummary = (s) => {
153
- if (s.numInputs === 0 && s.numOutputs === 0 && s.inputAmount === "0" && s.outputAmount === "0" && s.amountChange === "0") {
154
- return null;
155
- }
156
- return {
157
- ...(s.instrumentId.admin !== "" || s.instrumentId.id !== "") && {
158
- instrumentId: s.instrumentId
159
- },
160
- ...s.numInputs !== 0 && { numInputs: s.numInputs },
161
- ...s.inputAmount !== "0" && { inputAmount: s.inputAmount },
162
- ...s.numOutputs !== 0 && { numOutputs: s.numOutputs },
163
- ...s.outputAmount !== "0" && { outputAmount: s.outputAmount },
164
- ...s.amountChange !== "0" && { amountChange: s.amountChange }
165
- };
125
+ const renderHoldingsChangeSummary = (s) => {
126
+ if (s.numInputs === 0 && s.numOutputs === 0 && s.inputAmount === "0" && s.outputAmount === "0" && s.amountChange === "0") return null;
127
+ return {
128
+ ...(s.instrumentId.admin !== "" || s.instrumentId.id !== "") && { instrumentId: s.instrumentId },
129
+ ...s.numInputs !== 0 && { numInputs: s.numInputs },
130
+ ...s.inputAmount !== "0" && { inputAmount: s.inputAmount },
131
+ ...s.numOutputs !== 0 && { numOutputs: s.numOutputs },
132
+ ...s.outputAmount !== "0" && { outputAmount: s.outputAmount },
133
+ ...s.amountChange !== "0" && { amountChange: s.amountChange }
134
+ };
166
135
  };
167
- var renderHoldingsChange = (c) => {
168
- if (c.creates.length === 0 && c.archives.length === 0) {
169
- return null;
170
- }
171
- return {
172
- ...c.creates.length !== 0 && { creates: c.creates },
173
- ...c.archives.length !== 0 && { archives: c.archives }
174
- };
136
+ const renderHoldingsChange = (c) => {
137
+ if (c.creates.length === 0 && c.archives.length === 0) return null;
138
+ return {
139
+ ...c.creates.length !== 0 && { creates: c.creates },
140
+ ...c.archives.length !== 0 && { archives: c.archives }
141
+ };
175
142
  };
176
-
177
- // src/instrumentmap.ts
143
+ //#endregion
144
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/typeof.js
145
+ function _typeof(o) {
146
+ "@babel/helpers - typeof";
147
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
148
+ return typeof o;
149
+ } : function(o) {
150
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
151
+ }, _typeof(o);
152
+ }
153
+ //#endregion
154
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPrimitive.js
155
+ function toPrimitive(t, r) {
156
+ if ("object" != _typeof(t) || !t) return t;
157
+ var e = t[Symbol.toPrimitive];
158
+ if (void 0 !== e) {
159
+ var i = e.call(t, r || "default");
160
+ if ("object" != _typeof(i)) return i;
161
+ throw new TypeError("@@toPrimitive must return a primitive value.");
162
+ }
163
+ return ("string" === r ? String : Number)(t);
164
+ }
165
+ //#endregion
166
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPropertyKey.js
167
+ function toPropertyKey(t) {
168
+ var i = toPrimitive(t, "string");
169
+ return "symbol" == _typeof(i) ? i : i + "";
170
+ }
171
+ //#endregion
172
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/defineProperty.js
173
+ function _defineProperty(e, r, t) {
174
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
175
+ value: t,
176
+ enumerable: !0,
177
+ configurable: !0,
178
+ writable: !0
179
+ }) : e[r] = t, e;
180
+ }
181
+ //#endregion
182
+ //#region src/instrumentmap.ts
183
+ /** InstrumentMap is a helper for when you want to group values by instrument. */
178
184
  var InstrumentMap = class {
179
- constructor() {
180
- __publicField(this, "map");
181
- this.map = /* @__PURE__ */ new Map();
182
- }
183
- encodeKey(instrumentId) {
184
- return JSON.stringify([instrumentId.admin, instrumentId.id]);
185
- }
186
- decodeKey(key) {
187
- const [admin, id] = JSON.parse(key);
188
- return { admin, id };
189
- }
190
- set(key, value) {
191
- this.map.set(this.encodeKey(key), value);
192
- }
193
- get(key) {
194
- return this.map.get(this.encodeKey(key));
195
- }
196
- has(key) {
197
- return this.map.has(this.encodeKey(key));
198
- }
199
- delete(key) {
200
- return this.map.delete(this.encodeKey(key));
201
- }
202
- *entries() {
203
- for (const [key, value] of this.map.entries()) {
204
- yield [this.decodeKey(key), value];
205
- }
206
- }
185
+ encodeKey(instrumentId) {
186
+ return JSON.stringify([instrumentId.admin, instrumentId.id]);
187
+ }
188
+ decodeKey(key) {
189
+ const [admin, id] = JSON.parse(key);
190
+ return {
191
+ admin,
192
+ id
193
+ };
194
+ }
195
+ constructor() {
196
+ _defineProperty(this, "map", void 0);
197
+ this.map = /* @__PURE__ */ new Map();
198
+ }
199
+ set(key, value) {
200
+ this.map.set(this.encodeKey(key), value);
201
+ }
202
+ get(key) {
203
+ return this.map.get(this.encodeKey(key));
204
+ }
205
+ has(key) {
206
+ return this.map.has(this.encodeKey(key));
207
+ }
208
+ delete(key) {
209
+ return this.map.delete(this.encodeKey(key));
210
+ }
211
+ *entries() {
212
+ for (const [key, value] of this.map.entries()) yield [this.decodeKey(key), value];
213
+ }
207
214
  };
215
+ //#endregion
216
+ //#region src/parser.ts
208
217
  function currentStatusFromChoiceOrResult(choice, resultTag) {
209
- if (resultTag === "TransferInstructionResult_Failed") return "Failed";
210
- if (resultTag === "TransferInstructionResult_Completed") return "Completed";
211
- switch (choice) {
212
- case "TransferInstruction_Reject":
213
- return "Rejected";
214
- case "TransferInstruction_Withdraw":
215
- return "Withdrawn";
216
- case "TransferInstruction_Accept":
217
- case "TransferInstruction_Update":
218
- return "Pending";
219
- default:
220
- return "Pending";
221
- }
218
+ if (resultTag === "TransferInstructionResult_Failed") return "Failed";
219
+ if (resultTag === "TransferInstructionResult_Completed") return "Completed";
220
+ switch (choice) {
221
+ case "TransferInstruction_Reject": return "Rejected";
222
+ case "TransferInstruction_Withdraw": return "Withdrawn";
223
+ case "TransferInstruction_Accept":
224
+ case "TransferInstruction_Update": return "Pending";
225
+ default: return "Pending";
226
+ }
222
227
  }
223
228
  function getCorrelationIdFromTransferInstruction(currentInstructionCid, originalInstructionCid) {
224
- return originalInstructionCid ?? currentInstructionCid;
229
+ return originalInstructionCid ?? currentInstructionCid;
225
230
  }
226
231
  function getPendingTransferInstructionCid(exercisedEvent) {
227
- const output = exercisedEvent.exerciseResult?.output;
228
- if (output?.tag !== "TransferInstructionResult_Pending") return void 0;
229
- const cid = output.value?.transferInstructionCid;
230
- return cid ?? void 0;
232
+ const output = exercisedEvent.exerciseResult?.output;
233
+ if (output?.tag !== "TransferInstructionResult_Pending") return void 0;
234
+ return output.value?.transferInstructionCid ?? void 0;
231
235
  }
232
236
  function isTransferObject(value) {
233
- if (!value || typeof value !== "object") return false;
234
- const v = value;
235
- const instrumentId = v.instrumentId;
236
- const meta = v.meta;
237
- return typeof v.sender === "string" && typeof v.receiver === "string" && typeof v.amount === "string" && typeof v.requestedAt === "string" && typeof v.executeBefore === "string" && Array.isArray(v.inputHoldingCids) && v.inputHoldingCids.every((cid) => typeof cid === "string") && !!instrumentId && typeof instrumentId.admin === "string" && typeof instrumentId.id === "string" && !!meta && typeof meta.values === "object" && meta.values !== null;
237
+ if (!value || typeof value !== "object") return false;
238
+ const v = value;
239
+ const instrumentId = v.instrumentId;
240
+ const meta = v.meta;
241
+ return typeof v.sender === "string" && typeof v.receiver === "string" && typeof v.amount === "string" && typeof v.requestedAt === "string" && typeof v.executeBefore === "string" && Array.isArray(v.inputHoldingCids) && v.inputHoldingCids.every((cid) => typeof cid === "string") && !!instrumentId && typeof instrumentId.admin === "string" && typeof instrumentId.id === "string" && !!meta && typeof meta.values === "object" && meta.values !== null;
238
242
  }
239
243
  var TransactionParser = class {
240
- constructor(ledgerProvider, transaction, partyId, isMasterUser) {
241
- __publicField(this, "ledgerProvider");
242
- __publicField(this, "partyId");
243
- __publicField(this, "transaction");
244
- __publicField(this, "isMasterUser");
245
- this.ledgerProvider = ledgerProvider;
246
- this.partyId = partyId;
247
- this.transaction = transaction;
248
- this.isMasterUser = isMasterUser;
249
- }
250
- async parseTransaction() {
251
- const tx = this.transaction;
252
- const events = await this.parseEvents([...tx.events || []].reverse());
253
- return {
254
- updateId: tx.updateId,
255
- offset: tx.offset,
256
- recordTime: tx.recordTime,
257
- synchronizerId: tx.synchronizerId,
258
- events
259
- };
260
- }
261
- async parseTransferObjects() {
262
- const eventsStack = [...this.transaction.events || []].reverse();
263
- const results = await this.fetchTransferObjectChoice(eventsStack);
264
- return results;
265
- }
266
- async fetchTransferObjectChoice(eventsStack) {
267
- const result = [];
268
- while (eventsStack.length > 0) {
269
- const currentEvent = eventsStack.pop();
270
- const { exercisedEvent } = getNodeIdAndEvent(currentEvent);
271
- if (exercisedEvent && (exercisedEvent.choice === "TransferFactory_Transfer" || exercisedEvent.choice === "TransferRule_Transfer")) {
272
- const { choiceArgument } = exercisedEvent;
273
- if (choiceArgument && typeof choiceArgument === "object" && "transfer" in choiceArgument) {
274
- const transfer = choiceArgument.transfer;
275
- if (isTransferObject(transfer)) {
276
- result.push(transfer);
277
- }
278
- }
279
- }
280
- }
281
- return result;
282
- }
283
- async parseEvents(eventsStack) {
284
- let callStack = [];
285
- let continueAfterNodeId = -1;
286
- const result = [];
287
- while (eventsStack.length > 0) {
288
- const currentEvent = eventsStack.pop();
289
- const { nodeId, createdEvent, archivedEvent, exercisedEvent } = getNodeIdAndEvent(currentEvent);
290
- callStack = callStack.filter((s) => s.untilNodeId <= nodeId);
291
- const parentChoice = callStack[callStack.length - 1] && callStack[callStack.length - 1].parentChoiceName || "none (root node)";
292
- let parsed;
293
- if (nodeId <= continueAfterNodeId) {
294
- parsed = null;
295
- } else if (createdEvent) {
296
- parsed = this.parseRawCreate(createdEvent, parentChoice);
297
- } else if (archivedEvent) {
298
- parsed = await this.parseRawArchive(archivedEvent, parentChoice);
299
- } else if (exercisedEvent) {
300
- parsed = await this.parseExercise(exercisedEvent);
301
- } else {
302
- throw new Error(
303
- `Impossible event: ${JSON.stringify(currentEvent)}`
304
- );
305
- }
306
- if (parsed && isLeafEventNode(parsed)) {
307
- if (holdingChangesNonEmpty(parsed.event)) {
308
- result.push({
309
- ...parsed.event,
310
- label: {
311
- ...parsed.event.label,
312
- meta: removeParsedMetaKeys(parsed.event.label.meta)
313
- }
314
- });
315
- }
316
- continueAfterNodeId = parsed.continueAfterNodeId;
317
- } else if (parsed) {
318
- callStack.push({
319
- parentChoiceName: parsed.parentChoiceName,
320
- untilNodeId: parsed.lastDescendantNodeId
321
- });
322
- }
323
- }
324
- return result;
325
- }
326
- parseRawCreate(create, parentChoice) {
327
- return this.buildRawEvent(create, create.nodeId, (result) => {
328
- return {
329
- // TODO: this code currently only looks at the first instrument
330
- // to determine the type of the Event.
331
- type: Number(
332
- result.lockedHoldingsChangeSummaries[0]?.amountChange
333
- ) > 0 ? "Lock" : "Create",
334
- parentChoice,
335
- contractId: create.contractId,
336
- offset: create.offset,
337
- templateId: create.templateId,
338
- payload: result.payload,
339
- packageName: create.packageName,
340
- meta: void 0
341
- };
342
- });
343
- }
344
- async parseRawArchive(archive, parentChoice) {
345
- const events = await this.getEventsForArchive(archive);
346
- if (!events) {
347
- return null;
348
- }
349
- return this.buildRawEvent(
350
- events.created.createdEvent,
351
- archive.nodeId,
352
- (result) => {
353
- return {
354
- type: "Archive",
355
- parentChoice,
356
- contractId: archive.contractId,
357
- offset: archive.offset,
358
- templateId: archive.templateId ?? "",
359
- packageName: archive.packageName,
360
- actingParties: archive.actingParties || [],
361
- payload: result.payload,
362
- meta: void 0
363
- };
364
- }
365
- );
366
- }
367
- buildRawEvent(originalCreate, nodeId, buildLabel) {
368
- const view = getKnownInterfaceView(originalCreate);
369
- let result;
370
- switch (view?.type) {
371
- case "Holding": {
372
- const holdingView = view.viewValue;
373
- if (this.partyId !== holdingView.owner) {
374
- result = null;
375
- } else {
376
- const isLocked = !!holdingView.lock;
377
- const summary = {
378
- instrumentId: holdingView.instrumentId,
379
- amountChange: holdingView.amount,
380
- numInputs: 0,
381
- inputAmount: "0",
382
- numOutputs: 1,
383
- outputAmount: holdingView.amount
384
- };
385
- const lockedHoldingsChangeSummaries = isLocked ? [summary] : [];
386
- const unlockedHoldingsChangeSummaries = isLocked ? [] : [summary];
387
- result = {
388
- payload: holdingView,
389
- unlockedHoldingsChange: {
390
- creates: isLocked ? [] : [holdingView],
391
- archives: []
392
- },
393
- lockedHoldingsChange: {
394
- creates: isLocked ? [holdingView] : [],
395
- archives: []
396
- },
397
- lockedHoldingsChangeSummaries,
398
- lockedHoldingsChangeSummary: lockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
399
- unlockedHoldingsChangeSummaries,
400
- unlockedHoldingsChangeSummary: unlockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
401
- transferInstruction: null
402
- };
403
- }
404
- break;
405
- }
406
- case "TransferInstruction": {
407
- const transferInstructionView = view.viewValue;
408
- if (![
409
- transferInstructionView.transfer.sender,
410
- transferInstructionView.transfer.receiver
411
- ].some((stakeholder) => stakeholder === this.partyId)) {
412
- result = null;
413
- } else {
414
- const multiStepCorrelationId = getCorrelationIdFromTransferInstruction(
415
- originalCreate.contractId,
416
- transferInstructionView.originalInstructionCid ?? null
417
- );
418
- result = {
419
- payload: transferInstructionView,
420
- transferInstruction: {
421
- originalInstructionCid: transferInstructionView.originalInstructionCid,
422
- transfer: transferInstructionView.transfer,
423
- meta: transferInstructionView.meta,
424
- status: {
425
- before: transferInstructionView.status,
426
- // raw DAML pending sub-state
427
- current: { tag: "Pending", value: {} }
428
- // normalized
429
- },
430
- multiStepCorrelationId
431
- },
432
- unlockedHoldingsChange: { creates: [], archives: [] },
433
- lockedHoldingsChange: { creates: [], archives: [] },
434
- unlockedHoldingsChangeSummaries: [],
435
- unlockedHoldingsChangeSummary: emptyHoldingsChangeSummary,
436
- lockedHoldingsChangeSummaries: [],
437
- lockedHoldingsChangeSummary: emptyHoldingsChangeSummary
438
- };
439
- }
440
- break;
441
- }
442
- default:
443
- result = null;
444
- }
445
- return result && {
446
- continueAfterNodeId: nodeId,
447
- event: {
448
- label: buildLabel(result),
449
- unlockedHoldingsChange: result.unlockedHoldingsChange,
450
- lockedHoldingsChange: result.lockedHoldingsChange,
451
- lockedHoldingsChangeSummaries: result.lockedHoldingsChangeSummaries,
452
- lockedHoldingsChangeSummary: result.lockedHoldingsChangeSummary,
453
- unlockedHoldingsChangeSummaries: result.unlockedHoldingsChangeSummaries,
454
- unlockedHoldingsChangeSummary: result.unlockedHoldingsChangeSummary,
455
- transferInstruction: result.transferInstruction
456
- }
457
- };
458
- }
459
- async parseExercise(exercise) {
460
- let result = null;
461
- const tokenStandardChoice = {
462
- name: exercise.choice,
463
- choiceArgument: exercise.choiceArgument,
464
- exerciseResult: exercise.exerciseResult
465
- };
466
- switch (exercise.choice) {
467
- case "TransferRule_Transfer":
468
- case "TransferFactory_Transfer":
469
- result = await this.buildTransfer(exercise, tokenStandardChoice);
470
- break;
471
- case "TransferInstruction_Accept":
472
- case "TransferInstruction_Reject":
473
- case "TransferInstruction_Withdraw":
474
- case "TransferInstruction_Update":
475
- result = await this.buildFromTransferInstructionExercise(
476
- exercise,
477
- tokenStandardChoice
478
- );
479
- break;
480
- case "BurnMintFactory_BurnMint":
481
- result = await this.buildMergeSplit(
482
- exercise,
483
- tokenStandardChoice
484
- );
485
- break;
486
- default: {
487
- const meta = mergeMetas(exercise);
488
- const txKind = getMetaKeyValue(TxKindMetaKey, meta);
489
- if (txKind) {
490
- result = await this.parseViaTxKind(exercise, txKind);
491
- }
492
- break;
493
- }
494
- }
495
- if (!result) {
496
- return {
497
- lastDescendantNodeId: exercise.lastDescendantNodeId,
498
- parentChoiceName: exercise.choice
499
- };
500
- } else {
501
- const lockedHoldingsChange = {
502
- creates: result.children.creates.filter(
503
- (h) => !!h.lock && h.owner === this.partyId
504
- ),
505
- archives: result.children.archives.filter(
506
- (h) => !!h.lock && h.owner === this.partyId
507
- )
508
- };
509
- const unlockedHoldingsChange = {
510
- creates: result.children.creates.filter(
511
- (h) => !h.lock && h.owner === this.partyId
512
- ),
513
- archives: result.children.archives.filter(
514
- (h) => !h.lock && h.owner === this.partyId
515
- )
516
- };
517
- const lockedHoldingsChangeSummaries = computeSummaries(
518
- lockedHoldingsChange,
519
- this.partyId
520
- );
521
- const unlockedHoldingsChangeSummaries = computeSummaries(
522
- unlockedHoldingsChange,
523
- this.partyId
524
- );
525
- return {
526
- event: {
527
- label: result.label,
528
- lockedHoldingsChange,
529
- lockedHoldingsChangeSummaries,
530
- lockedHoldingsChangeSummary: lockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
531
- unlockedHoldingsChange,
532
- unlockedHoldingsChangeSummaries,
533
- unlockedHoldingsChangeSummary: unlockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
534
- transferInstruction: result.transferInstruction
535
- },
536
- continueAfterNodeId: exercise.lastDescendantNodeId
537
- };
538
- }
539
- }
540
- async parseViaTxKind(exercisedEvent, txKind) {
541
- switch (txKind) {
542
- case "transfer":
543
- return await this.buildTransfer(exercisedEvent, null);
544
- case "merge-split":
545
- case "burn":
546
- case "mint":
547
- return await this.buildMergeSplit(exercisedEvent, null);
548
- case "unlock":
549
- return await this.buildBasic(exercisedEvent, "Unlock", null);
550
- case "expire-dust":
551
- return await this.buildBasic(exercisedEvent, "ExpireDust", null);
552
- default:
553
- throw new Error(
554
- `Unknown tx-kind '${txKind}' in ${JSON.stringify(exercisedEvent)}`
555
- );
556
- }
557
- }
558
- async buildTransfer(exercisedEvent, tokenStandardChoice, transferInstructions) {
559
- const meta = mergeMetas(
560
- exercisedEvent,
561
- transferInstructions?.transfer?.meta
562
- );
563
- const reason = getMetaKeyValue(ReasonMetaKey, meta);
564
- const choiceArgumentTransfer = exercisedEvent.choiceArgument.transfer;
565
- const sender = transferInstructions?.transfer?.sender || getMetaKeyValue(SenderMetaKey, meta) || choiceArgumentTransfer.sender;
566
- if (!sender) {
567
- console.error(
568
- `Malformed transfer didn't contain sender. Will instead attempt to parse the children.
569
- Transfer: ${JSON.stringify(exercisedEvent)}`
570
- );
571
- return null;
572
- }
573
- const resultTag = exercisedEvent.exerciseResult?.output?.tag || void 0;
574
- const pendingCid = getPendingTransferInstructionCid(exercisedEvent);
575
- const currentTag = currentStatusFromChoiceOrResult(
576
- exercisedEvent.choice,
577
- resultTag
578
- );
579
- const children = await this.getChildren(exercisedEvent);
580
- const receiverAmounts = /* @__PURE__ */ new Map();
581
- children.creates.filter((h) => h.owner !== sender).forEach(
582
- (holding) => receiverAmounts.set(
583
- holding.owner,
584
- (receiverAmounts.get(holding.owner) || BigNumber("0")).plus(
585
- BigNumber(holding.amount)
586
- )
587
- )
588
- );
589
- const amountChanges = computeAmountChanges(children, meta, this.partyId);
590
- let label;
591
- if (receiverAmounts.size === 0) {
592
- label = {
593
- ...amountChanges,
594
- type: "MergeSplit",
595
- tokenStandardChoice,
596
- reason,
597
- meta
598
- };
599
- } else if (sender === this.partyId) {
600
- label = {
601
- ...amountChanges,
602
- type: "TransferOut",
603
- receiverAmounts: [...receiverAmounts].map(([k, v]) => {
604
- return { receiver: k, amount: v.toString() };
605
- }),
606
- tokenStandardChoice,
607
- reason,
608
- meta
609
- };
610
- } else {
611
- label = {
612
- type: "TransferIn",
613
- // for Transfers, the burn/mint is always 0 for the receiving party (i.e., 0 for TransferIn)
614
- burnAmount: "0",
615
- mintAmount: "0",
616
- sender,
617
- tokenStandardChoice,
618
- reason,
619
- meta
620
- };
621
- }
622
- if (transferInstructions) {
623
- transferInstructions.status.current = transferInstructions.status.current || { tag: currentTag, value: {} };
624
- return {
625
- label,
626
- children,
627
- transferInstruction: transferInstructions
628
- };
629
- }
630
- const transferInstruction = {
631
- originalInstructionCid: null,
632
- ...choiceArgumentTransfer !== void 0 && {
633
- transfer: choiceArgumentTransfer
634
- },
635
- status: {
636
- before: null,
637
- current: { tag: currentTag, value: {} }
638
- },
639
- meta: null,
640
- ...pendingCid ? { multiStepCorrelationId: pendingCid } : {}
641
- };
642
- return {
643
- label,
644
- children,
645
- transferInstruction
646
- };
647
- }
648
- async buildMergeSplit(exercisedEvent, tokenStandardChoice) {
649
- let type;
650
- const meta = mergeMetas(exercisedEvent);
651
- switch (getMetaKeyValue(TxKindMetaKey, meta)) {
652
- case "burn":
653
- type = "Burn";
654
- break;
655
- case "mint":
656
- type = "Mint";
657
- break;
658
- default:
659
- type = "MergeSplit";
660
- }
661
- const reason = getMetaKeyValue(ReasonMetaKey, meta);
662
- const children = await this.getChildren(exercisedEvent);
663
- const amountChanges = computeAmountChanges(children, meta, this.partyId);
664
- const label = {
665
- ...amountChanges,
666
- type,
667
- tokenStandardChoice,
668
- reason,
669
- meta
670
- };
671
- return {
672
- label,
673
- children,
674
- transferInstruction: null
675
- };
676
- }
677
- async buildFromTransferInstructionExercise(exercisedEvent, tokenStandardChoice) {
678
- const instructionCid = exercisedEvent.contractId;
679
- const transferInstructionEvents = await this.getEventsForArchive(exercisedEvent);
680
- if (!transferInstructionEvents) {
681
- return null;
682
- }
683
- const transferInstructionView = ensureInterfaceViewIsPresent(
684
- transferInstructionEvents.created.createdEvent,
685
- TRANSFER_INSTRUCTION_INTERFACE_ID
686
- ).viewValue;
687
- const multiStepCorrelationId = getCorrelationIdFromTransferInstruction(
688
- instructionCid,
689
- transferInstructionView.originalInstructionCid ?? null
690
- );
691
- const resultTag = exercisedEvent.exerciseResult?.output?.tag || void 0;
692
- const currentTag = currentStatusFromChoiceOrResult(
693
- exercisedEvent.choice,
694
- resultTag
695
- );
696
- const transferInstruction = {
697
- originalInstructionCid: transferInstructionView.originalInstructionCid,
698
- multiStepCorrelationId,
699
- transfer: transferInstructionView.transfer,
700
- meta: transferInstructionView.meta,
701
- status: {
702
- before: transferInstructionView.status,
703
- current: { tag: currentTag, value: {} }
704
- }
705
- };
706
- const exerciseResultOutputTag = resultTag;
707
- const result = await (async () => {
708
- switch (exerciseResultOutputTag) {
709
- case "TransferInstructionResult_Failed":
710
- case "TransferInstructionResult_Pending":
711
- return this.buildMergeSplit(
712
- exercisedEvent,
713
- tokenStandardChoice
714
- );
715
- case "TransferInstructionResult_Completed":
716
- return this.buildTransfer(
717
- exercisedEvent,
718
- tokenStandardChoice,
719
- transferInstruction
720
- );
721
- default:
722
- throw new Error(
723
- `Unknown TransferInstructionResult: ${exerciseResultOutputTag}`
724
- );
725
- }
726
- })();
727
- return result && {
728
- ...result,
729
- transferInstruction
730
- };
731
- }
732
- async buildBasic(exercisedEvent, type, tokenStandardChoice) {
733
- const children = await this.getChildren(exercisedEvent);
734
- const meta = mergeMetas(exercisedEvent);
735
- const amountChanges = computeAmountChanges(children, meta, this.partyId);
736
- const reason = getMetaKeyValue(ReasonMetaKey, meta);
737
- return {
738
- label: {
739
- ...amountChanges,
740
- type,
741
- tokenStandardChoice,
742
- reason,
743
- meta
744
- },
745
- children,
746
- transferInstruction: null
747
- };
748
- }
749
- async getChildren(exercisedEvent) {
750
- const mutatingResult = { creates: [], archives: [] };
751
- const childrenEventsSlice = (this.transaction.events || []).map(getNodeIdAndEvent).filter(
752
- ({ nodeId }) => nodeId > exercisedEvent.nodeId && nodeId <= exercisedEvent.lastDescendantNodeId
753
- );
754
- if (exercisedEvent.consuming && hasInterface(HOLDING_INTERFACE_ID, exercisedEvent)) {
755
- const selfEvent = await this.getEventsForArchive(exercisedEvent);
756
- if (selfEvent) {
757
- const holdingView = ensureInterfaceViewIsPresent(
758
- selfEvent.created.createdEvent,
759
- HOLDING_INTERFACE_ID
760
- ).viewValue;
761
- mutatingResult.archives.push({
762
- amount: holdingView.amount,
763
- instrumentId: holdingView.instrumentId,
764
- contractId: exercisedEvent.contractId,
765
- owner: holdingView.owner,
766
- meta: holdingView.meta,
767
- lock: holdingView.lock
768
- });
769
- }
770
- }
771
- for (const {
772
- createdEvent,
773
- archivedEvent,
774
- exercisedEvent: exercisedEvent2
775
- } of childrenEventsSlice) {
776
- if (createdEvent) {
777
- const interfaceView = getInterfaceView(createdEvent);
778
- if (interfaceView && interfaceView.interfaceId && matchInterfaceIds(
779
- HOLDING_INTERFACE_ID,
780
- interfaceView.interfaceId
781
- )) {
782
- const holdingView = interfaceView.viewValue;
783
- mutatingResult.creates.push({
784
- amount: holdingView.amount,
785
- instrumentId: holdingView.instrumentId,
786
- contractId: createdEvent.contractId,
787
- owner: holdingView.owner,
788
- meta: holdingView.meta,
789
- lock: holdingView.lock
790
- });
791
- }
792
- } else if (archivedEvent && hasInterface(HOLDING_INTERFACE_ID, archivedEvent) || exercisedEvent2 && exercisedEvent2.consuming && hasInterface(HOLDING_INTERFACE_ID, exercisedEvent2)) {
793
- const contractEvents = await this.getEventsForArchive(
794
- archivedEvent || exercisedEvent2
795
- );
796
- if (contractEvents) {
797
- const holdingView = ensureInterfaceViewIsPresent(
798
- contractEvents.created?.createdEvent,
799
- HOLDING_INTERFACE_ID
800
- ).viewValue;
801
- mutatingResult.archives.push({
802
- amount: holdingView.amount,
803
- instrumentId: holdingView.instrumentId,
804
- contractId: archivedEvent?.contractId || exercisedEvent2.contractId,
805
- owner: holdingView.owner,
806
- meta: holdingView.meta,
807
- lock: holdingView.lock
808
- });
809
- }
810
- }
811
- }
812
- return {
813
- // remove transient contracts
814
- creates: mutatingResult.creates.filter(
815
- (create) => !mutatingResult.archives.some(
816
- (archive) => create.contractId === archive.contractId
817
- )
818
- ),
819
- archives: mutatingResult.archives.filter(
820
- (archive) => !mutatingResult.creates.some(
821
- (create) => create.contractId === archive.contractId
822
- )
823
- )
824
- };
825
- }
826
- async getEventsForArchive(archivedEvent) {
827
- if (!(archivedEvent.witnessParties || []).includes(this.partyId)) {
828
- return null;
829
- }
830
- const basePayload = {
831
- contractId: archivedEvent.contractId,
832
- eventFormat: EventFilterBySetup({
833
- interfaceIds: [
834
- HOLDING_INTERFACE_ID,
835
- TRANSFER_INSTRUCTION_INTERFACE_ID
836
- ],
837
- isMasterUser: this.isMasterUser,
838
- partyId: this.partyId,
839
- verbose: true
840
- })
841
- };
842
- const events = await this.ledgerProvider.request({
843
- method: "ledgerApi",
844
- params: {
845
- resource: "/v2/events/events-by-contract-id",
846
- requestMethod: "post",
847
- body: basePayload
848
- }
849
- }).catch((err) => {
850
- if (err.code === "CONTRACT_EVENTS_NOT_FOUND") {
851
- return null;
852
- } else {
853
- throw err;
854
- }
855
- });
856
- if (!events) {
857
- return null;
858
- }
859
- const created = events.created;
860
- const archived = events.archived;
861
- if (!created || !archived) {
862
- throw new Error(
863
- `Archival of ${archivedEvent.contractId} does not have a corresponding create/archive event: ${JSON.stringify(
864
- events
865
- )}`
866
- );
867
- }
868
- return { created, archived };
869
- }
244
+ constructor(ledgerProvider, transaction, partyId, isMasterUser) {
245
+ _defineProperty(this, "ledgerProvider", void 0);
246
+ _defineProperty(this, "partyId", void 0);
247
+ _defineProperty(this, "transaction", void 0);
248
+ _defineProperty(this, "isMasterUser", void 0);
249
+ this.ledgerProvider = ledgerProvider;
250
+ this.partyId = partyId;
251
+ this.transaction = transaction;
252
+ this.isMasterUser = isMasterUser;
253
+ }
254
+ async parseTransaction() {
255
+ const tx = this.transaction;
256
+ const events = await this.parseEvents([...tx.events || []].reverse());
257
+ return {
258
+ updateId: tx.updateId,
259
+ offset: tx.offset,
260
+ recordTime: tx.recordTime,
261
+ synchronizerId: tx.synchronizerId,
262
+ events
263
+ };
264
+ }
265
+ async parseTransferObjects() {
266
+ const eventsStack = [...this.transaction.events || []].reverse();
267
+ return await this.fetchTransferObjectChoice(eventsStack);
268
+ }
269
+ async fetchTransferObjectChoice(eventsStack) {
270
+ const result = [];
271
+ while (eventsStack.length > 0) {
272
+ const { exercisedEvent } = getNodeIdAndEvent(eventsStack.pop());
273
+ if (exercisedEvent && (exercisedEvent.choice === "TransferFactory_Transfer" || exercisedEvent.choice === "TransferRule_Transfer")) {
274
+ const { choiceArgument } = exercisedEvent;
275
+ if (choiceArgument && typeof choiceArgument === "object" && "transfer" in choiceArgument) {
276
+ const transfer = choiceArgument.transfer;
277
+ if (isTransferObject(transfer)) result.push(transfer);
278
+ }
279
+ }
280
+ }
281
+ return result;
282
+ }
283
+ async parseEvents(eventsStack) {
284
+ let callStack = [];
285
+ let continueAfterNodeId = -1;
286
+ const result = [];
287
+ while (eventsStack.length > 0) {
288
+ const currentEvent = eventsStack.pop();
289
+ const { nodeId, createdEvent, archivedEvent, exercisedEvent } = getNodeIdAndEvent(currentEvent);
290
+ callStack = callStack.filter((s) => s.untilNodeId <= nodeId);
291
+ const parentChoice = callStack[callStack.length - 1] && callStack[callStack.length - 1].parentChoiceName || "none (root node)";
292
+ let parsed;
293
+ if (nodeId <= continueAfterNodeId) parsed = null;
294
+ else if (createdEvent) parsed = this.parseRawCreate(createdEvent, parentChoice);
295
+ else if (archivedEvent) parsed = await this.parseRawArchive(archivedEvent, parentChoice);
296
+ else if (exercisedEvent) parsed = await this.parseExercise(exercisedEvent);
297
+ else throw new Error(`Impossible event: ${JSON.stringify(currentEvent)}`);
298
+ if (parsed && isLeafEventNode(parsed)) {
299
+ if (holdingChangesNonEmpty(parsed.event) || parsed.event.transferInstruction?.transfer != null) result.push({
300
+ ...parsed.event,
301
+ label: {
302
+ ...parsed.event.label,
303
+ meta: removeParsedMetaKeys(parsed.event.label.meta)
304
+ }
305
+ });
306
+ continueAfterNodeId = parsed.continueAfterNodeId;
307
+ } else if (parsed) callStack.push({
308
+ parentChoiceName: parsed.parentChoiceName,
309
+ untilNodeId: parsed.lastDescendantNodeId
310
+ });
311
+ }
312
+ return result;
313
+ }
314
+ parseRawCreate(create, parentChoice) {
315
+ return this.buildRawEvent(create, create.nodeId, (result) => {
316
+ return {
317
+ type: Number(result.lockedHoldingsChangeSummaries[0]?.amountChange) > 0 ? "Lock" : "Create",
318
+ parentChoice,
319
+ contractId: create.contractId,
320
+ offset: create.offset,
321
+ templateId: create.templateId,
322
+ payload: result.payload,
323
+ packageName: create.packageName,
324
+ meta: void 0
325
+ };
326
+ });
327
+ }
328
+ async parseRawArchive(archive, parentChoice) {
329
+ const events = await this.getEventsForArchive(archive);
330
+ if (!events) return null;
331
+ return this.buildRawEvent(events.created.createdEvent, archive.nodeId, (result) => {
332
+ return {
333
+ type: "Archive",
334
+ parentChoice,
335
+ contractId: archive.contractId,
336
+ offset: archive.offset,
337
+ templateId: archive.templateId ?? "",
338
+ packageName: archive.packageName,
339
+ actingParties: archive.actingParties || [],
340
+ payload: result.payload,
341
+ meta: void 0
342
+ };
343
+ });
344
+ }
345
+ buildRawEvent(originalCreate, nodeId, buildLabel) {
346
+ const view = getKnownInterfaceView(originalCreate);
347
+ let result;
348
+ switch (view?.type) {
349
+ case "Holding": {
350
+ const holdingView = view.viewValue;
351
+ if (this.partyId !== holdingView.owner) result = null;
352
+ else {
353
+ const isLocked = !!holdingView.lock;
354
+ const summary = {
355
+ instrumentId: holdingView.instrumentId,
356
+ amountChange: holdingView.amount,
357
+ numInputs: 0,
358
+ inputAmount: "0",
359
+ numOutputs: 1,
360
+ outputAmount: holdingView.amount
361
+ };
362
+ const lockedHoldingsChangeSummaries = isLocked ? [summary] : [];
363
+ const unlockedHoldingsChangeSummaries = isLocked ? [] : [summary];
364
+ result = {
365
+ payload: holdingView,
366
+ unlockedHoldingsChange: {
367
+ creates: isLocked ? [] : [holdingView],
368
+ archives: []
369
+ },
370
+ lockedHoldingsChange: {
371
+ creates: isLocked ? [holdingView] : [],
372
+ archives: []
373
+ },
374
+ lockedHoldingsChangeSummaries,
375
+ lockedHoldingsChangeSummary: lockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
376
+ unlockedHoldingsChangeSummaries,
377
+ unlockedHoldingsChangeSummary: unlockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
378
+ transferInstruction: null
379
+ };
380
+ }
381
+ break;
382
+ }
383
+ case "TransferInstruction": {
384
+ const transferInstructionView = view.viewValue;
385
+ if (![transferInstructionView.transfer.sender, transferInstructionView.transfer.receiver].some((stakeholder) => stakeholder === this.partyId)) result = null;
386
+ else {
387
+ const multiStepCorrelationId = getCorrelationIdFromTransferInstruction(originalCreate.contractId, transferInstructionView.originalInstructionCid ?? null);
388
+ result = {
389
+ payload: transferInstructionView,
390
+ transferInstruction: {
391
+ originalInstructionCid: transferInstructionView.originalInstructionCid,
392
+ transfer: transferInstructionView.transfer,
393
+ meta: transferInstructionView.meta,
394
+ status: {
395
+ before: transferInstructionView.status,
396
+ current: {
397
+ tag: "Pending",
398
+ value: {}
399
+ }
400
+ },
401
+ multiStepCorrelationId
402
+ },
403
+ unlockedHoldingsChange: {
404
+ creates: [],
405
+ archives: []
406
+ },
407
+ lockedHoldingsChange: {
408
+ creates: [],
409
+ archives: []
410
+ },
411
+ unlockedHoldingsChangeSummaries: [],
412
+ unlockedHoldingsChangeSummary: emptyHoldingsChangeSummary,
413
+ lockedHoldingsChangeSummaries: [],
414
+ lockedHoldingsChangeSummary: emptyHoldingsChangeSummary
415
+ };
416
+ }
417
+ break;
418
+ }
419
+ default: result = null;
420
+ }
421
+ return result && {
422
+ continueAfterNodeId: nodeId,
423
+ event: {
424
+ label: buildLabel(result),
425
+ unlockedHoldingsChange: result.unlockedHoldingsChange,
426
+ lockedHoldingsChange: result.lockedHoldingsChange,
427
+ lockedHoldingsChangeSummaries: result.lockedHoldingsChangeSummaries,
428
+ lockedHoldingsChangeSummary: result.lockedHoldingsChangeSummary,
429
+ unlockedHoldingsChangeSummaries: result.unlockedHoldingsChangeSummaries,
430
+ unlockedHoldingsChangeSummary: result.unlockedHoldingsChangeSummary,
431
+ transferInstruction: result.transferInstruction
432
+ }
433
+ };
434
+ }
435
+ async parseExercise(exercise) {
436
+ let result = null;
437
+ const tokenStandardChoice = {
438
+ name: exercise.choice,
439
+ choiceArgument: exercise.choiceArgument,
440
+ exerciseResult: exercise.exerciseResult
441
+ };
442
+ switch (exercise.choice) {
443
+ case "TransferRule_Transfer":
444
+ case "TransferFactory_Transfer":
445
+ case "AllocationFactory_Allocate":
446
+ case "Allocation_ExecuteTransfer":
447
+ result = await this.buildTransfer(exercise, tokenStandardChoice);
448
+ break;
449
+ case "Allocation_Withdraw":
450
+ case "Allocation_Cancel":
451
+ result = await this.buildBasic(exercise, "Unlock", tokenStandardChoice);
452
+ break;
453
+ case "TransferInstruction_Accept":
454
+ case "TransferInstruction_Reject":
455
+ case "TransferInstruction_Withdraw":
456
+ case "TransferInstruction_Update":
457
+ result = await this.buildFromTransferInstructionExercise(exercise, tokenStandardChoice);
458
+ break;
459
+ case "BurnMintFactory_BurnMint":
460
+ result = await this.buildMergeSplit(exercise, tokenStandardChoice);
461
+ break;
462
+ default: {
463
+ const meta = mergeMetas(exercise);
464
+ const txKind = getMetaKeyValue(TxKindMetaKey, meta);
465
+ if (txKind) result = await this.parseViaTxKind(exercise, txKind);
466
+ break;
467
+ }
468
+ }
469
+ if (!result) return {
470
+ lastDescendantNodeId: exercise.lastDescendantNodeId,
471
+ parentChoiceName: exercise.choice
472
+ };
473
+ else {
474
+ const lockedHoldingsChange = {
475
+ creates: result.children.creates.filter((h) => !!h.lock && h.owner === this.partyId),
476
+ archives: result.children.archives.filter((h) => !!h.lock && h.owner === this.partyId)
477
+ };
478
+ const unlockedHoldingsChange = {
479
+ creates: result.children.creates.filter((h) => !h.lock && h.owner === this.partyId),
480
+ archives: result.children.archives.filter((h) => !h.lock && h.owner === this.partyId)
481
+ };
482
+ const lockedHoldingsChangeSummaries = computeSummaries(lockedHoldingsChange, this.partyId);
483
+ const unlockedHoldingsChangeSummaries = computeSummaries(unlockedHoldingsChange, this.partyId);
484
+ return {
485
+ event: {
486
+ label: result.label,
487
+ lockedHoldingsChange,
488
+ lockedHoldingsChangeSummaries,
489
+ lockedHoldingsChangeSummary: lockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
490
+ unlockedHoldingsChange,
491
+ unlockedHoldingsChangeSummaries,
492
+ unlockedHoldingsChangeSummary: unlockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
493
+ transferInstruction: result.transferInstruction
494
+ },
495
+ continueAfterNodeId: exercise.lastDescendantNodeId
496
+ };
497
+ }
498
+ }
499
+ async parseViaTxKind(exercisedEvent, txKind) {
500
+ switch (txKind) {
501
+ case "transfer": return await this.buildTransfer(exercisedEvent, null);
502
+ case "merge-split":
503
+ case "burn":
504
+ case "mint": return await this.buildMergeSplit(exercisedEvent, null);
505
+ case "unlock": return await this.buildBasic(exercisedEvent, "Unlock", null);
506
+ case "expire-dust": return await this.buildBasic(exercisedEvent, "ExpireDust", null);
507
+ default: throw new Error(`Unknown tx-kind '${txKind}' in ${JSON.stringify(exercisedEvent)}`);
508
+ }
509
+ }
510
+ async buildTransfer(exercisedEvent, tokenStandardChoice, transferInstructions) {
511
+ const meta = mergeMetas(exercisedEvent, transferInstructions?.transfer?.meta);
512
+ const reason = getMetaKeyValue(ReasonMetaKey, meta);
513
+ const rawTransferArg = exercisedEvent.choiceArgument.transfer;
514
+ const choiceArgumentTransfer = rawTransferArg?.receiver != null && rawTransferArg?.amount != null ? rawTransferArg : void 0;
515
+ const sender = transferInstructions?.transfer?.sender || getMetaKeyValue(SenderMetaKey, meta) || rawTransferArg?.sender;
516
+ if (!sender) {
517
+ console.error(`Malformed transfer didn't contain sender. Will instead attempt to parse the children.
518
+ Transfer: ${JSON.stringify(exercisedEvent)}`);
519
+ return null;
520
+ }
521
+ const resultTag = exercisedEvent.exerciseResult?.output?.tag || void 0;
522
+ const pendingCid = getPendingTransferInstructionCid(exercisedEvent);
523
+ const currentTag = currentStatusFromChoiceOrResult(exercisedEvent.choice, resultTag);
524
+ const children = await this.getChildren(exercisedEvent);
525
+ const receiverAmounts = /* @__PURE__ */ new Map();
526
+ children.creates.filter((h) => h.owner !== sender).forEach((holding) => receiverAmounts.set(holding.owner, (receiverAmounts.get(holding.owner) || BigNumber("0")).plus(BigNumber(holding.amount))));
527
+ const amountChanges = computeAmountChanges(children, meta, this.partyId);
528
+ let label;
529
+ if (receiverAmounts.size === 0) label = {
530
+ ...amountChanges,
531
+ type: "MergeSplit",
532
+ tokenStandardChoice,
533
+ reason,
534
+ meta
535
+ };
536
+ else if (sender === this.partyId) label = {
537
+ ...amountChanges,
538
+ type: "TransferOut",
539
+ receiverAmounts: [...receiverAmounts].map(([k, v]) => {
540
+ return {
541
+ receiver: k,
542
+ amount: v.toString()
543
+ };
544
+ }),
545
+ tokenStandardChoice,
546
+ reason,
547
+ meta
548
+ };
549
+ else label = {
550
+ type: "TransferIn",
551
+ burnAmount: "0",
552
+ mintAmount: "0",
553
+ sender,
554
+ tokenStandardChoice,
555
+ reason,
556
+ meta
557
+ };
558
+ if (transferInstructions) {
559
+ transferInstructions.status.current = transferInstructions.status.current || {
560
+ tag: currentTag,
561
+ value: {}
562
+ };
563
+ return {
564
+ label,
565
+ children,
566
+ transferInstruction: transferInstructions
567
+ };
568
+ }
569
+ const transferInstruction = {
570
+ originalInstructionCid: null,
571
+ ...choiceArgumentTransfer !== void 0 && { transfer: choiceArgumentTransfer },
572
+ status: {
573
+ before: null,
574
+ current: {
575
+ tag: currentTag,
576
+ value: {}
577
+ }
578
+ },
579
+ meta: null,
580
+ ...pendingCid ? { multiStepCorrelationId: pendingCid } : {}
581
+ };
582
+ return {
583
+ label,
584
+ children,
585
+ transferInstruction
586
+ };
587
+ }
588
+ async buildMergeSplit(exercisedEvent, tokenStandardChoice) {
589
+ let type;
590
+ const meta = mergeMetas(exercisedEvent);
591
+ switch (getMetaKeyValue(TxKindMetaKey, meta)) {
592
+ case "burn":
593
+ type = "Burn";
594
+ break;
595
+ case "mint":
596
+ type = "Mint";
597
+ break;
598
+ default: type = "MergeSplit";
599
+ }
600
+ const reason = getMetaKeyValue(ReasonMetaKey, meta);
601
+ const children = await this.getChildren(exercisedEvent);
602
+ return {
603
+ label: {
604
+ ...computeAmountChanges(children, meta, this.partyId),
605
+ type,
606
+ tokenStandardChoice,
607
+ reason,
608
+ meta
609
+ },
610
+ children,
611
+ transferInstruction: null
612
+ };
613
+ }
614
+ async buildFromTransferInstructionExercise(exercisedEvent, tokenStandardChoice) {
615
+ const instructionCid = exercisedEvent.contractId;
616
+ const transferInstructionEvents = await this.getEventsForArchive(exercisedEvent);
617
+ if (!transferInstructionEvents) return null;
618
+ const transferInstructionView = ensureInterfaceViewIsPresent(transferInstructionEvents.created.createdEvent, TRANSFER_INSTRUCTION_INTERFACE_ID).viewValue;
619
+ const multiStepCorrelationId = getCorrelationIdFromTransferInstruction(instructionCid, transferInstructionView.originalInstructionCid ?? null);
620
+ const resultTag = exercisedEvent.exerciseResult?.output?.tag || void 0;
621
+ const currentTag = currentStatusFromChoiceOrResult(exercisedEvent.choice, resultTag);
622
+ const transferInstruction = {
623
+ originalInstructionCid: transferInstructionView.originalInstructionCid,
624
+ multiStepCorrelationId,
625
+ transfer: transferInstructionView.transfer,
626
+ meta: transferInstructionView.meta,
627
+ status: {
628
+ before: transferInstructionView.status,
629
+ current: {
630
+ tag: currentTag,
631
+ value: {}
632
+ }
633
+ }
634
+ };
635
+ const exerciseResultOutputTag = resultTag;
636
+ const result = await (async () => {
637
+ switch (exerciseResultOutputTag) {
638
+ case "TransferInstructionResult_Failed":
639
+ case "TransferInstructionResult_Pending": return this.buildMergeSplit(exercisedEvent, tokenStandardChoice);
640
+ case "TransferInstructionResult_Completed": return this.buildTransfer(exercisedEvent, tokenStandardChoice, transferInstruction);
641
+ default: throw new Error(`Unknown TransferInstructionResult: ${exerciseResultOutputTag}`);
642
+ }
643
+ })();
644
+ return result && {
645
+ ...result,
646
+ transferInstruction
647
+ };
648
+ }
649
+ async buildBasic(exercisedEvent, type, tokenStandardChoice) {
650
+ const children = await this.getChildren(exercisedEvent);
651
+ const meta = mergeMetas(exercisedEvent);
652
+ const amountChanges = computeAmountChanges(children, meta, this.partyId);
653
+ const reason = getMetaKeyValue(ReasonMetaKey, meta);
654
+ return {
655
+ label: {
656
+ ...amountChanges,
657
+ type,
658
+ tokenStandardChoice,
659
+ reason,
660
+ meta
661
+ },
662
+ children,
663
+ transferInstruction: null
664
+ };
665
+ }
666
+ async getChildren(exercisedEvent) {
667
+ const mutatingResult = {
668
+ creates: [],
669
+ archives: []
670
+ };
671
+ const childrenEventsSlice = (this.transaction.events || []).map(getNodeIdAndEvent).filter(({ nodeId }) => nodeId > exercisedEvent.nodeId && nodeId <= exercisedEvent.lastDescendantNodeId);
672
+ if (exercisedEvent.consuming && hasInterface(HOLDING_INTERFACE_ID, exercisedEvent)) {
673
+ const selfEvent = await this.getEventsForArchive(exercisedEvent);
674
+ if (selfEvent) {
675
+ const holdingView = ensureInterfaceViewIsPresent(selfEvent.created.createdEvent, HOLDING_INTERFACE_ID).viewValue;
676
+ mutatingResult.archives.push({
677
+ amount: holdingView.amount,
678
+ instrumentId: holdingView.instrumentId,
679
+ contractId: exercisedEvent.contractId,
680
+ owner: holdingView.owner,
681
+ meta: holdingView.meta,
682
+ lock: holdingView.lock
683
+ });
684
+ }
685
+ }
686
+ for (const { createdEvent, archivedEvent, exercisedEvent } of childrenEventsSlice) if (createdEvent) {
687
+ const interfaceView = getInterfaceView(createdEvent);
688
+ if (interfaceView && interfaceView.interfaceId && matchInterfaceIds(HOLDING_INTERFACE_ID, interfaceView.interfaceId)) {
689
+ const holdingView = interfaceView.viewValue;
690
+ mutatingResult.creates.push({
691
+ amount: holdingView.amount,
692
+ instrumentId: holdingView.instrumentId,
693
+ contractId: createdEvent.contractId,
694
+ owner: holdingView.owner,
695
+ meta: holdingView.meta,
696
+ lock: holdingView.lock
697
+ });
698
+ }
699
+ } else if (archivedEvent && hasInterface(HOLDING_INTERFACE_ID, archivedEvent) || exercisedEvent && exercisedEvent.consuming && hasInterface(HOLDING_INTERFACE_ID, exercisedEvent)) {
700
+ const contractEvents = await this.getEventsForArchive(archivedEvent || exercisedEvent);
701
+ if (contractEvents) {
702
+ const holdingView = ensureInterfaceViewIsPresent(contractEvents.created?.createdEvent, HOLDING_INTERFACE_ID).viewValue;
703
+ mutatingResult.archives.push({
704
+ amount: holdingView.amount,
705
+ instrumentId: holdingView.instrumentId,
706
+ contractId: archivedEvent?.contractId || exercisedEvent.contractId,
707
+ owner: holdingView.owner,
708
+ meta: holdingView.meta,
709
+ lock: holdingView.lock
710
+ });
711
+ }
712
+ }
713
+ return {
714
+ creates: mutatingResult.creates.filter((create) => !mutatingResult.archives.some((archive) => create.contractId === archive.contractId)),
715
+ archives: mutatingResult.archives.filter((archive) => !mutatingResult.creates.some((create) => create.contractId === archive.contractId))
716
+ };
717
+ }
718
+ async getEventsForArchive(archivedEvent) {
719
+ if (!(archivedEvent.witnessParties || []).includes(this.partyId)) return null;
720
+ const basePayload = {
721
+ contractId: archivedEvent.contractId,
722
+ eventFormat: EventFilterBySetup({
723
+ interfaceIds: [HOLDING_INTERFACE_ID, TRANSFER_INSTRUCTION_INTERFACE_ID],
724
+ isMasterUser: this.isMasterUser,
725
+ partyId: this.partyId,
726
+ verbose: true
727
+ })
728
+ };
729
+ const events = await this.ledgerProvider.request({
730
+ method: "ledgerApi",
731
+ params: {
732
+ resource: "/v2/events/events-by-contract-id",
733
+ requestMethod: "post",
734
+ body: basePayload
735
+ }
736
+ }).catch((err) => {
737
+ if (isContractEventsNotFoundError(err)) return null;
738
+ else throw err;
739
+ });
740
+ if (!events) return null;
741
+ const created = events.created;
742
+ const archived = events.archived;
743
+ if (!created || !archived) throw new Error(`Archival of ${archivedEvent.contractId} does not have a corresponding create/archive event: ${JSON.stringify(events)}`);
744
+ return {
745
+ created,
746
+ archived
747
+ };
748
+ }
870
749
  };
871
750
  function isLeafEventNode(result) {
872
- return !!result.event;
751
+ return !!result.event;
873
752
  }
874
753
  function getNodeIdAndEvent(event) {
875
- if ("ExercisedEvent" in event) {
876
- if (event.ExercisedEvent.choice === "Archive") {
877
- return {
878
- nodeId: event.ExercisedEvent.nodeId,
879
- archivedEvent: event.ExercisedEvent
880
- };
881
- } else {
882
- return {
883
- nodeId: event.ExercisedEvent.nodeId,
884
- exercisedEvent: event.ExercisedEvent
885
- };
886
- }
887
- } else if ("CreatedEvent" in event) {
888
- return {
889
- nodeId: event.CreatedEvent.nodeId,
890
- createdEvent: event.CreatedEvent
891
- };
892
- } else if ("ArchivedEvent" in event) {
893
- return {
894
- nodeId: event.ArchivedEvent.nodeId,
895
- archivedEvent: event.ArchivedEvent
896
- };
897
- } else {
898
- throw new Error(`Impossible event type: ${event}`);
899
- }
754
+ if ("ExercisedEvent" in event) if (event.ExercisedEvent.choice === "Archive") return {
755
+ nodeId: event.ExercisedEvent.nodeId,
756
+ archivedEvent: event.ExercisedEvent
757
+ };
758
+ else return {
759
+ nodeId: event.ExercisedEvent.nodeId,
760
+ exercisedEvent: event.ExercisedEvent
761
+ };
762
+ else if ("CreatedEvent" in event) return {
763
+ nodeId: event.CreatedEvent.nodeId,
764
+ createdEvent: event.CreatedEvent
765
+ };
766
+ else if ("ArchivedEvent" in event) return {
767
+ nodeId: event.ArchivedEvent.nodeId,
768
+ archivedEvent: event.ArchivedEvent
769
+ };
770
+ else throw new Error(`Impossible event type: ${event}`);
900
771
  }
772
+ /** sumHoldingsChange sums all the changes over a number of holdings.
773
+ * Note that this function currently assumes all holdings use the same
774
+ * instrument. */
901
775
  function sumHoldingsChange(change, filter) {
902
- return sumHoldings(
903
- change.creates.filter((create) => filter(create.owner, create.lock))
904
- ).minus(
905
- sumHoldings(
906
- change.archives.filter(
907
- (archive) => filter(archive.owner, archive.lock)
908
- )
909
- )
910
- );
776
+ return sumHoldings(change.creates.filter((create) => filter(create.owner, create.lock))).minus(sumHoldings(change.archives.filter((archive) => filter(archive.owner, archive.lock))));
911
777
  }
912
778
  function sumHoldings(holdings) {
913
- if (holdings.length > 0) {
914
- const instrumentId = holdings[0].instrumentId;
915
- for (const holding of holdings) {
916
- if (holding.instrumentId.admin !== instrumentId.admin || holding.instrumentId.id !== instrumentId.id) {
917
- throw new Error(
918
- `Attempted to call sumHoldings on heterogeneous instruments: ${JSON.stringify(instrumentId)} != ${JSON.stringify(holding.instrumentId)}`
919
- );
920
- }
921
- }
922
- }
923
- return BigNumber.sum(
924
- ...holdings.map((h) => h.amount).concat(["0"])
925
- // avoid NaN
926
- );
779
+ if (holdings.length > 0) {
780
+ const instrumentId = holdings[0].instrumentId;
781
+ for (const holding of holdings) if (holding.instrumentId.admin !== instrumentId.admin || holding.instrumentId.id !== instrumentId.id) throw new Error(`Attempted to call sumHoldings on heterogeneous instruments: ${JSON.stringify(instrumentId)} != ${JSON.stringify(holding.instrumentId)}`);
782
+ }
783
+ return BigNumber.sum(...holdings.map((h) => h.amount).concat(["0"]));
927
784
  }
928
785
  function computeAmountChanges(children, meta, partyId) {
929
- const burnAmount = BigNumber(getMetaKeyValue(BurnedMetaKey, meta) || "0");
930
- const partyHoldingAmountChange = sumHoldingsChange(
931
- children,
932
- (owner) => owner === partyId
933
- );
934
- const otherPartiesHoldingAmountChange = sumHoldingsChange(
935
- children,
936
- (owner) => owner !== partyId
937
- );
938
- const mintAmount = partyHoldingAmountChange.plus(burnAmount).plus(otherPartiesHoldingAmountChange);
939
- return {
940
- burnAmount: burnAmount.toString(),
941
- mintAmount: mintAmount.toString()
942
- };
786
+ const burnAmount = BigNumber(getMetaKeyValue(BurnedMetaKey, meta) || "0");
787
+ const partyHoldingAmountChange = sumHoldingsChange(children, (owner) => owner === partyId);
788
+ const otherPartiesHoldingAmountChange = sumHoldingsChange(children, (owner) => owner !== partyId);
789
+ const mintAmount = partyHoldingAmountChange.plus(burnAmount).plus(otherPartiesHoldingAmountChange);
790
+ return {
791
+ burnAmount: burnAmount.toString(),
792
+ mintAmount: mintAmount.toString()
793
+ };
943
794
  }
944
795
  function computeSummary(instrumentId, changes, partyId) {
945
- const amountChange = sumHoldingsChange(
946
- changes,
947
- (owner) => owner === partyId
948
- );
949
- const outputAmount = sumHoldings(changes.creates);
950
- const inputAmount = sumHoldings(changes.archives);
951
- return {
952
- instrumentId,
953
- amountChange: amountChange.toString(),
954
- numOutputs: changes.creates.length,
955
- outputAmount: outputAmount.toString(),
956
- numInputs: changes.archives.length,
957
- inputAmount: inputAmount.toString()
958
- };
796
+ const amountChange = sumHoldingsChange(changes, (owner) => owner === partyId);
797
+ const outputAmount = sumHoldings(changes.creates);
798
+ const inputAmount = sumHoldings(changes.archives);
799
+ return {
800
+ instrumentId,
801
+ amountChange: amountChange.toString(),
802
+ numOutputs: changes.creates.length,
803
+ outputAmount: outputAmount.toString(),
804
+ numInputs: changes.archives.length,
805
+ inputAmount: inputAmount.toString()
806
+ };
959
807
  }
960
808
  function holdingsChangeByInstrument(changes) {
961
- const map = new InstrumentMap();
962
- for (const create of changes.creates) {
963
- if (map.has(create.instrumentId)) {
964
- map.get(create.instrumentId).creates.push(create);
965
- } else {
966
- map.set(create.instrumentId, { creates: [create], archives: [] });
967
- }
968
- }
969
- for (const archive of changes.archives) {
970
- if (map.has(archive.instrumentId)) {
971
- map.get(archive.instrumentId).archives.push(archive);
972
- } else {
973
- map.set(archive.instrumentId, { creates: [], archives: [archive] });
974
- }
975
- }
976
- return map;
809
+ const map = new InstrumentMap();
810
+ for (const create of changes.creates) if (map.has(create.instrumentId)) map.get(create.instrumentId).creates.push(create);
811
+ else map.set(create.instrumentId, {
812
+ creates: [create],
813
+ archives: []
814
+ });
815
+ for (const archive of changes.archives) if (map.has(archive.instrumentId)) map.get(archive.instrumentId).archives.push(archive);
816
+ else map.set(archive.instrumentId, {
817
+ creates: [],
818
+ archives: [archive]
819
+ });
820
+ return map;
977
821
  }
978
822
  function computeSummaries(changes, partyId) {
979
- const byInstrument = holdingsChangeByInstrument(changes);
980
- return [...byInstrument.entries()].map(
981
- ([instrumentId, change]) => computeSummary(instrumentId, change, partyId)
982
- );
823
+ return [...holdingsChangeByInstrument(changes).entries()].map(([instrumentId, change]) => computeSummary(instrumentId, change, partyId));
824
+ }
825
+ const CONTRACT_EVENTS_NOT_FOUND = "CONTRACT_EVENTS_NOT_FOUND";
826
+ /** Detects the ledger API CONTRACT_EVENTS_NOT_FOUND error across the
827
+ * different error shapes thrown by the various provider/transport stacks:
828
+ * - JsCantonError from a direct ledger client:
829
+ * `{ code: 'CONTRACT_EVENTS_NOT_FOUND', cause, ... }`
830
+ * - JSON-RPC error response (e.g. wallet gateway over HTTP):
831
+ * `{ error: { code, message, data: JsCantonError } }`
832
+ * - JSON-RPC error object (e.g. extension window transport):
833
+ * `{ code, message, data: JsCantonError }`
834
+ * - As a last resort, a stringified error body containing the code. */
835
+ function isContractEventsNotFoundError(err) {
836
+ const e = err;
837
+ return e?.code === CONTRACT_EVENTS_NOT_FOUND || e?.data?.code === CONTRACT_EVENTS_NOT_FOUND || e?.error?.data?.code === CONTRACT_EVENTS_NOT_FOUND || typeof e?.error?.data === "string" && e.error.data.includes(CONTRACT_EVENTS_NOT_FOUND);
983
838
  }
984
839
  function holdingChangesNonEmpty(event) {
985
- return event.unlockedHoldingsChange.creates.length > 0 || event.unlockedHoldingsChange.archives.length > 0 || event.lockedHoldingsChange.creates.length > 0 || event.lockedHoldingsChange.archives.length > 0;
840
+ return event.unlockedHoldingsChange.creates.length > 0 || event.unlockedHoldingsChange.archives.length > 0 || event.lockedHoldingsChange.creates.length > 0 || event.lockedHoldingsChange.archives.length > 0;
986
841
  }
987
- var emptyHoldingsChangeSummary = {
988
- // This is obviously incorrect, but the field was introduced at the same
989
- // time at which we introduced the more correct per-instrument summaries,
990
- // so we know that old code couldn't use this (broken) field, and new code
991
- // should use the correct summaries.
992
- instrumentId: { admin: "", id: "" },
993
- numInputs: 0,
994
- numOutputs: 0,
995
- inputAmount: "0",
996
- outputAmount: "0",
997
- amountChange: "0"
842
+ const emptyHoldingsChangeSummary = {
843
+ instrumentId: {
844
+ admin: "",
845
+ id: ""
846
+ },
847
+ numInputs: 0,
848
+ numOutputs: 0,
849
+ inputAmount: "0",
850
+ outputAmount: "0",
851
+ amountChange: "0"
998
852
  };
853
+ //#endregion
854
+ export { AllKnownMetaKeys, BurnedMetaKey, ReasonMetaKey, SenderMetaKey, TokenStandardTransactionInterfaces, TransactionParser, TxKindMetaKey, ensureInterfaceViewIsPresent, getInterfaceView, getKnownInterfaceView, getMetaKeyValue, hasInterface, isContractEventsNotFoundError, matchInterfaceIds, mergeMetas, removeParsedMetaKeys, renderTransaction, splitInterfaceId };
999
855
 
1000
- export { AllKnownMetaKeys, BurnedMetaKey, ReasonMetaKey, SenderMetaKey, TokenStandardTransactionInterfaces, TransactionParser, TxKindMetaKey, ensureInterfaceViewIsPresent, getInterfaceView, getKnownInterfaceView, getMetaKeyValue, hasInterface, matchInterfaceIds, mergeMetas, removeParsedMetaKeys, renderTransaction, splitInterfaceId };
1001
- //# sourceMappingURL=index.js.map
1002
856
  //# sourceMappingURL=index.js.map