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