@canton-network/core-ledger-client 0.27.2 → 0.28.1

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,130 +1,10 @@
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, TokenStandardClient, FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID } from '@canton-network/core-token-standard';
2
- import { EventFilterBySetup } from '@canton-network/core-ledger-client-types';
3
- export * from '@canton-network/core-ledger-client-types';
4
- import { ErrorInfo, RetryInfo } from '@canton-network/core-ledger-proto';
5
- import BigNumber from 'bignumber.js';
6
1
  import createClient from 'openapi-fetch';
2
+ import { ErrorInfo, RetryInfo } from '@canton-network/core-ledger-proto';
7
3
  import { LRUCache } from 'typescript-lru-cache';
8
4
 
9
5
  var __defProp = Object.defineProperty;
10
6
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
7
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
12
- function splitInterfaceId(interfaceId) {
13
- const regExp = /^#?([^:]+):([^:]+):([^:]+)$/;
14
- const match = regExp.exec(interfaceId);
15
- if (!match) return null;
16
- const [, packageName, moduleName, entityName] = match;
17
- return {
18
- packageName,
19
- moduleName,
20
- entityName
21
- };
22
- }
23
- function matchInterfaceIds(a, b) {
24
- const aParts = splitInterfaceId(a);
25
- const bParts = splitInterfaceId(b);
26
- return aParts !== null && bParts !== null && aParts.moduleName === bParts.moduleName && aParts.entityName === bParts.entityName;
27
- }
28
- var TokenStandardTransactionInterfaces = [
29
- HOLDING_INTERFACE_ID,
30
- TRANSFER_FACTORY_INTERFACE_ID,
31
- TRANSFER_INSTRUCTION_INTERFACE_ID,
32
- ALLOCATION_FACTORY_INTERFACE_ID,
33
- ALLOCATION_INSTRUCTION_INTERFACE_ID,
34
- ALLOCATION_INTERFACE_ID,
35
- ALLOCATION_REQUEST_INTERFACE_ID
36
- ];
37
- var SpliceMetaKeyPrefix = "splice.lfdecentralizedtrust.org/";
38
- var TxKindMetaKey = `${SpliceMetaKeyPrefix}tx-kind`;
39
- var SenderMetaKey = `${SpliceMetaKeyPrefix}sender`;
40
- var ReasonMetaKey = `${SpliceMetaKeyPrefix}reason`;
41
- var BurnedMetaKey = `${SpliceMetaKeyPrefix}burned`;
42
- var AllKnownMetaKeys = [
43
- TxKindMetaKey,
44
- SenderMetaKey,
45
- ReasonMetaKey,
46
- BurnedMetaKey
47
- ];
48
- function hasInterface(interfaceId, event) {
49
- return (event.implementedInterfaces || []).some(
50
- (id) => matchInterfaceIds(id, interfaceId)
51
- );
52
- }
53
- function getInterfaceView(createdEvent) {
54
- const interfaceViews = createdEvent.interfaceViews || null;
55
- return interfaceViews && interfaceViews[0] || null;
56
- }
57
- function getKnownInterfaceView(createdEvent) {
58
- const interfaceView = getInterfaceView(createdEvent);
59
- if (!interfaceView) {
60
- return null;
61
- } else if (matchInterfaceIds(HOLDING_INTERFACE_ID, interfaceView.interfaceId)) {
62
- return {
63
- type: "Holding",
64
- viewValue: interfaceView.viewValue
65
- };
66
- } else if (matchInterfaceIds(
67
- TRANSFER_INSTRUCTION_INTERFACE_ID,
68
- interfaceView.interfaceId
69
- )) {
70
- return {
71
- type: "TransferInstruction",
72
- viewValue: interfaceView.viewValue
73
- };
74
- } else {
75
- return null;
76
- }
77
- }
78
- function ensureInterfaceViewIsPresent(createdEvent, interfaceId) {
79
- const interfaceView = getInterfaceView(createdEvent);
80
- if (!interfaceView) {
81
- throw new Error(
82
- `Expected to have interface views, but didn't: ${JSON.stringify(
83
- createdEvent
84
- )}`
85
- );
86
- }
87
- if (!matchInterfaceIds(interfaceId, interfaceView.interfaceId)) {
88
- throw new Error(
89
- `Not a ${interfaceId} but a ${interfaceView.interfaceId}: ${JSON.stringify(createdEvent)}`
90
- );
91
- }
92
- return interfaceView;
93
- }
94
- function mergeMetas(event, extra) {
95
- const choiceArgument = event.choiceArgument;
96
- const lastWriteWins = [
97
- choiceArgument?.transfer?.meta,
98
- choiceArgument?.extraArgs?.meta,
99
- choiceArgument?.meta,
100
- extra,
101
- event.exerciseResult?.meta
102
- ];
103
- const result = {};
104
- lastWriteWins.forEach((meta) => {
105
- const values = meta?.values || {};
106
- Object.entries(values).forEach(([k, v]) => {
107
- result[k] = v;
108
- });
109
- });
110
- if (Object.keys(result).length === 0) {
111
- return void 0;
112
- } else {
113
- return { values: result };
114
- }
115
- }
116
- function getMetaKeyValue(key, meta) {
117
- return (meta?.values || {})[key] || null;
118
- }
119
- function removeParsedMetaKeys(meta) {
120
- return {
121
- values: Object.fromEntries(
122
- Object.entries(meta?.values || {}).filter(
123
- ([k]) => !AllKnownMetaKeys.includes(k)
124
- )
125
- )
126
- };
127
- }
128
8
  var COMPLETIONS_LIMIT = "100";
129
9
  var COMPLETIONS_STREAM_IDLE_TIMEOUT_MS = "1000";
