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