130
10
  async function awaitCompletion(ledgerClient, ledgerEnd, partyId, userId, commandIdOrSubmissionId) {
@@ -135,2228 +15,135 @@ async function awaitCompletion(ledgerClient, ledgerEnd, partyId, userId, command
135
15
  parties: [partyId],
136
16
  beginExclusive: ledgerEnd
137
17
  },
138
- defaultRetryableOptions,
139
- {
140
- query: {
141
- limit: COMPLETIONS_LIMIT,
142
- stream_idle_timeout_ms: COMPLETIONS_STREAM_IDLE_TIMEOUT_MS
143
- }
144
- }
145
- );
146
- const completions = responses.filter(
147
- (r) => "Completion" in r.completionResponse
148
- );
149
- const wantedCompletion = responses.find((r) => {
150
- if ("Completion" in r.completionResponse) {
151
- const completion = r.completionResponse.Completion.value;
152
- return completion.userId === userId && (completion.commandId === commandIdOrSubmissionId || completion.submissionId === commandIdOrSubmissionId);
153
- }
154
- return false;
155
- });
156
- if (wantedCompletion && "Completion" in wantedCompletion.completionResponse) {
157
- const completion = wantedCompletion.completionResponse.Completion.value;
158
- const status = completion.status;
159
- if (status && status.code !== 0) {
160
- throw asGrpcError(status);
161
- }
162
- return completion;
163
- } else {
164
- const lastCompletion = completions[completions.length - 1];
165
- const newLedgerEnd = lastCompletion && "Completion" in lastCompletion.completionResponse ? lastCompletion.completionResponse.Completion.value.offset : void 0;
166
- return awaitCompletion(
167
- ledgerClient,
168
- newLedgerEnd || ledgerEnd,
169
- // !newLedgerEnd implies response was empty
170
- partyId,
171
- userId,
172
- commandIdOrSubmissionId
173
- );
174
- }
175
- }
176
- async function promiseWithTimeout(promise, timeoutMs, errorMessage) {
177
- let timeoutPid = null;
178
- const timeoutPromise = new Promise((_resolve, reject) => {
179
- timeoutPid = setTimeout(() => reject(errorMessage), timeoutMs);
180
- });
181
- try {
182
- return await Promise.race([promise, timeoutPromise]);
183
- } finally {
184
- if (timeoutPid) {
185
- clearTimeout(timeoutPid);
186
- }
187
- }
188
- }
189
- var defaultRetryableOptions = {
190
- retries: 5,
191
- delayMs: 3e3,
192
- cantonErrorKeys: [
193
- "SEQUENCER_REQUEST_FAILED",
194
- "SEQUENCER_BACKPRESSURE",
195
- "SUBMISSION_ALREADY_IN_FLIGHT",
196
- "LOCAL_VERDICT_TIMEOUT",
197
- "NOT_SEQUENCED_TIMEOUT",
198
- "NO_VIEW_WITH_VALID_RECIPIENTS"
199
- ]
200
- };
201
- async function retryable(fn, retryableOptions2, logger) {
202
- for (let attempts = 1; attempts <= retryableOptions2.retries; attempts++) {
203
- try {
204
- return await fn();
205
- } catch (err) {
206
- const grpcError = asGrpcError(err);
207
- const message = grpcError.message;
208
- const shouldRetry = retryableOptions2.cantonErrorKeys.length === 0 || retryableOptions2.cantonErrorKeys.some(
209
- (key) => message.includes(key)
210
- );
211
- if (attempts < retryableOptions2.retries && shouldRetry) {
212
- logger?.warn(
213
- `Caught retryiable error: ${message}. Retrying attempt ${attempts} of ${retryableOptions2.retries}...`
214
- );
215
- await new Promise(
216
- (res) => setTimeout(res, retryableOptions2.delayMs)
217
- );
218
- } else {
219
- throw grpcError;
220
- }
221
- }
222
- }
223
- throw new Error("retryable: Exceeded maximum retries without throwing.");
224
- }
225
- var isJsCantonError = (e) => typeof e === "object" && e !== null && "code" in e && "cause" in e && "errorCategory" in e;
226
- var asJsCantonError = (e) => {
227
- if (isJsCantonError(e)) {
228
- return e;
229
- } else {
230
- throw e;
231
- }
232
- };
233
- var asGrpcError = (e) => {
234
- let errorInfo = void 0;
235
- let retryInfo = void 0;
236
- let code = 500;
237
- let message = e?.message || "";
238
- if (typeof e === "object" && e !== null && "cause" in e) {
239
- message = e.cause;
240
- } else if (typeof e === "object" && e !== null && "message" in e) {
241
- message = e.message;
242
- }
243
- if (typeof e === "object" && e !== null && "code" in e && "message" in e && "details" in e && Array.isArray(e.details)) {
244
- code = e.code;
245
- message = e.message;
246
- for (const detail of e.details) {
247
- if (detail.typeUrl === "type.googleapis.com/google.rpc.ErrorInfo" && typeof detail.value === "string") {
248
- try {
249
- errorInfo = ErrorInfo.fromBinary(
250
- Buffer.from(detail.value, "base64")
251
- );
252
- } catch {
253
- }
254
- } else if (detail.typeUrl === "type.googleapis.com/google.rpc.RetryInfo" && typeof detail.value === "string") {
255
- try {
256
- retryInfo = RetryInfo.fromBinary(
257
- Buffer.from(detail.value, "base64")
258
- );
259
- } catch {
260
- }
261
- }
262
- }
263
- } else {
264
- throw e;
265
- }
266
- return { code, message, errorInfo, retryInfo };
267
- };
268
-
269
- // src/txparse/instrumentmap.ts
270
- var InstrumentMap = class {
271
- constructor() {
272
- __publicField(this, "map");
273
- this.map = /* @__PURE__ */ new Map();
274
- }
275
- encodeKey(instrumentId) {
276
- return JSON.stringify([instrumentId.admin, instrumentId.id]);
277
- }
278
- decodeKey(key) {
279
- const [admin, id] = JSON.parse(key);
280
- return { admin, id };
281
- }
282
- set(key, value) {
283
- this.map.set(this.encodeKey(key), value);
284
- }
285
- get(key) {
286
- return this.map.get(this.encodeKey(key));
287
- }
288
- has(key) {
289
- return this.map.has(this.encodeKey(key));
290
- }
291
- delete(key) {
292
- return this.map.delete(this.encodeKey(key));
293
- }
294
- *entries() {
295
- for (const [key, value] of this.map.entries()) {
296
- yield [this.decodeKey(key), value];
297
- }
298
- }
299
- };
300
- function currentStatusFromChoiceOrResult(choice, resultTag) {
301
- if (resultTag === "TransferInstructionResult_Failed") return "Failed";
302
- if (resultTag === "TransferInstructionResult_Completed") return "Completed";
303
- switch (choice) {
304
- case "TransferInstruction_Reject":
305
- return "Rejected";
306
- case "TransferInstruction_Withdraw":
307
- return "Withdrawn";
308
- case "TransferInstruction_Accept":
309
- case "TransferInstruction_Update":
310
- return "Pending";
311
- default:
312
- return "Pending";
313
- }
314
- }
315
- function getCorrelationIdFromTransferInstruction(currentInstructionCid, originalInstructionCid) {
316
- return originalInstructionCid ?? currentInstructionCid;
317
- }
318
- function getPendingTransferInstructionCid(exercisedEvent) {
319
- const output = exercisedEvent.exerciseResult?.output;
320
- if (output?.tag !== "TransferInstructionResult_Pending") return void 0;
321
- const cid = output.value?.transferInstructionCid;
322
- return cid ?? void 0;
323
- }
324
- var TransactionParser = class {
325
- constructor(transaction, ledgerClient, partyId, isMasterUser) {
326
- __publicField(this, "ledgerClient");
327
- __publicField(this, "partyId");
328
- __publicField(this, "transaction");
329
- __publicField(this, "isMasterUser");
330
- this.ledgerClient = ledgerClient;
331
- this.partyId = partyId;
332
- this.transaction = transaction;
333
- this.isMasterUser = isMasterUser;
334
- }
335
- async parseTransaction() {
336
- const tx = this.transaction;
337
- const events = await this.parseEvents([...tx.events || []].reverse());
338
- return {
339
- updateId: tx.updateId,
340
- offset: tx.offset,
341
- recordTime: tx.recordTime,
342
- synchronizerId: tx.synchronizerId,
343
- events
344
- };
345
- }
346
- async parseEvents(eventsStack) {
347
- let callStack = [];
348
- let continueAfterNodeId = -1;
349
- const result = [];
350
- while (eventsStack.length > 0) {
351
- const currentEvent = eventsStack.pop();
352
- const { nodeId, createdEvent, archivedEvent, exercisedEvent } = getNodeIdAndEvent(currentEvent);
353
- callStack = callStack.filter((s) => s.untilNodeId <= nodeId);
354
- const parentChoice = callStack[callStack.length - 1] && callStack[callStack.length - 1].parentChoiceName || "none (root node)";
355
- let parsed;
356
- if (nodeId <= continueAfterNodeId) {
357
- parsed = null;
358
- } else if (createdEvent) {
359
- parsed = this.parseRawCreate(createdEvent, parentChoice);
360
- } else if (archivedEvent) {
361
- parsed = await this.parseRawArchive(archivedEvent, parentChoice);
362
- } else if (exercisedEvent) {
363
- parsed = await this.parseExercise(exercisedEvent);
364
- } else {
365
- throw new Error(
366
- `Impossible event: ${JSON.stringify(currentEvent)}`
367
- );
368
- }
369
- if (parsed && isLeafEventNode(parsed)) {
370
- if (holdingChangesNonEmpty(parsed.event)) {
371
- result.push({
372
- ...parsed.event,
373
- label: {
374
- ...parsed.event.label,
375
- meta: removeParsedMetaKeys(parsed.event.label.meta)
376
- }
377
- });
378
- }
379
- continueAfterNodeId = parsed.continueAfterNodeId;
380
- } else if (parsed) {
381
- callStack.push({
382
- parentChoiceName: parsed.parentChoiceName,
383
- untilNodeId: parsed.lastDescendantNodeId
384
- });
385
- }
386
- }
387
- return result;
388
- }
389
- parseRawCreate(create, parentChoice) {
390
- return this.buildRawEvent(create, create.nodeId, (result) => {
391
- return {
392
- // TODO: this code currently only looks at the first instrument
393
- // to determine the type of the Event.
394
- type: Number(
395
- result.lockedHoldingsChangeSummaries[0]?.amountChange
396
- ) > 0 ? "Lock" : "Create",
397
- parentChoice,
398
- contractId: create.contractId,
399
- offset: create.offset,
400
- templateId: create.templateId,
401
- payload: result.payload,
402
- packageName: create.packageName,
403
- meta: void 0
404
- };
405
- });
406
- }
407
- async parseRawArchive(archive, parentChoice) {
408
- const events = await this.getEventsForArchive(archive);
409
- if (!events) {
410
- return null;
411
- }
412
- return this.buildRawEvent(
413
- events.created.createdEvent,
414
- archive.nodeId,
415
- (result) => {
416
- return {
417
- type: "Archive",
418
- parentChoice,
419
- contractId: archive.contractId,
420
- offset: archive.offset,
421
- templateId: archive.templateId,
422
- packageName: archive.packageName,
423
- actingParties: archive.actingParties || [],
424
- payload: result.payload,
425
- meta: void 0
426
- };
427
- }
428
- );
429
- }
430
- buildRawEvent(originalCreate, nodeId, buildLabel) {
431
- const view = getKnownInterfaceView(originalCreate);
432
- let result;
433
- switch (view?.type) {
434
- case "Holding": {
435
- const holdingView = view.viewValue;
436
- if (this.partyId !== holdingView.owner) {
437
- result = null;
438
- } else {
439
- const isLocked = !!holdingView.lock;
440
- const summary = {
441
- instrumentId: holdingView.instrumentId,
442
- amountChange: holdingView.amount,
443
- numInputs: 0,
444
- inputAmount: "0",
445
- numOutputs: 1,
446
- outputAmount: holdingView.amount
447
- };
448
- const lockedHoldingsChangeSummaries = isLocked ? [summary] : [];
449
- const unlockedHoldingsChangeSummaries = isLocked ? [] : [summary];
450
- result = {
451
- payload: holdingView,
452
- unlockedHoldingsChange: {
453
- creates: isLocked ? [] : [holdingView],
454
- archives: []
455
- },
456
- lockedHoldingsChange: {
457
- creates: isLocked ? [holdingView] : [],
458
- archives: []
459
- },
460
- lockedHoldingsChangeSummaries,
461
- lockedHoldingsChangeSummary: lockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
462
- unlockedHoldingsChangeSummaries,
463
- unlockedHoldingsChangeSummary: unlockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
464
- transferInstruction: null
465
- };
466
- }
467
- break;
468
- }
469
- case "TransferInstruction": {
470
- const transferInstructionView = view.viewValue;
471
- if (![
472
- transferInstructionView.transfer.sender,
473
- transferInstructionView.transfer.receiver
474
- ].some((stakeholder) => stakeholder === this.partyId)) {
475
- result = null;
476
- } else {
477
- const multiStepCorrelationId = getCorrelationIdFromTransferInstruction(
478
- originalCreate.contractId,
479
- transferInstructionView.originalInstructionCid ?? null
480
- );
481
- result = {
482
- payload: transferInstructionView,
483
- transferInstruction: {
484
- originalInstructionCid: transferInstructionView.originalInstructionCid,
485
- transfer: transferInstructionView.transfer,
486
- meta: transferInstructionView.meta,
487
- status: {
488
- before: transferInstructionView.status,
489
- // raw DAML pending sub-state
490
- current: { tag: "Pending", value: {} }
491
- // normalized
492
- },
493
- multiStepCorrelationId
494
- },
495
- unlockedHoldingsChange: { creates: [], archives: [] },
496
- lockedHoldingsChange: { creates: [], archives: [] },
497
- unlockedHoldingsChangeSummaries: [],
498
- unlockedHoldingsChangeSummary: emptyHoldingsChangeSummary,
499
- lockedHoldingsChangeSummaries: [],
500
- lockedHoldingsChangeSummary: emptyHoldingsChangeSummary
501
- };
502
- }
503
- break;
504
- }
505
- default:
506
- result = null;
507
- }
508
- return result && {
509
- continueAfterNodeId: nodeId,
510
- event: {
511
- label: buildLabel(result),
512
- unlockedHoldingsChange: result.unlockedHoldingsChange,
513
- lockedHoldingsChange: result.lockedHoldingsChange,
514
- lockedHoldingsChangeSummaries: result.lockedHoldingsChangeSummaries,
515
- lockedHoldingsChangeSummary: result.lockedHoldingsChangeSummary,
516
- unlockedHoldingsChangeSummaries: result.unlockedHoldingsChangeSummaries,
517
- unlockedHoldingsChangeSummary: result.unlockedHoldingsChangeSummary,
518
- transferInstruction: result.transferInstruction
519
- }
520
- };
521
- }
522
- async parseExercise(exercise) {
523
- let result = null;
524
- const tokenStandardChoice = {
525
- name: exercise.choice,
526
- choiceArgument: exercise.choiceArgument,
527
- exerciseResult: exercise.exerciseResult
528
- };
529
- switch (exercise.choice) {
530
- case "TransferRule_Transfer":
531
- case "TransferFactory_Transfer":
532
- result = await this.buildTransfer(exercise, tokenStandardChoice);
533
- break;
534
- case "TransferInstruction_Accept":
535
- case "TransferInstruction_Reject":
536
- case "TransferInstruction_Withdraw":
537
- case "TransferInstruction_Update":
538
- result = await this.buildFromTransferInstructionExercise(
539
- exercise,
540
- tokenStandardChoice
541
- );
542
- break;
543
- case "BurnMintFactory_BurnMint":
544
- result = await this.buildMergeSplit(
545
- exercise,
546
- tokenStandardChoice
547
- );
548
- break;
549
- default: {
550
- const meta = mergeMetas(exercise);
551
- const txKind = getMetaKeyValue(TxKindMetaKey, meta);
552
- if (txKind) {
553
- result = await this.parseViaTxKind(exercise, txKind);
554
- }
555
- break;
556
- }
557
- }
558
- if (!result) {
559
- return {
560
- lastDescendantNodeId: exercise.lastDescendantNodeId,
561
- parentChoiceName: exercise.choice
562
- };
563
- } else {
564
- const lockedHoldingsChange = {
565
- creates: result.children.creates.filter(
566
- (h) => !!h.lock && h.owner === this.partyId
567
- ),
568
- archives: result.children.archives.filter(
569
- (h) => !!h.lock && h.owner === this.partyId
570
- )
571
- };
572
- const unlockedHoldingsChange = {
573
- creates: result.children.creates.filter(
574
- (h) => !h.lock && h.owner === this.partyId
575
- ),
576
- archives: result.children.archives.filter(
577
- (h) => !h.lock && h.owner === this.partyId
578
- )
579
- };
580
- const lockedHoldingsChangeSummaries = computeSummaries(
581
- lockedHoldingsChange,
582
- this.partyId
583
- );
584
- const unlockedHoldingsChangeSummaries = computeSummaries(
585
- unlockedHoldingsChange,
586
- this.partyId
587
- );
588
- return {
589
- event: {
590
- label: result.label,
591
- lockedHoldingsChange,
592
- lockedHoldingsChangeSummaries,
593
- lockedHoldingsChangeSummary: lockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
594
- unlockedHoldingsChange,
595
- unlockedHoldingsChangeSummaries,
596
- unlockedHoldingsChangeSummary: unlockedHoldingsChangeSummaries[0] ?? emptyHoldingsChangeSummary,
597
- transferInstruction: result.transferInstruction
598
- },
599
- continueAfterNodeId: exercise.lastDescendantNodeId
600
- };
601
- }
602
- }
603
- async parseViaTxKind(exercisedEvent, txKind) {
604
- switch (txKind) {
605
- case "transfer":
606
- return await this.buildTransfer(exercisedEvent, null);
607
- case "merge-split":
608
- case "burn":
609
- case "mint":
610
- return await this.buildMergeSplit(exercisedEvent, null);
611
- case "unlock":
612
- return await this.buildBasic(exercisedEvent, "Unlock", null);
613
- case "expire-dust":
614
- return await this.buildBasic(exercisedEvent, "ExpireDust", null);
615
- default:
616
- throw new Error(
617
- `Unknown tx-kind '${txKind}' in ${JSON.stringify(exercisedEvent)}`
618
- );
619
- }
620
- }
621
- async buildTransfer(exercisedEvent, tokenStandardChoice, transferInstructions) {
622
- const meta = mergeMetas(
623
- exercisedEvent,
624
- transferInstructions?.transfer?.meta
625
- );
626
- const reason = getMetaKeyValue(ReasonMetaKey, meta);
627
- const choiceArgumentTransfer = exercisedEvent.choiceArgument.transfer;
628
- const sender = transferInstructions?.transfer?.sender || getMetaKeyValue(SenderMetaKey, meta) || choiceArgumentTransfer.sender;
629
- if (!sender) {
630
- console.error(
631
- `Malformed transfer didn't contain sender. Will instead attempt to parse the children.
632
- Transfer: ${JSON.stringify(exercisedEvent)}`
633
- );
634
- return null;
635
- }
636
- const resultTag = exercisedEvent.exerciseResult?.output?.tag || void 0;
637
- const pendingCid = getPendingTransferInstructionCid(exercisedEvent);
638
- const currentTag = currentStatusFromChoiceOrResult(
639
- exercisedEvent.choice,
640
- resultTag
641
- );
642
- const children = await this.getChildren(exercisedEvent);
643
- const receiverAmounts = /* @__PURE__ */ new Map();
644
- children.creates.filter((h) => h.owner !== sender).forEach(
645
- (holding) => receiverAmounts.set(
646
- holding.owner,
647
- (receiverAmounts.get(holding.owner) || BigNumber("0")).plus(
648
- BigNumber(holding.amount)
649
- )
650
- )
651
- );
652
- const amountChanges = computeAmountChanges(children, meta, this.partyId);
653
- let label;
654
- if (receiverAmounts.size === 0) {
655
- label = {
656
- ...amountChanges,
657
- type: "MergeSplit",
658
- tokenStandardChoice,
659
- reason,
660
- meta
661
- };
662
- } else if (sender === this.partyId) {
663
- label = {
664
- ...amountChanges,
665
- type: "TransferOut",
666
- receiverAmounts: [...receiverAmounts].map(([k, v]) => {
667
- return { receiver: k, amount: v.toString() };
668
- }),
669
- tokenStandardChoice,
670
- reason,
671
- meta
672
- };
673
- } else {
674
- label = {
675
- type: "TransferIn",
676
- // for Transfers, the burn/mint is always 0 for the receiving party (i.e., 0 for TransferIn)
677
- burnAmount: "0",
678
- mintAmount: "0",
679
- sender,
680
- tokenStandardChoice,
681
- reason,
682
- meta
683
- };
684
- }
685
- if (transferInstructions) {
686
- transferInstructions.status.current = transferInstructions.status.current || { tag: currentTag, value: {} };
687
- return {
688
- label,
689
- children,
690
- transferInstruction: transferInstructions
691
- };
692
- }
693
- const transferInstruction = {
694
- originalInstructionCid: null,
695
- ...choiceArgumentTransfer !== void 0 && {
696
- transfer: choiceArgumentTransfer
697
- },
698
- status: {
699
- before: null,
700
- current: { tag: currentTag, value: {} }
701
- },
702
- meta: null,
703
- ...pendingCid ? { multiStepCorrelationId: pendingCid } : {}
704
- };
705
- return {
706
- label,
707
- children,
708
- transferInstruction
709
- };
710
- }
711
- async buildMergeSplit(exercisedEvent, tokenStandardChoice) {
712
- let type;
713
- const meta = mergeMetas(exercisedEvent);
714
- switch (getMetaKeyValue(TxKindMetaKey, meta)) {
715
- case "burn":
716
- type = "Burn";
717
- break;
718
- case "mint":
719
- type = "Mint";
720
- break;
721
- default:
722
- type = "MergeSplit";
723
- }
724
- const reason = getMetaKeyValue(ReasonMetaKey, meta);
725
- const children = await this.getChildren(exercisedEvent);
726
- const amountChanges = computeAmountChanges(children, meta, this.partyId);
727
- const label = {
728
- ...amountChanges,
729
- type,
730
- tokenStandardChoice,
731
- reason,
732
- meta
733
- };
734
- return {
735
- label,
736
- children,
737
- transferInstruction: null
738
- };
739
- }
740
- async buildFromTransferInstructionExercise(exercisedEvent, tokenStandardChoice) {
741
- const instructionCid = exercisedEvent.contractId;
742
- const transferInstructionEvents = await this.getEventsForArchive(exercisedEvent);
743
- if (!transferInstructionEvents) {
744
- return null;
745
- }
746
- const transferInstructionView = ensureInterfaceViewIsPresent(
747
- transferInstructionEvents.created.createdEvent,
748
- TRANSFER_INSTRUCTION_INTERFACE_ID
749
- ).viewValue;
750
- const multiStepCorrelationId = getCorrelationIdFromTransferInstruction(
751
- instructionCid,
752
- transferInstructionView.originalInstructionCid ?? null
753
- );
754
- const resultTag = exercisedEvent.exerciseResult?.output?.tag || void 0;
755
- const currentTag = currentStatusFromChoiceOrResult(
756
- exercisedEvent.choice,
757
- resultTag
758
- );
759
- const transferInstruction = {
760
- originalInstructionCid: transferInstructionView.originalInstructionCid,
761
- multiStepCorrelationId,
762
- transfer: transferInstructionView.transfer,
763
- meta: transferInstructionView.meta,
764
- status: {
765
- before: transferInstructionView.status,
766
- current: { tag: currentTag, value: {} }
767
- }
768
- };
769
- const exerciseResultOutputTag = resultTag;
770
- let result = null;
771
- switch (exerciseResultOutputTag) {
772
- case "TransferInstructionResult_Failed":
773
- case "TransferInstructionResult_Pending":
774
- result = await this.buildMergeSplit(
775
- exercisedEvent,
776
- tokenStandardChoice
777
- );
778
- break;
779
- case "TransferInstructionResult_Completed":
780
- result = await this.buildTransfer(
781
- exercisedEvent,
782
- tokenStandardChoice,
783
- transferInstruction
784
- );
785
- break;
786
- default:
787
- throw new Error(
788
- `Unknown TransferInstructionResult: ${exerciseResultOutputTag}`
789
- );
790
- }
791
- return result && {
792
- ...result,
793
- transferInstruction
794
- };
795
- }
796
- async buildBasic(exercisedEvent, type, tokenStandardChoice) {
797
- const children = await this.getChildren(exercisedEvent);
798
- const meta = mergeMetas(exercisedEvent);
799
- const amountChanges = computeAmountChanges(children, meta, this.partyId);
800
- const reason = getMetaKeyValue(ReasonMetaKey, meta);
801
- return {
802
- label: {
803
- ...amountChanges,
804
- type,
805
- tokenStandardChoice,
806
- reason,
807
- meta
808
- },
809
- children,
810
- transferInstruction: null
811
- };
812
- }
813
- async getChildren(exercisedEvent) {
814
- const mutatingResult = { creates: [], archives: [] };
815
- const childrenEventsSlice = (this.transaction.events || []).map(getNodeIdAndEvent).filter(
816
- ({ nodeId }) => nodeId > exercisedEvent.nodeId && nodeId <= exercisedEvent.lastDescendantNodeId
817
- );
818
- if (exercisedEvent.consuming && hasInterface(HOLDING_INTERFACE_ID, exercisedEvent)) {
819
- const selfEvent = await this.getEventsForArchive(exercisedEvent);
820
- if (selfEvent) {
821
- const holdingView = ensureInterfaceViewIsPresent(
822
- selfEvent.created.createdEvent,
823
- HOLDING_INTERFACE_ID
824
- ).viewValue;
825
- mutatingResult.archives.push({
826
- amount: holdingView.amount,
827
- instrumentId: holdingView.instrumentId,
828
- contractId: exercisedEvent.contractId,
829
- owner: holdingView.owner,
830
- meta: holdingView.meta,
831
- lock: holdingView.lock
832
- });
833
- }
834
- }
835
- for (const {
836
- createdEvent,
837
- archivedEvent,
838
- exercisedEvent: exercisedEvent2
839
- } of childrenEventsSlice) {
840
- if (createdEvent) {
841
- const interfaceView = getInterfaceView(createdEvent);
842
- if (interfaceView && matchInterfaceIds(
843
- HOLDING_INTERFACE_ID,
844
- interfaceView.interfaceId
845
- )) {
846
- const holdingView = interfaceView.viewValue;
847
- mutatingResult.creates.push({
848
- amount: holdingView.amount,
849
- instrumentId: holdingView.instrumentId,
850
- contractId: createdEvent.contractId,
851
- owner: holdingView.owner,
852
- meta: holdingView.meta,
853
- lock: holdingView.lock
854
- });
855
- }
856
- } else if (archivedEvent && hasInterface(HOLDING_INTERFACE_ID, archivedEvent) || exercisedEvent2 && exercisedEvent2.consuming && hasInterface(HOLDING_INTERFACE_ID, exercisedEvent2)) {
857
- const contractEvents = await this.getEventsForArchive(
858
- archivedEvent || exercisedEvent2
859
- );
860
- if (contractEvents) {
861
- const holdingView = ensureInterfaceViewIsPresent(
862
- contractEvents.created?.createdEvent,
863
- HOLDING_INTERFACE_ID
864
- ).viewValue;
865
- mutatingResult.archives.push({
866
- amount: holdingView.amount,
867
- instrumentId: holdingView.instrumentId,
868
- contractId: archivedEvent?.contractId || exercisedEvent2.contractId,
869
- owner: holdingView.owner,
870
- meta: holdingView.meta,
871
- lock: holdingView.lock
872
- });
873
- }
874
- }
875
- }
876
- return {
877
- // remove transient contracts
878
- creates: mutatingResult.creates.filter(
879
- (create) => !mutatingResult.archives.some(
880
- (archive) => create.contractId === archive.contractId
881
- )
882
- ),
883
- archives: mutatingResult.archives.filter(
884
- (archive) => !mutatingResult.creates.some(
885
- (create) => create.contractId === archive.contractId
886
- )
887
- )
888
- };
889
- }
890
- async getEventsForArchive(archivedEvent) {
891
- if (!(archivedEvent.witnessParties || []).includes(this.partyId)) {
892
- return null;
893
- }
894
- const basePayload = {
895
- contractId: archivedEvent.contractId,
896
- eventFormat: EventFilterBySetup({
897
- interfaceIds: [
898
- HOLDING_INTERFACE_ID,
899
- TRANSFER_INSTRUCTION_INTERFACE_ID
900
- ],
901
- isMasterUser: this.isMasterUser,
902
- partyId: this.partyId,
903
- verbose: true
904
- })
905
- };
906
- const payload = this.ledgerClient.getCurrentClientVersion() === "3.3" ? { ...basePayload, requestingParties: [] } : basePayload;
907
- const events = await this.ledgerClient.postWithRetry("/v2/events/events-by-contract-id", payload).catch((err) => {
908
- if (err.code === "CONTRACT_EVENTS_NOT_FOUND") {
909
- return null;
910
- } else {
911
- throw err;
912
- }
913
- });
914
- if (!events) {
915
- return null;
916
- }
917
- const created = events.created;
918
- const archived = events.archived;
919
- if (!created || !archived) {
920
- throw new Error(
921
- `Archival of ${archivedEvent.contractId} does not have a corresponding create/archive event: ${JSON.stringify(
922
- events
923
- )}`
924
- );
925
- }
926
- return { created, archived };
927
- }
928
- };
929
- function isLeafEventNode(result) {
930
- return !!result.event;
931
- }
932
- function getNodeIdAndEvent(event) {
933
- if ("ExercisedEvent" in event) {
934
- if (event.ExercisedEvent.choice === "Archive") {
935
- return {
936
- nodeId: event.ExercisedEvent.nodeId,
937
- archivedEvent: event.ExercisedEvent
938
- };
939
- } else {
940
- return {
941
- nodeId: event.ExercisedEvent.nodeId,
942
- exercisedEvent: event.ExercisedEvent
943
- };
944
- }
945
- } else if ("CreatedEvent" in event) {
946
- return {
947
- nodeId: event.CreatedEvent.nodeId,
948
- createdEvent: event.CreatedEvent
949
- };
950
- } else if ("ArchivedEvent" in event) {
951
- return {
952
- nodeId: event.ArchivedEvent.nodeId,
953
- archivedEvent: event.ArchivedEvent
954
- };
955
- } else {
956
- throw new Error(`Impossible event type: ${event}`);
957
- }
958
- }
959
- function sumHoldingsChange(change, filter) {
960
- return sumHoldings(
961
- change.creates.filter((create) => filter(create.owner, create.lock))
962
- ).minus(
963
- sumHoldings(
964
- change.archives.filter(
965
- (archive) => filter(archive.owner, archive.lock)
966
- )
967
- )
968
- );
969
- }
970
- function sumHoldings(holdings) {
971
- if (holdings.length > 0) {
972
- const instrumentId = holdings[0].instrumentId;
973
- for (const holding of holdings) {
974
- if (holding.instrumentId.admin !== instrumentId.admin || holding.instrumentId.id !== instrumentId.id) {
975
- throw new Error(
976
- `Attempted to call sumHoldings on heterogeneous instruments: ${JSON.stringify(instrumentId)} != ${JSON.stringify(holding.instrumentId)}`
977
- );
978
- }
979
- }
980
- }
981
- return BigNumber.sum(
982
- ...holdings.map((h) => h.amount).concat(["0"])
983
- // avoid NaN
984
- );
985
- }
986
- function computeAmountChanges(children, meta, partyId) {
987
- const burnAmount = BigNumber(getMetaKeyValue(BurnedMetaKey, meta) || "0");
988
- const partyHoldingAmountChange = sumHoldingsChange(
989
- children,
990
- (owner) => owner === partyId
991
- );
992
- const otherPartiesHoldingAmountChange = sumHoldingsChange(
993
- children,
994
- (owner) => owner !== partyId
995
- );
996
- const mintAmount = partyHoldingAmountChange.plus(burnAmount).plus(otherPartiesHoldingAmountChange);
997
- return {
998
- burnAmount: burnAmount.toString(),
999
- mintAmount: mintAmount.toString()
1000
- };
1001
- }
1002
- function computeSummary(instrumentId, changes, partyId) {
1003
- const amountChange = sumHoldingsChange(
1004
- changes,
1005
- (owner) => owner === partyId
1006
- );
1007
- const outputAmount = sumHoldings(changes.creates);
1008
- const inputAmount = sumHoldings(changes.archives);
1009
- return {
1010
- instrumentId,
1011
- amountChange: amountChange.toString(),
1012
- numOutputs: changes.creates.length,
1013
- outputAmount: outputAmount.toString(),
1014
- numInputs: changes.archives.length,
1015
- inputAmount: inputAmount.toString()
1016
- };
1017
- }
1018
- function holdingsChangeByInstrument(changes) {
1019
- const map = new InstrumentMap();
1020
- for (const create of changes.creates) {
1021
- if (map.has(create.instrumentId)) {
1022
- map.get(create.instrumentId).creates.push(create);
1023
- } else {
1024
- map.set(create.instrumentId, { creates: [create], archives: [] });
1025
- }
1026
- }
1027
- for (const archive of changes.archives) {
1028
- if (map.has(archive.instrumentId)) {
1029
- map.get(archive.instrumentId).archives.push(archive);
1030
- } else {
1031
- map.set(archive.instrumentId, { creates: [], archives: [archive] });
1032
- }
1033
- }
1034
- return map;
1035
- }
1036
- function computeSummaries(changes, partyId) {
1037
- const byInstrument = holdingsChangeByInstrument(changes);
1038
- return [...byInstrument.entries()].map(
1039
- ([instrumentId, change]) => computeSummary(instrumentId, change, partyId)
1040
- );
1041
- }
1042
- function holdingChangesNonEmpty(event) {
1043
- return event.unlockedHoldingsChange.creates.length > 0 || event.unlockedHoldingsChange.archives.length > 0 || event.lockedHoldingsChange.creates.length > 0 || event.lockedHoldingsChange.archives.length > 0;
1044
- }
1045
- var emptyHoldingsChangeSummary = {
1046
- // This is obviously incorrect, but the field was introduced at the same
1047
- // time at which we introduced the more correct per-instrument summaries,
1048
- // so we know that old code couldn't use this (broken) field, and new code
1049
- // should use the correct summaries.
1050
- instrumentId: { admin: "", id: "" },
1051
- numInputs: 0,
1052
- numOutputs: 0,
1053
- inputAmount: "0",
1054
- outputAmount: "0",
1055
- amountChange: "0"
1056
- };
1057
-
1058
- // src/txparse/types.ts
1059
- var renderTransaction = (t) => {
1060
- return { ...t, events: t.events.map(renderTransactionEvent) };
1061
- };
1062
- var renderTransactionEvent = (e) => {
1063
- const lockedHoldingsChangeSummaries = e.lockedHoldingsChangeSummaries.map(renderHoldingsChangeSummary).filter((s) => s !== null);
1064
- const unlockedHoldingsChangeSummaries = e.unlockedHoldingsChangeSummaries.map(renderHoldingsChangeSummary).filter((s) => s !== null);
1065
- const lockedHoldingsChange = renderHoldingsChange(e.lockedHoldingsChange);
1066
- const unlockedHoldingsChange = renderHoldingsChange(
1067
- e.unlockedHoldingsChange
1068
- );
1069
- return {
1070
- ...e,
1071
- lockedHoldingsChange,
1072
- unlockedHoldingsChange,
1073
- lockedHoldingsChangeSummaries,
1074
- // Deprecated
1075
- lockedHoldingsChangeSummary: renderHoldingsChangeSummary(
1076
- e.lockedHoldingsChangeSummary
1077
- ),
1078
- unlockedHoldingsChangeSummaries,
1079
- // Deprecated
1080
- unlockedHoldingsChangeSummary: renderHoldingsChangeSummary(
1081
- e.unlockedHoldingsChangeSummary
1082
- )
1083
- };
1084
- };
1085
- var renderHoldingsChangeSummary = (s) => {
1086
- if (s.numInputs === 0 && s.numOutputs === 0 && s.inputAmount === "0" && s.outputAmount === "0" && s.amountChange === "0") {
1087
- return null;
1088
- }
1089
- return {
1090
- ...(s.instrumentId.admin !== "" || s.instrumentId.id !== "") && {
1091
- instrumentId: s.instrumentId
1092
- },
1093
- ...s.numInputs !== 0 && { numInputs: s.numInputs },
1094
- ...s.inputAmount !== "0" && { inputAmount: s.inputAmount },
1095
- ...s.numOutputs !== 0 && { numOutputs: s.numOutputs },
1096
- ...s.outputAmount !== "0" && { outputAmount: s.outputAmount },
1097
- ...s.amountChange !== "0" && { amountChange: s.amountChange }
1098
- };
1099
- };
1100
- var renderHoldingsChange = (c) => {
1101
- if (c.creates.length === 0 && c.archives.length === 0) {
1102
- return null;
1103
- }
1104
- return {
1105
- ...c.creates.length !== 0 && { creates: c.creates },
1106
- ...c.archives.length !== 0 && { archives: c.archives }
1107
- };
1108
- };
1109
-
1110
- // src/token-standard-service.ts
1111
- var REQUESTED_AT_SKEW_MS = 6e4;
1112
- var EMPTY_META = { values: {} };
1113
- var CoreService = class _CoreService {
1114
- constructor(ledgerClient, logger, accessTokenProvider, isMasterUser, isAdmin = false, accessToken = "") {
1115
- this.ledgerClient = ledgerClient;
1116
- this.logger = logger;
1117
- this.accessTokenProvider = accessTokenProvider;
1118
- this.isMasterUser = isMasterUser;
1119
- this.isAdmin = isAdmin;
1120
- this.accessToken = accessToken;
1121
- }
1122
- getTokenStandardClient(registryUrl) {
1123
- return new TokenStandardClient(
1124
- registryUrl,
1125
- this.logger,
1126
- this.isAdmin,
1127
- this.accessToken,
1128
- this.accessTokenProvider
1129
- );
1130
- }
1131
- // TODO: probably needs a filter by instrument ID as well?
1132
- async getInputHoldingsCids(sender, inputUtxos, amount) {
1133
- const now = /* @__PURE__ */ new Date();
1134
- if (inputUtxos && inputUtxos.length > 0) {
1135
- return inputUtxos;
1136
- }
1137
- const senderHoldings = await this.listContractsByInterface(
1138
- HOLDING_INTERFACE_ID,
1139
- sender
1140
- );
1141
- if (senderHoldings.length === 0) {
1142
- throw new Error(
1143
- "Sender has no holdings, so transfer can't be executed."
1144
- );
1145
- }
1146
- const unlockedSenderHoldings = senderHoldings.filter((utxo) => {
1147
- const lock = utxo.interfaceViewValue.lock;
1148
- if (!lock) return true;
1149
- const expiresAt = lock.expiresAt;
1150
- if (!expiresAt) return false;
1151
- const expiresAtDate = new Date(expiresAt);
1152
- return expiresAtDate <= now;
1153
- });
1154
- if (unlockedSenderHoldings.length > 100) {
1155
- this.logger.warn(`Sender has more than 100 unlocked utxos.`);
1156
- }
1157
- if (amount) {
1158
- return _CoreService.getInputHoldingsCidsForAmount(
1159
- amount,
1160
- unlockedSenderHoldings
1161
- );
1162
- } else {
1163
- return unlockedSenderHoldings.map((h) => h.contractId);
1164
- }
1165
- }
1166
- static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
1167
- const exactAmount = unlockedSenderHoldings.find(
1168
- (holding) => parseFloat(holding.interfaceViewValue.amount) === amount
1169
- );
1170
- if (exactAmount) {
1171
- return [exactAmount.contractId];
1172
- }
1173
- const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted(
1174
- (a, b) => parseFloat(a.interfaceViewValue.amount) - parseFloat(b.interfaceViewValue.amount)
1175
- );
1176
- const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
1177
- if (!largestHoldingAmount) {
1178
- throw new Error(`Sender doesn't have any unlocked holdings`);
1179
- }
1180
- let currentSum = parseFloat(
1181
- largestHoldingAmount.interfaceViewValue.amount
1182
- );
1183
- const cIds = [largestHoldingAmount.contractId];
1184
- for (const h of sortedUnlockedSenderHoldings) {
1185
- if (currentSum >= amount) {
1186
- break;
1187
- }
1188
- const currentHoldingAmount = parseFloat(h.interfaceViewValue.amount);
1189
- currentSum += currentHoldingAmount;
1190
- cIds.push(h.contractId);
1191
- }
1192
- if (currentSum < amount) {
1193
- throw new Error(
1194
- `Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount - currentSum}`
1195
- );
1196
- }
1197
- if (cIds.length > 100) {
1198
- throw new Error(
1199
- `Exceeded the maximum of 100 utxos in 1 transaction`
1200
- );
1201
- }
1202
- return cIds;
1203
- }
1204
- async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
1205
- try {
1206
- const ledgerEnd = offset ?? (await this.ledgerClient.getWithRetry("/v2/state/ledger-end")).offset;
1207
- const options = {
1208
- offset: ledgerEnd,
1209
- interfaceIds: [interfaceId],
1210
- parties: [partyId],
1211
- filterByParty: true,
1212
- continueUntilCompletion: Boolean(continueUntilCompletion)
1213
- };
1214
- if (limit !== void 0) {
1215
- options.limit = limit;
1216
- }
1217
- const acsResponses = await this.ledgerClient.activeContracts(options);
1218
- const isActiveContractEntry = (acsResponse) => "JsActiveContract" in acsResponse.contractEntry && !!acsResponse.contractEntry.JsActiveContract?.createdEvent;
1219
- const activeContractEntries = acsResponses.filter(
1220
- isActiveContractEntry
1221
- );
1222
- return activeContractEntries.map(
1223
- (response) => this.toPrettyContract(interfaceId, response, ledgerEnd)
1224
- );
1225
- } catch (err) {
1226
- this.logger.error(
1227
- `Failed to list contracts of interface ${interfaceId}`,
1228
- err
1229
- );
1230
- throw err;
1231
- }
1232
- }
1233
- async toPrettyTransactions(updates, partyId, ledgerClient) {
1234
- const isOffsetCheckpointUpdate = (updateResponse) => "OffsetCheckpoint" in updateResponse.update;
1235
- const isTransactionUpdate = (updateResponse) => "Transaction" in updateResponse.update && !!updateResponse.update.Transaction?.value;
1236
- const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map((update) => update.update.OffsetCheckpoint.value.offset);
1237
- const latestCheckpointOffset = Math.max(...offsetCheckpoints);
1238
- const transactions = await Promise.all(
1239
- updates.filter(isTransactionUpdate).map(async (update) => {
1240
- const tx = update.update.Transaction.value;
1241
- const parser = new TransactionParser(
1242
- tx,
1243
- ledgerClient,
1244
- partyId,
1245
- this.isMasterUser
1246
- );
1247
- return await parser.parseTransaction();
1248
- })
1249
- );
1250
- return {
1251
- // OffsetCheckpoint can be anywhere... or not at all, maybe
1252
- nextOffset: Math.max(
1253
- latestCheckpointOffset,
1254
- ...transactions.map((tx) => tx.offset)
1255
- ),
1256
- transactions: transactions.filter((tx) => tx.events.length > 0).map(renderTransaction)
1257
- };
1258
- }
1259
- async toPrettyTransaction(getTransactionResponse, partyId, ledgerClient) {
1260
- const tx = getTransactionResponse.transaction;
1261
- const parser = new TransactionParser(
1262
- tx,
1263
- ledgerClient,
1264
- partyId,
1265
- this.isMasterUser
1266
- );
1267
- const parsedTx = await parser.parseTransaction();
1268
- return renderTransaction(parsedTx);
1269
- }
1270
- async toPrettyTransactionsPerParty(updates, parties, ledgerClient) {
1271
- const all = await Promise.all(
1272
- parties.map(
1273
- async (partyId) => [
1274
- partyId,
1275
- await this.toPrettyTransactions(
1276
- updates,
1277
- partyId,
1278
- ledgerClient
1279
- )
1280
- ]
1281
- )
1282
- );
1283
- return new Map(all);
1284
- }
1285
- // returns object with JsActiveContract content
1286
- // and contractId and interface view value extracted from it as separate fields for convenience
1287
- toPrettyContract(interfaceId, response, offset) {
1288
- const activeContract = response.contractEntry.JsActiveContract;
1289
- const { createdEvent } = activeContract;
1290
- return {
1291
- contractId: createdEvent.contractId,
1292
- activeContract,
1293
- interfaceViewValue: ensureInterfaceViewIsPresent(
1294
- createdEvent,
1295
- interfaceId
1296
- ).viewValue,
1297
- fetchedAtOffset: offset
1298
- };
1299
- }
1300
- toQualifiedMemberId(memberId) {
1301
- if (!memberId) throw new Error("memberId is required");
1302
- return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
1303
- }
1304
- };
1305
- var AllocationService = class {
1306
- constructor(core, logger) {
1307
- this.core = core;
1308
- this.logger = logger;
1309
- }
1310
- async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
1311
- const allocationSpecificationNormalized = {
1312
- ...allocationSpecification,
1313
- settlement: {
1314
- ...allocationSpecification.settlement,
1315
- meta: allocationSpecification.settlement.meta ?? { values: {} }
1316
- },
1317
- transferLeg: {
1318
- ...allocationSpecification.transferLeg,
1319
- meta: allocationSpecification.transferLeg.meta ?? {
1320
- values: {}
1321
- }
1322
- }
1323
- };
1324
- const inputHoldingCids = await this.core.getInputHoldingsCids(
1325
- allocationSpecificationNormalized.transferLeg.sender,
1326
- inputUtxos
1327
- );
1328
- return {
1329
- expectedAdmin,
1330
- allocation: allocationSpecificationNormalized,
1331
- requestedAt: requestedAt ?? new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
1332
- inputHoldingCids,
1333
- extraArgs: {
1334
- context: { values: {} },
1335
- meta: { values: {} }
1336
- }
1337
- };
1338
- }
1339
- async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
1340
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocation-instruction/v1/allocation-factory", {
1341
- choiceArguments: choiceArgs,
1342
- excludeDebugFields
1343
- });
1344
- }
1345
- async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
1346
- choiceArgs.extraArgs.context = {
1347
- ...choiceContext.choiceContextData,
1348
- values: choiceContext.choiceContextData?.values ?? {}
1349
- };
1350
- const exercise = {
1351
- templateId: ALLOCATION_FACTORY_INTERFACE_ID,
1352
- contractId: factoryId,
1353
- choice: "AllocationFactory_Allocate",
1354
- choiceArgument: choiceArgs
1355
- };
1356
- return [exercise, choiceContext.disclosedContracts];
1357
- }
1358
- async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
1359
- const choiceArgs = await this.buildAllocationFactoryChoiceArgs(
1360
- allocationSpecification,
1361
- expectedAdmin,
1362
- inputUtxos,
1363
- requestedAt
1364
- );
1365
- if (prefetchedRegistryChoiceContext) {
1366
- return this.createAllocationInstructionFromContext(
1367
- prefetchedRegistryChoiceContext.factoryId,
1368
- choiceArgs,
1369
- prefetchedRegistryChoiceContext.choiceContext
1370
- );
1371
- }
1372
- const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(
1373
- registryUrl,
1374
- choiceArgs
1375
- );
1376
- return this.createAllocationInstructionFromContext(
1377
- factoryId,
1378
- choiceArgs,
1379
- choiceContext
1380
- );
1381
- }
1382
- buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
1383
- const exercise = {
1384
- templateId,
1385
- contractId,
1386
- choice,
1387
- choiceArgument: {
1388
- extraArgs: {
1389
- context: choiceContext.choiceContextData,
1390
- meta: EMPTY_META
1391
- }
1392
- }
1393
- };
1394
- return [exercise, choiceContext.disclosedContracts ?? []];
1395
- }
1396
- async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
1397
- return this.core.getTokenStandardClient(registryUrl).post(
1398
- "/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer",
1399
- {
1400
- excludeDebugFields: true
1401
- },
1402
- {
1403
- path: {
1404
- allocationId
1405
- }
1406
- }
1407
- );
1408
- }
1409
- createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
1410
- return this.buildAllocationExerciseWithContext(
1411
- ALLOCATION_INTERFACE_ID,
1412
- allocationCid,
1413
- "Allocation_ExecuteTransfer",
1414
- choiceContext
1415
- );
1416
- }
1417
- async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1418
- if (prefetchedRegistryChoiceContext) {
1419
- return this.createExecuteTransferAllocationFromContext(
1420
- allocationCid,
1421
- prefetchedRegistryChoiceContext
1422
- );
1423
- }
1424
- const choiceContext = await this.fetchExecuteTransferChoiceContext(
1425
- allocationCid,
1426
- registryUrl
1427
- );
1428
- return this.createExecuteTransferAllocationFromContext(
1429
- allocationCid,
1430
- choiceContext
1431
- );
1432
- }
1433
- async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
1434
- return this.core.getTokenStandardClient(registryUrl).post(
1435
- "/registry/allocations/v1/{allocationId}/choice-contexts/withdraw",
1436
- {
1437
- excludeDebugFields: true
1438
- },
1439
- { path: { allocationId: allocationCid } }
1440
- );
1441
- }
1442
- createWithdrawAllocationFromContext(allocationCid, choiceContext) {
1443
- return this.buildAllocationExerciseWithContext(
1444
- ALLOCATION_INTERFACE_ID,
1445
- allocationCid,
1446
- "Allocation_Withdraw",
1447
- choiceContext
1448
- );
1449
- }
1450
- async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1451
- if (prefetchedRegistryChoiceContext) {
1452
- return this.createWithdrawAllocationFromContext(
1453
- allocationCid,
1454
- prefetchedRegistryChoiceContext
1455
- );
1456
- }
1457
- const choiceContext = await this.fetchWithdrawAllocationChoiceContext(
1458
- allocationCid,
1459
- registryUrl
1460
- );
1461
- return this.createWithdrawAllocationFromContext(
1462
- allocationCid,
1463
- choiceContext
1464
- );
1465
- }
1466
- async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
1467
- return this.core.getTokenStandardClient(registryUrl).post(
1468
- "/registry/allocations/v1/{allocationId}/choice-contexts/cancel",
1469
- {
1470
- excludeDebugFields: true
1471
- },
1472
- { path: { allocationId: allocationCid } }
1473
- );
1474
- }
1475
- createCancelAllocationFromContext(allocationCid, choiceContext) {
1476
- return this.buildAllocationExerciseWithContext(
1477
- ALLOCATION_INTERFACE_ID,
1478
- allocationCid,
1479
- "Allocation_Cancel",
1480
- choiceContext
1481
- );
1482
- }
1483
- async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1484
- if (prefetchedRegistryChoiceContext) {
1485
- return this.createCancelAllocationFromContext(
1486
- allocationCid,
1487
- prefetchedRegistryChoiceContext
1488
- );
1489
- }
1490
- const choiceContext = await this.fetchCancelAllocationChoiceContext(
1491
- allocationCid,
1492
- registryUrl
1493
- );
1494
- return this.createCancelAllocationFromContext(
1495
- allocationCid,
1496
- choiceContext
1497
- );
1498
- }
1499
- async createWithdrawAllocationInstruction(allocationInstructionCid) {
1500
- const exercise = {
1501
- templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
1502
- contractId: allocationInstructionCid,
1503
- choice: "AllocationInstruction_Withdraw",
1504
- choiceArgument: {
1505
- extraArgs: {
1506
- context: { values: {} },
1507
- meta: { values: {} }
1508
- }
1509
- }
1510
- };
1511
- return [exercise, []];
1512
- }
1513
- async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
1514
- const exercise = {
1515
- templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
1516
- contractId: allocationInstructionCid,
1517
- choice: "AllocationInstruction_Update",
1518
- choiceArgument: {
1519
- extraActors,
1520
- extraArgs: {
1521
- context: { values: extraArgsContext },
1522
- meta: { values: extraArgsMeta }
1523
- }
1524
- }
1525
- };
1526
- return [exercise, []];
1527
- }
1528
- async createRejectAllocationRequest(allocationRequestCid, actor) {
1529
- const exercise = {
1530
- templateId: ALLOCATION_REQUEST_INTERFACE_ID,
1531
- contractId: allocationRequestCid,
1532
- choice: "AllocationRequest_Reject",
1533
- choiceArgument: {
1534
- actor,
1535
- extraArgs: {
1536
- context: { values: {} },
1537
- meta: { values: {} }
1538
- }
1539
- }
1540
- };
1541
- return [exercise, []];
1542
- }
1543
- async createWithdrawAllocationRequest(allocationRequestCid) {
1544
- const exercise = {
1545
- templateId: ALLOCATION_REQUEST_INTERFACE_ID,
1546
- contractId: allocationRequestCid,
1547
- choice: "AllocationRequest_Withdraw",
1548
- choiceArgument: {
1549
- extraArgs: {
1550
- context: { values: {} },
1551
- meta: { values: {} }
1552
- }
1553
- }
1554
- };
1555
- return [exercise, []];
1556
- }
1557
- };
1558
- var TransferService = class {
1559
- constructor(core, logger) {
1560
- this.core = core;
1561
- this.logger = logger;
1562
- }
1563
- async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta) {
1564
- const inputHoldingCids = await this.core.getInputHoldingsCids(
1565
- sender,
1566
- inputUtxos,
1567
- parseFloat(amount)
1568
- );
1569
- return {
1570
- expectedAdmin: instrumentAdmin,
1571
- transfer: {
1572
- sender,
1573
- receiver,
1574
- amount,
1575
- instrumentId: { admin: instrumentAdmin, id: instrumentId },
1576
- requestedAt: new Date(
1577
- Date.now() - REQUESTED_AT_SKEW_MS
1578
- ).toISOString(),
1579
- executeBefore: (expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1e3)).toISOString(),
1580
- inputHoldingCids,
1581
- meta: {
1582
- values: {
1583
- [TokenStandardService.MEMO_KEY]: memo || "",
1584
- ...meta?.values
1585
- }
1586
- }
1587
- },
1588
- extraArgs: {
1589
- context: { values: {} },
1590
- meta: { values: {} }
1591
- }
1592
- };
1593
- }
1594
- async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
1595
- return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
1596
- choiceArguments: choiceArgs,
1597
- excludeDebugFields
1598
- });
1599
- }
1600
- async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
1601
- this.logger.debug("Creating transfer from pre-fetched context...");
1602
- choiceArgs.extraArgs.context = {
1603
- ...choiceContext.choiceContextData,
1604
- values: choiceContext.choiceContextData?.values ?? {}
1605
- };
1606
- const exercise = {
1607
- templateId: TRANSFER_FACTORY_INTERFACE_ID,
1608
- contractId: factoryId,
1609
- choice: "TransferFactory_Transfer",
1610
- choiceArgument: choiceArgs
1611
- };
1612
- return [exercise, choiceContext.disclosedContracts];
1613
- }
1614
- // TODO: use named parameters
1615
- async createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext) {
1616
- try {
1617
- const choiceArgs = await this.buildTransferChoiceArgs(
1618
- sender,
1619
- receiver,
1620
- amount,
1621
- instrumentAdmin,
1622
- instrumentId,
1623
- inputUtxos,
1624
- memo,
1625
- expiryDate,
1626
- meta
1627
- );
1628
- if (prefetchedRegistryChoiceContext) {
1629
- return this.createTransferFromContext(
1630
- prefetchedRegistryChoiceContext.factoryId,
1631
- choiceArgs,
1632
- prefetchedRegistryChoiceContext.choiceContext
1633
- );
1634
- }
1635
- const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(
1636
- registryUrl,
1637
- choiceArgs
1638
- );
1639
- return this.createTransferFromContext(
1640
- factoryId,
1641
- choiceArgs,
1642
- choiceContext
1643
- );
1644
- } catch (e) {
1645
- this.logger.error("Failed to execute transfer:", e);
1646
- throw e;
1647
- }
1648
- }
1649
- async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
1650
- const client = this.core.getTokenStandardClient(registryUrl);
1651
- const choiceContext = await client.post(
1652
- "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept",
1653
- {
1654
- excludeDebugFields: true
1655
- },
1656
- {
1657
- path: {
1658
- transferInstructionId: transferInstructionCid
1659
- }
1660
- }
1661
- );
1662
- return {
1663
- choiceContextData: choiceContext.choiceContextData,
1664
- disclosedContracts: choiceContext.disclosedContracts
1665
- };
1666
- }
1667
- async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
1668
- try {
1669
- const exercise = {
1670
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
1671
- contractId: transferInstructionCid,
1672
- choice: "TransferInstruction_Accept",
1673
- choiceArgument: {
1674
- extraArgs: {
1675
- context: choiceContext.choiceContextData,
1676
- meta: { values: {} }
1677
- }
1678
- }
1679
- };
1680
- return [exercise, choiceContext.disclosedContracts];
1681
- } catch (e) {
1682
- this.logger.error(
1683
- "Failed to create accept transfer instruction:",
1684
- e
1685
- );
1686
- throw e;
1687
- }
1688
- }
1689
- async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1690
- const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(
1691
- transferInstructionCid,
1692
- registryUrl.href
1693
- );
1694
- const choiceArgs = {
1695
- cid: acceptTransferInstructionContext.contractId,
1696
- proxyArg: {
1697
- featuredAppRightCid,
1698
- beneficiaries,
1699
- choiceArg: acceptTransferInstructionContext.choiceArgument
1700
- }
1701
- };
1702
- return [
1703
- {
1704
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1705
- contractId: proxyCid,
1706
- choice: "DelegateProxy_TransferInstruction_Accept",
1707
- choiceArgument: choiceArgs
1708
- },
1709
- disclosedContracts
1710
- ];
1711
- }
1712
- async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1713
- const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(
1714
- transferInstructionCid,
1715
- registryUrl.href
1716
- );
1717
- const choiceArgs = {
1718
- cid: rejectTransferInstructionContext.contractId,
1719
- proxyArg: {
1720
- featuredAppRightCid,
1721
- beneficiaries,
1722
- choiceArg: rejectTransferInstructionContext.choiceArgument
1723
- }
1724
- };
1725
- return [
1726
- {
1727
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1728
- contractId: proxyCid,
1729
- choice: "DelegateProxy_TransferInstruction_Reject",
1730
- choiceArgument: choiceArgs
1731
- },
1732
- disclosedContracts
1733
- ];
1734
- }
1735
- async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1736
- const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(
1737
- transferInstructionCid,
1738
- registryUrl.href
1739
- );
1740
- const sumOfWeights = beneficiaries.reduce(
1741
- (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
1742
- 0
1743
- );
1744
- if (sumOfWeights > 1) {
1745
- throw new Error("Sum of beneficiary weights is larger than 1.");
1746
- }
1747
- const choiceArgs = {
1748
- cid: withdrawTransferInstructionContext.contractId,
1749
- proxyArg: {
1750
- featuredAppRightCid,
1751
- beneficiaries,
1752
- choiceArg: withdrawTransferInstructionContext.choiceArgument
1753
- }
1754
- };
1755
- return [
1756
- {
1757
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1758
- contractId: proxyCid,
1759
- choice: "DelegateProxy_TransferInstruction_Withdraw",
1760
- choiceArgument: choiceArgs
1761
- },
1762
- disclosedContracts
1763
- ];
1764
- }
1765
- async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
1766
- if (prefetchedRegistryChoiceContext) {
1767
- return this.createAcceptTransferInstructionFromContext(
1768
- transferInstructionCid,
1769
- {
1770
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
1771
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
1772
- }
1773
- );
1774
- }
1775
- const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(
1776
- transferInstructionCid,
1777
- registryUrl
1778
- );
1779
- return this.createAcceptTransferInstructionFromContext(
1780
- transferInstructionCid,
1781
- choiceContext
1782
- );
1783
- }
1784
- async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
1785
- const client = this.core.getTokenStandardClient(registryUrl);
1786
- const choiceContext = await client.post(
1787
- "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject",
1788
- {
1789
- excludeDebugFields: true
1790
- },
1791
- {
1792
- path: {
1793
- transferInstructionId: transferInstructionCid
1794
- }
1795
- }
1796
- );
1797
- return {
1798
- choiceContextData: choiceContext.choiceContextData,
1799
- disclosedContracts: choiceContext.disclosedContracts
1800
- };
1801
- }
1802
- async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
1803
- try {
1804
- const exercise = {
1805
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
1806
- contractId: transferInstructionCid,
1807
- choice: "TransferInstruction_Reject",
1808
- choiceArgument: {
1809
- extraArgs: {
1810
- context: choiceContext.choiceContextData,
1811
- meta: { values: {} }
1812
- }
1813
- }
1814
- };
1815
- return [exercise, choiceContext.disclosedContracts];
1816
- } catch (e) {
1817
- this.logger.error(
1818
- "Failed to create reject transfer instruction:",
1819
- e
1820
- );
1821
- throw e;
1822
- }
1823
- }
1824
- async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
1825
- if (prefetchedRegistryChoiceContext) {
1826
- return this.createRejectTransferInstructionFromContext(
1827
- transferInstructionCid,
1828
- {
1829
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
1830
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
1831
- }
1832
- );
1833
- }
1834
- const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(
1835
- transferInstructionCid,
1836
- registryUrl
1837
- );
1838
- return this.createRejectTransferInstructionFromContext(
1839
- transferInstructionCid,
1840
- choiceContext
1841
- );
1842
- }
1843
- async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
1844
- const client = this.core.getTokenStandardClient(registryUrl);
1845
- const choiceContext = await client.post(
1846
- "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw",
1847
- {
1848
- excludeDebugFields: true
1849
- },
1850
- {
1851
- path: {
1852
- transferInstructionId: transferInstructionCid
1853
- }
18
+ defaultRetryableOptions,
19
+ {
20
+ query: {
21
+ limit: COMPLETIONS_LIMIT,
22
+ stream_idle_timeout_ms: COMPLETIONS_STREAM_IDLE_TIMEOUT_MS
1854
23
  }
1855
- );
1856
- return {
1857
- choiceContextData: choiceContext.choiceContextData,
1858
- disclosedContracts: choiceContext.disclosedContracts
1859
- };
1860
- }
1861
- async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
1862
- try {
1863
- const exercise = {
1864
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
1865
- contractId: transferInstructionCid,
1866
- choice: "TransferInstruction_Withdraw",
1867
- choiceArgument: {
1868
- extraArgs: {
1869
- context: choiceContext.choiceContextData,
1870
- meta: { values: {} }
1871
- }
1872
- }
1873
- };
1874
- return [exercise, choiceContext.disclosedContracts];
1875
- } catch (e) {
1876
- this.logger.error(
1877
- "Failed to create withdraw transfer instruction:",
1878
- e
1879
- );
1880
- throw e;
1881
24
  }
1882
- }
1883
- async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
1884
- if (prefetchedRegistryChoiceContext) {
1885
- return this.createWithdrawTransferInstructionFromContext(
1886
- transferInstructionCid,
1887
- {
1888
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
1889
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
1890
- }
1891
- );
25
+ );
26
+ const completions = responses.filter(
27
+ (r) => "Completion" in r.completionResponse
28
+ );
29
+ const wantedCompletion = responses.find((r) => {
30
+ if ("Completion" in r.completionResponse) {
31
+ const completion = r.completionResponse.Completion.value;
32
+ return completion.userId === userId && (completion.commandId === commandIdOrSubmissionId || completion.submissionId === commandIdOrSubmissionId);
1892
33
  }
1893
- const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(
1894
- transferInstructionCid,
1895
- registryUrl
1896
- );
1897
- return this.createWithdrawTransferInstructionFromContext(
1898
- transferInstructionCid,
1899
- choiceContext
1900
- );
1901
- }
1902
- async createTransferInstruction(transferInstructionCid, registryUrl, instructionChoice, prefetchedRegistryChoiceContext) {
1903
- switch (instructionChoice) {
1904
- case "Accept":
1905
- return this.createAcceptTransferInstruction(
1906
- transferInstructionCid,
1907
- registryUrl,
1908
- prefetchedRegistryChoiceContext
1909
- );
1910
- case "Reject":
1911
- return this.createRejectTransferInstruction(
1912
- transferInstructionCid,
1913
- registryUrl,
1914
- prefetchedRegistryChoiceContext
1915
- );
1916
- case "Withdraw":
1917
- return this.createWithdrawTransferInstruction(
1918
- transferInstructionCid,
1919
- registryUrl,
1920
- prefetchedRegistryChoiceContext
1921
- );
34
+ return false;
35
+ });
36
+ if (wantedCompletion && "Completion" in wantedCompletion.completionResponse) {
37
+ const completion = wantedCompletion.completionResponse.Completion.value;
38
+ const status = completion.status;
39
+ if (status && status.code !== 0) {
40
+ throw asGrpcError(status);
1922
41
  }
1923
- }
1924
- };
1925
- var TokenStandardService = class {
1926
- constructor(ledgerClient, logger, accessTokenProvider, isMasterUser) {
1927
- this.ledgerClient = ledgerClient;
1928
- this.logger = logger;
1929
- this.accessTokenProvider = accessTokenProvider;
1930
- this.isMasterUser = isMasterUser;
1931
- __publicField(this, "core");
1932
- __publicField(this, "allocation");
1933
- __publicField(this, "transfer");
1934
- this.core = new CoreService(
42
+ return completion;
43
+ } else {
44
+ const lastCompletion = completions[completions.length - 1];
45
+ const newLedgerEnd = lastCompletion && "Completion" in lastCompletion.completionResponse ? lastCompletion.completionResponse.Completion.value.offset : void 0;
46
+ return awaitCompletion(
1935
47
  ledgerClient,
1936
- logger,
1937
- accessTokenProvider,
1938
- isMasterUser,
1939
- void 0,
1940
- void 0
48
+ newLedgerEnd || ledgerEnd,
49
+ // !newLedgerEnd implies response was empty
50
+ partyId,
51
+ userId,
52
+ commandIdOrSubmissionId
1941
53
  );
1942
- this.allocation = new AllocationService(this.core, this.logger);
1943
- this.transfer = new TransferService(this.core, this.logger);
1944
54
  }
1945
- async getInstrumentById(registryUrl, instrumentId) {
1946
- try {
1947
- const params = {
1948
- path: {
1949
- instrumentId
1950
- }
1951
- };
1952
- const client = this.core.getTokenStandardClient(registryUrl);
1953
- return client.get(
1954
- "/registry/metadata/v1/instruments/{instrumentId}",
1955
- params
1956
- );
1957
- } catch (e) {
1958
- this.logger.error(e);
1959
- throw new Error(
1960
- `Instrument id ${instrumentId} does not exist for this instrument admin.`
1961
- );
55
+ }
56
+ async function promiseWithTimeout(promise, timeoutMs, errorMessage) {
57
+ let timeoutPid = null;
58
+ const timeoutPromise = new Promise((_resolve, reject) => {
59
+ timeoutPid = setTimeout(() => reject(errorMessage), timeoutMs);
60
+ });
61
+ try {
62
+ return await Promise.race([promise, timeoutPromise]);
63
+ } finally {
64
+ if (timeoutPid) {
65
+ clearTimeout(timeoutPid);
1962
66
  }
1963
67
  }
1964
- async getInstrumentAdmin(registryUrl) {
1965
- const client = this.core.getTokenStandardClient(registryUrl);
1966
- const info = await client.get("/registry/metadata/v1/info");
1967
- return info.adminId;
1968
- }
1969
- async listInstruments(registryUrl, pageSize, pageToken) {
1970
- const client = this.core.getTokenStandardClient(registryUrl);
1971
- return client.get("/registry/metadata/v1/instruments", {
1972
- query: {
1973
- ...pageSize && { pageSize },
1974
- ...pageToken && { pageToken }
1975
- }
1976
- });
1977
- }
1978
- // <T> is shape of viewValue related to queried interface.
1979
- // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
1980
- async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
1981
- return this.core.listContractsByInterface(
1982
- interfaceId,
1983
- partyId,
1984
- limit,
1985
- offset,
1986
- continueUntilCompletion
1987
- );
1988
- }
1989
- async listHoldingTransactions(partyId, afterOffset, beforeOffset) {
68
+ }
69
+ var defaultRetryableOptions = {
70
+ retries: 5,
71
+ delayMs: 3e3,
72
+ cantonErrorKeys: [
73
+ "SEQUENCER_REQUEST_FAILED",
74
+ "SEQUENCER_BACKPRESSURE",
75
+ "SUBMISSION_ALREADY_IN_FLIGHT",
76
+ "LOCAL_VERDICT_TIMEOUT",
77
+ "NOT_SEQUENCED_TIMEOUT",
78
+ "NO_VIEW_WITH_VALID_RECIPIENTS"
79
+ ]
80
+ };
81
+ async function retryable(fn, retryableOptions2, logger) {
82
+ for (let attempts = 1; attempts <= retryableOptions2.retries; attempts++) {
1990
83
  try {
1991
- this.logger.debug("Set or query offset");
1992
- const afterOffsetOrLatest = Number(afterOffset) || (await this.ledgerClient.getWithRetry(
1993
- "/v2/state/latest-pruned-offsets"
1994
- )).participantPrunedUpToInclusive;
1995
- const beforeOffsetOrLatest = Number(beforeOffset) || (await this.ledgerClient.getWithRetry("/v2/state/ledger-end")).offset;
1996
- this.logger.debug(afterOffsetOrLatest, "Using offset");
1997
- const updatesResponse = await this.ledgerClient.postWithRetry("/v2/updates/flats", {
1998
- updateFormat: {
1999
- includeTransactions: {
2000
- eventFormat: EventFilterBySetup({
2001
- interfaceIds: TokenStandardTransactionInterfaces,
2002
- isMasterUser: this.isMasterUser,
2003
- partyId,
2004
- includeWildcard: true
2005
- }),
2006
- transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
2007
- }
2008
- },
2009
- beginExclusive: afterOffsetOrLatest,
2010
- endInclusive: beforeOffsetOrLatest,
2011
- verbose: false
2012
- });
2013
- return this.core.toPrettyTransactions(
2014
- updatesResponse,
2015
- partyId,
2016
- this.ledgerClient
2017
- );
84
+ return await fn();
2018
85
  } catch (err) {
2019
- this.logger.error("Failed to list holding transactions.", err);
2020
- throw err;
2021
- }
2022
- }
2023
- async getTransactionById(updateId, partyId) {
2024
- const transactionFormat = {
2025
- eventFormat: EventFilterBySetup({
2026
- interfaceIds: TokenStandardTransactionInterfaces,
2027
- isMasterUser: this.isMasterUser,
2028
- partyId,
2029
- includeWildcard: true
2030
- }),
2031
- transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
2032
- };
2033
- const getTransactionResponse = await this.ledgerClient.postWithRetry(
2034
- "/v2/updates/transaction-by-id",
2035
- {
2036
- updateId,
2037
- transactionFormat
86
+ const grpcError = asGrpcError(err);
87
+ const message = grpcError.message;
88
+ const shouldRetry = retryableOptions2.cantonErrorKeys.length === 0 || retryableOptions2.cantonErrorKeys.some(
89
+ (key) => message.includes(key)
90
+ );
91
+ if (attempts < retryableOptions2.retries && shouldRetry) {
92
+ logger?.warn(
93
+ `Caught retryiable error: ${message}. Retrying attempt ${attempts} of ${retryableOptions2.retries}...`
94
+ );
95
+ await new Promise(
96
+ (res) => setTimeout(res, retryableOptions2.delayMs)
97
+ );
98
+ } else {
99
+ throw grpcError;
2038
100
  }
2039
- );
2040
- return this.core.toPrettyTransaction(
2041
- getTransactionResponse,
2042
- partyId,
2043
- this.ledgerClient
2044
- );
2045
- }
2046
- async getInputHoldingsCids(sender, inputUtxos, amount) {
2047
- return this.core.getInputHoldingsCids(sender, inputUtxos, amount);
2048
- }
2049
- async createDelegateProxyTranfser(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, featuredAppRightCid, proxyCid, beneficiaries, inputUtxos, memo, expiryDate, meta) {
2050
- const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(
2051
- sender,
2052
- receiver,
2053
- amount,
2054
- instrumentAdmin,
2055
- instrumentId,
2056
- registryUrl,
2057
- inputUtxos,
2058
- memo,
2059
- expiryDate,
2060
- meta
2061
- );
2062
- const sumOfWeights = beneficiaries.reduce(
2063
- (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
2064
- 0
2065
- );
2066
- if (sumOfWeights > 1) {
2067
- throw new Error("Sum of beneficiary weights is larger than 1.");
2068
101
  }
2069
- const choiceArgs = {
2070
- cid: transferCommand.contractId,
2071
- proxyArg: {
2072
- featuredAppRightCid,
2073
- beneficiaries,
2074
- choiceArg: transferCommand.choiceArgument
2075
- }
2076
- };
2077
- const exercise = {
2078
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
2079
- contractId: proxyCid,
2080
- choice: "DelegateProxy_TransferFactory_Transfer",
2081
- choiceArgument: choiceArgs
2082
- };
2083
- return [exercise, disclosedContracts];
2084
- }
2085
- async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
2086
- const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(
2087
- transferInstructionCid,
2088
- registryUrl
2089
- );
2090
- const choiceArgs = {
2091
- cid: acceptTransferInstructionContext.contractId,
2092
- proxyArg: {
2093
- featuredAppRightCid,
2094
- beneficiaries: [
2095
- {
2096
- beneficiary: exchangeParty,
2097
- weight: 1
2098
- }
2099
- ],
2100
- choiceArg: acceptTransferInstructionContext.choiceArgument
2101
- }
2102
- };
2103
- return [
2104
- {
2105
- templateId: "#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy",
2106
- contractId: proxyCid,
2107
- choice: "DelegateProxy_TransferInstruction_Accept",
2108
- choiceArgument: choiceArgs
2109
- },
2110
- disclosedContracts
2111
- ];
2112
102
  }
2113
- static isHoldingLocked(holding, currentTime = /* @__PURE__ */ new Date()) {
2114
- const lock = holding.lock;
2115
- if (!lock) return false;
2116
- const expiresAt = lock.expiresAt;
2117
- if (!expiresAt) return true;
2118
- const expiresAtDate = new Date(expiresAt);
2119
- return currentTime < expiresAtDate;
103
+ throw new Error("retryable: Exceeded maximum retries without throwing.");
104
+ }
105
+ var isJsCantonError = (e) => typeof e === "object" && e !== null && "code" in e && "cause" in e && "errorCategory" in e;
106
+ var asJsCantonError = (e) => {
107
+ if (isJsCantonError(e)) {
108
+ return e;
109
+ } else {
110
+ throw e;
2120
111
  }
2121
112
  };
2122
- __publicField(TokenStandardService, "MEMO_KEY", "splice.lfdecentralizedtrust.org/reason");
2123
-
2124
- // src/amulet-service.ts
2125
- var REQUESTED_AT_SKEW_MS2 = 6e4;
2126
- var AmuletService = class {
2127
- constructor(tokenStandard, scanProxyClient, scanClient) {
2128
- this.tokenStandard = tokenStandard;
2129
- this.scanProxyClient = scanProxyClient;
2130
- this.scanClient = scanClient;
2131
- }
2132
- async getTransferPreApprovalByParty(partyId) {
2133
- const { transfer_preapproval } = await this.scanProxyClient.get(
2134
- "/v0/scan-proxy/transfer-preapprovals/by-party/{party}",
2135
- {
2136
- path: {
2137
- party: partyId
2138
- }
2139
- }
2140
- );
2141
- return transfer_preapproval;
2142
- }
2143
- async getFeaturedAppsByParty(partyId) {
2144
- const { featured_app_right } = await this.scanProxyClient.get(
2145
- "/v0/scan-proxy/featured-apps/{provider_party_id}",
2146
- {
2147
- path: {
2148
- provider_party_id: partyId
2149
- }
2150
- }
2151
- );
2152
- return featured_app_right;
2153
- }
2154
- async buyMemberTraffic(dso, provider, trafficAmount, synchronizerId, memberId, migrationId, inputUtxos) {
2155
- const amuletRules = await this.scanProxyClient.getAmuletRules();
2156
- const activeRound = await this.scanProxyClient.getActiveOpenMiningRound();
2157
- const inputHoldings = await this.tokenStandard.getInputHoldingsCids(
2158
- provider,
2159
- inputUtxos,
2160
- trafficAmount
2161
- );
2162
- if (!amuletRules) {
2163
- throw new Error("AmuletRules contract not found");
2164
- }
2165
- if (!activeRound) {
2166
- throw new Error(
2167
- "OpenMiningRound active at current moment not found"
2168
- );
2169
- }
2170
- const disclosed = [
2171
- {
2172
- templateId: amuletRules.template_id,
2173
- contractId: amuletRules.contract_id,
2174
- createdEventBlob: amuletRules.created_event_blob,
2175
- synchronizerId
2176
- },
2177
- {
2178
- templateId: activeRound.template_id,
2179
- contractId: activeRound.contract_id,
2180
- createdEventBlob: activeRound.created_event_blob,
2181
- synchronizerId
2182
- }
2183
- ];
2184
- const context = {
2185
- openMiningRound: activeRound.contract_id,
2186
- issuingMiningRounds: [],
2187
- validatorRights: [],
2188
- featuredAppRight: null
2189
- };
2190
- const choiceArgs = {
2191
- context,
2192
- inputs: inputHoldings.map((cid) => ({
2193
- tag: "InputAmulet",
2194
- value: cid
2195
- })),
2196
- provider,
2197
- memberId: this.tokenStandard.core.toQualifiedMemberId(memberId),
2198
- synchronizerId,
2199
- migrationId,
2200
- trafficAmount,
2201
- expectedDso: dso
2202
- };
2203
- const exercise = {
2204
- templateId: "#splice-amulet:Splice.AmuletRules:AmuletRules",
2205
- contractId: amuletRules.contract_id,
2206
- choice: "AmuletRules_BuyMemberTraffic",
2207
- choiceArgument: choiceArgs
2208
- };
2209
- return [exercise, disclosed];
113
+ var asGrpcError = (e) => {
114
+ let errorInfo = void 0;
115
+ let retryInfo = void 0;
116
+ let code = 500;
117
+ let message = e?.message || "";
118
+ if (typeof e === "object" && e !== null && "cause" in e) {
119
+ message = e.cause;
120
+ } else if (typeof e === "object" && e !== null && "message" in e) {
121
+ message = e.message;
2210
122
  }
2211
- async getMemberTrafficStatus(domainId, memberId) {
2212
- if (!this.scanClient) {
2213
- throw new Error("Scan API URL was not provided");
2214
- }
2215
- return this.scanClient.get(
2216
- "/v0/domains/{domain_id}/members/{member_id}/traffic-status",
2217
- {
2218
- path: {
2219
- domain_id: domainId,
2220
- member_id: this.tokenStandard.core.toQualifiedMemberId(memberId)
123
+ if (typeof e === "object" && e !== null && "code" in e && "message" in e && "details" in e && Array.isArray(e.details)) {
124
+ code = e.code;
125
+ message = e.message;
126
+ for (const detail of e.details) {
127
+ if (detail.typeUrl === "type.googleapis.com/google.rpc.ErrorInfo" && typeof detail.value === "string") {
128
+ try {
129
+ errorInfo = ErrorInfo.fromBinary(
130
+ Buffer.from(detail.value, "base64")
131
+ );
132
+ } catch {
2221
133
  }
2222
- }
2223
- );
2224
- }
2225
- async selfGrantFeatureAppRight(providerPartyId, synchronizerId) {
2226
- const amuletRules = await this.scanProxyClient.getAmuletRules();
2227
- const disclosedContracts = {
2228
- templateId: amuletRules.template_id,
2229
- contractId: amuletRules.contract_id,
2230
- createdEventBlob: amuletRules.created_event_blob,
2231
- synchronizerId
2232
- };
2233
- return [
2234
- {
2235
- templateId: amuletRules.template_id,
2236
- contractId: amuletRules.contract_id,
2237
- choice: "AmuletRules_DevNet_FeatureApp",
2238
- choiceArgument: {
2239
- provider: providerPartyId
134
+ } else if (detail.typeUrl === "type.googleapis.com/google.rpc.RetryInfo" && typeof detail.value === "string") {
135
+ try {
136
+ retryInfo = RetryInfo.fromBinary(
137
+ Buffer.from(detail.value, "base64")
138
+ );
139
+ } catch {
2240
140
  }
2241
- },
2242
- [disclosedContracts]
2243
- ];
2244
- }
2245
- async cancelTransferPreapproval(contractId, templateId, actor) {
2246
- const exercise = {
2247
- templateId,
2248
- contractId,
2249
- choice: "TransferPreapproval_Cancel",
2250
- choiceArgument: { p: actor }
2251
- };
2252
- return [exercise, []];
2253
- }
2254
- async renewTransferPreapproval(contractId, templateId, provider, synchronizerId, newExpiresAt, inputUtxos) {
2255
- const amuletRules = await this.scanProxyClient.getAmuletRules();
2256
- const activeRound = await this.scanProxyClient.getActiveOpenMiningRound();
2257
- if (!amuletRules) {
2258
- throw new Error("AmuletRules contract not found");
2259
- }
2260
- if (!activeRound) {
2261
- throw new Error(
2262
- "OpenMiningRound active at current moment not found"
2263
- );
2264
- }
2265
- const disclosed = [
2266
- {
2267
- templateId: amuletRules.template_id,
2268
- contractId: amuletRules.contract_id,
2269
- createdEventBlob: amuletRules.created_event_blob,
2270
- synchronizerId
2271
- },
2272
- {
2273
- templateId: activeRound.template_id,
2274
- contractId: activeRound.contract_id,
2275
- createdEventBlob: activeRound.created_event_blob,
2276
- synchronizerId
2277
- }
2278
- ];
2279
- const inputHoldings = await this.tokenStandard.getInputHoldingsCids(
2280
- provider,
2281
- inputUtxos
2282
- );
2283
- const context = {
2284
- context: {
2285
- openMiningRound: activeRound.contract_id,
2286
- issuingMiningRounds: [],
2287
- validatorRights: [],
2288
- featuredAppRight: null
2289
- },
2290
- amuletRules: amuletRules.contract_id
2291
- };
2292
- const effectiveNewExpiresAt = newExpiresAt ?? new Date(Date.now() + 90 * 24 * 3600 * 1e3);
2293
- const exercise = {
2294
- templateId,
2295
- contractId,
2296
- choice: "TransferPreapproval_Renew",
2297
- choiceArgument: {
2298
- context,
2299
- inputs: inputHoldings.map((cid) => ({
2300
- tag: "InputAmulet",
2301
- value: cid
2302
- })),
2303
- newExpiresAt: effectiveNewExpiresAt.toISOString()
2304
- }
2305
- };
2306
- return [exercise, disclosed];
2307
- }
2308
- async createTap(receiver, amount, instrumentAdmin, instrumentId, registryUrl) {
2309
- const now = /* @__PURE__ */ new Date();
2310
- const tomorrow = new Date(now);
2311
- tomorrow.setDate(tomorrow.getDate() + 1);
2312
- const choiceArgs = {
2313
- expectedAdmin: instrumentAdmin,
2314
- transfer: {
2315
- sender: instrumentAdmin,
2316
- receiver,
2317
- amount,
2318
- instrumentId: { admin: instrumentAdmin, id: instrumentId },
2319
- lock: null,
2320
- requestedAt: new Date(
2321
- Date.now() - REQUESTED_AT_SKEW_MS2
2322
- ).toISOString(),
2323
- executeBefore: tomorrow.toISOString(),
2324
- inputHoldingCids: [],
2325
- meta: { values: {} }
2326
- },
2327
- extraArgs: {
2328
- context: { values: {} },
2329
- meta: { values: {} }
2330
141
  }
2331
- };
2332
- const disclosedContracts = (await this.tokenStandard.transfer.fetchTransferFactoryChoiceContext(
2333
- registryUrl,
2334
- choiceArgs
2335
- )).choiceContext.disclosedContracts;
2336
- const amuletRules = await this.scanProxyClient.getAmuletRules();
2337
- if (!amuletRules) {
2338
- throw new Error("AmuletRules contract not found");
2339
- }
2340
- const latestOpenMiningRound = await this.scanProxyClient.getActiveOpenMiningRound();
2341
- if (!latestOpenMiningRound) {
2342
- throw new Error(
2343
- "OpenMiningRound active at current moment not found"
2344
- );
2345
142
  }
2346
- return [
2347
- {
2348
- templateId: amuletRules.template_id,
2349
- contractId: amuletRules.contract_id,
2350
- choice: "AmuletRules_DevNet_Tap",
2351
- choiceArgument: {
2352
- receiver,
2353
- amount,
2354
- openRound: latestOpenMiningRound.contract_id
2355
- }
2356
- },
2357
- disclosedContracts
2358
- ];
143
+ } else {
144
+ throw e;
2359
145
  }
146
+ return { code, message, errorInfo, retryInfo };
2360
147
  };
2361
148
 
2362
149
  // src/acs/acs-container.ts
@@ -2877,11 +664,9 @@ var LedgerClient = class {
2877
664
  }
2878
665
  async init() {
2879
666
  if (!this.initialized) {
2880
- this.logger.debug(
2881
- "Initializing LedgerClient with version %s for url %s",
2882
- this.clientVersion,
2883
- this.baseUrl.href
2884
- );
667
+ this.logger.debug({
668
+ message: `Initializing LedgerClient with version ${this.clientVersion} for url ${this.baseUrl.href}`
669
+ });
2885
670
  const versionFromClient = await this.currentClient.GET("/v2/version");
2886
671
  this.logger.debug(versionFromClient, "getV2Version response");
2887
672
  this.clientVersion = this.parseSupportedVersions(
@@ -3177,14 +962,16 @@ var LedgerClient = class {
3177
962
  limit,
3178
963
  continueUntilCompletion
3179
964
  } = options;
965
+ if (continueUntilCompletion) {
966
+ const filter2 = this.buildActiveContractFilter(options);
967
+ return await this.fetchActiveContractsUntilComplete(
968
+ filter2,
969
+ limit ?? 200
970
+ );
971
+ }
3180
972
  const hasLimit = typeof limit === "number";
3181
973
  if (hasLimit) {
3182
974
  const filter2 = this.buildActiveContractFilter(options);
3183
- if (continueUntilCompletion)
3184
- return await this.fetchActiveContractsUntilComplete(
3185
- filter2,
3186
- limit
3187
- );
3188
975
  return await this.postWithRetry(
3189
976
  "/v2/state/active-contracts",
3190
977
  filter2,
@@ -3225,7 +1012,6 @@ var LedgerClient = class {
3225
1012
  * @private
3226
1013
  */
3227
1014
  async fetchActiveContractsUntilComplete(activeContractsArgs, limit) {
3228
- const result = [];
3229
1015
  const ledgerEnd = await this.getWithRetry("/v2/state/ledger-end");
3230
1016
  const bodyRequest = {
3231
1017
  beginExclusive: 0,
@@ -3235,9 +1021,11 @@ var LedgerClient = class {
3235
1021
  if (activeContractsArgs.filter)
3236
1022
  bodyRequest.filter = activeContractsArgs.filter;
3237
1023
  let currentOffset = 0;
1024
+ const allContractsData = /* @__PURE__ */ new Map();
1025
+ const exercisedContracts = /* @__PURE__ */ new Set();
3238
1026
  while (currentOffset < ledgerEnd.offset) {
3239
1027
  bodyRequest.beginExclusive = currentOffset;
3240
- const newResults = (await this.postWithRetry(
1028
+ const results = (await this.postWithRetry(
3241
1029
  "/v2/updates",
3242
1030
  bodyRequest,
3243
1031
  defaultRetryableOptions,
@@ -3250,30 +1038,36 @@ var LedgerClient = class {
3250
1038
  }
3251
1039
  throw new Error("Expected Transaction update");
3252
1040
  }).map((data) => {
3253
- const createdEvent = data.events?.find(
3254
- (event) => typeof event === "object" && event !== null && "CreatedEvent" in event
1041
+ const exercisedEvents = data.events?.filter((event) => "ExercisedEvent" in event).map(
1042
+ (event) => event.ExercisedEvent
1043
+ ).filter((event) => event.consuming);
1044
+ const createdEvents = data.events?.filter((event) => "CreatedEvent" in event).map(
1045
+ (event) => event.CreatedEvent
3255
1046
  );
3256
- if (!createdEvent || !("CreatedEvent" in createdEvent)) {
3257
- throw new Error(
3258
- "CreatedEvent not found in transaction events"
3259
- );
3260
- }
3261
- currentOffset = Math.max(currentOffset, data.offset);
3262
- return {
3263
- workflowId: data.workflowId,
3264
- contractEntry: {
3265
- JsActiveContract: {
3266
- synchronizerId: data.synchronizerId,
3267
- createdEvent: createdEvent.CreatedEvent,
3268
- reassignmentCounter: data.offset
1047
+ exercisedEvents?.forEach((event) => {
1048
+ exercisedContracts.add(event.contractId);
1049
+ });
1050
+ createdEvents?.forEach((event) => {
1051
+ allContractsData.set(event.contractId, {
1052
+ workflowId: data.workflowId,
1053
+ contractEntry: {
1054
+ JsActiveContract: {
1055
+ synchronizerId: data.synchronizerId,
1056
+ createdEvent: event,
1057
+ reassignmentCounter: data.offset
1058
+ }
3269
1059
  }
3270
- }
3271
- };
1060
+ });
1061
+ });
1062
+ currentOffset = Math.max(currentOffset, data.offset);
1063
+ return true;
3272
1064
  });
3273
- result.push(...newResults);
3274
- if (!newResults.length) currentOffset++;
1065
+ if (!results.length) currentOffset++;
3275
1066
  }
3276
- return result;
1067
+ exercisedContracts.forEach((cid) => {
1068
+ allContractsData.delete(cid);
1069
+ });
1070
+ return Array.from(allContractsData.values());
3277
1071
  }
3278
1072
  buildActiveContractFilter(options) {
3279
1073
  const filter = {
@@ -3434,6 +1228,6 @@ var WSSupportWithBackOffSwitch = class {
3434
1228
  }
3435
1229
  };
3436
1230
 
3437
- export { ACSContainer, ACS_UPDATE_CONFIG, AmuletService, CoreService, LedgerClient, TokenStandardService, TokenStandardTransactionInterfaces, TransactionParser, WSSupportWithBackOffSwitch, asJsCantonError, awaitCompletion, defaultRetryableOptions, isJsCantonError, promiseWithTimeout, supportedVersions };
1231
+ export { ACSContainer, ACS_UPDATE_CONFIG, LedgerClient, WSSupportWithBackOffSwitch, asJsCantonError, awaitCompletion, defaultRetryableOptions, isJsCantonError, promiseWithTimeout, supportedVersions };
3438
1232
  //# sourceMappingURL=index.js.map
3439
1233
  //# sourceMappingURL=index.js.map