@canton-network/core-ledger-client 0.27.3 → 0.29.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2373 +1,155 @@
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
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
-
12
- var BigNumber__default = /*#__PURE__*/_interopDefault(BigNumber);
13
- var createClient__default = /*#__PURE__*/_interopDefault(createClient);
14
-
15
- var __defProp = Object.defineProperty;
16
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
17
- 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
- var COMPLETIONS_LIMIT = "100";
135
- var COMPLETIONS_STREAM_IDLE_TIMEOUT_MS = "1000";
136
- async function awaitCompletion(ledgerClient, ledgerEnd, partyId, userId, commandIdOrSubmissionId) {
137
- const responses = await ledgerClient.postWithRetry(
138
- "/v2/commands/completions",
139
- {
140
- userId,
141
- parties: [partyId],
142
- beginExclusive: ledgerEnd
143
- },
144
- defaultRetryableOptions,
145
- {
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, continueUntilCompletion) {
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
- void 0,
1147
- void 0,
1148
- continueUntilCompletion
1149
- );
1150
- if (senderHoldings.length === 0) {
1151
- throw new Error(
1152
- "Sender has no holdings, so transfer can't be executed."
1153
- );
1154
- }
1155
- const unlockedSenderHoldings = senderHoldings.filter((utxo) => {
1156
- const lock = utxo.interfaceViewValue.lock;
1157
- if (!lock) return true;
1158
- const expiresAt = lock.expiresAt;
1159
- if (!expiresAt) return false;
1160
- const expiresAtDate = new Date(expiresAt);
1161
- return expiresAtDate <= now;
1162
- });
1163
- if (unlockedSenderHoldings.length > 100) {
1164
- this.logger.warn(`Sender has more than 100 unlocked utxos.`);
1165
- }
1166
- if (amount) {
1167
- return _CoreService.getInputHoldingsCidsForAmount(
1168
- amount,
1169
- unlockedSenderHoldings
1170
- );
1171
- } else {
1172
- return unlockedSenderHoldings.map((h) => h.contractId);
1173
- }
1174
- }
1175
- static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
1176
- const exactAmount = unlockedSenderHoldings.find(
1177
- (holding) => parseFloat(holding.interfaceViewValue.amount) === amount
1178
- );
1179
- if (exactAmount) {
1180
- return [exactAmount.contractId];
1181
- }
1182
- const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted(
1183
- (a, b) => parseFloat(a.interfaceViewValue.amount) - parseFloat(b.interfaceViewValue.amount)
1184
- );
1185
- const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
1186
- if (!largestHoldingAmount) {
1187
- throw new Error(`Sender doesn't have any unlocked holdings`);
1188
- }
1189
- let currentSum = parseFloat(
1190
- largestHoldingAmount.interfaceViewValue.amount
1191
- );
1192
- const cIds = [largestHoldingAmount.contractId];
1193
- for (const h of sortedUnlockedSenderHoldings) {
1194
- if (currentSum >= amount) {
1195
- break;
1196
- }
1197
- const currentHoldingAmount = parseFloat(h.interfaceViewValue.amount);
1198
- currentSum += currentHoldingAmount;
1199
- cIds.push(h.contractId);
1200
- }
1201
- if (currentSum < amount) {
1202
- throw new Error(
1203
- `Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount - currentSum}`
1204
- );
1205
- }
1206
- if (cIds.length > 100) {
1207
- throw new Error(
1208
- `Exceeded the maximum of 100 utxos in 1 transaction`
1209
- );
1210
- }
1211
- return cIds;
1212
- }
1213
- async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
1214
- try {
1215
- const ledgerEnd = offset ?? (await this.ledgerClient.getWithRetry("/v2/state/ledger-end")).offset;
1216
- const options = {
1217
- offset: ledgerEnd,
1218
- interfaceIds: [interfaceId],
1219
- parties: [partyId],
1220
- filterByParty: true,
1221
- continueUntilCompletion: Boolean(continueUntilCompletion)
1222
- };
1223
- if (limit !== void 0) {
1224
- options.limit = limit;
1225
- }
1226
- const acsResponses = await this.ledgerClient.activeContracts(options);
1227
- const isActiveContractEntry = (acsResponse) => "JsActiveContract" in acsResponse.contractEntry && !!acsResponse.contractEntry.JsActiveContract?.createdEvent;
1228
- const activeContractEntries = acsResponses.filter(
1229
- isActiveContractEntry
1230
- );
1231
- return activeContractEntries.map(
1232
- (response) => this.toPrettyContract(interfaceId, response, ledgerEnd)
1233
- );
1234
- } catch (err) {
1235
- this.logger.error(
1236
- `Failed to list contracts of interface ${interfaceId}`,
1237
- err
1238
- );
1239
- throw err;
1240
- }
1241
- }
1242
- async toPrettyTransactions(updates, partyId, ledgerClient) {
1243
- const isOffsetCheckpointUpdate = (updateResponse) => "OffsetCheckpoint" in updateResponse.update;
1244
- const isTransactionUpdate = (updateResponse) => "Transaction" in updateResponse.update && !!updateResponse.update.Transaction?.value;
1245
- const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map((update) => update.update.OffsetCheckpoint.value.offset);
1246
- const latestCheckpointOffset = Math.max(...offsetCheckpoints);
1247
- const transactions = await Promise.all(
1248
- updates.filter(isTransactionUpdate).map(async (update) => {
1249
- const tx = update.update.Transaction.value;
1250
- const parser = new TransactionParser(
1251
- tx,
1252
- ledgerClient,
1253
- partyId,
1254
- this.isMasterUser
1255
- );
1256
- return await parser.parseTransaction();
1257
- })
1258
- );
1259
- return {
1260
- // OffsetCheckpoint can be anywhere... or not at all, maybe
1261
- nextOffset: Math.max(
1262
- latestCheckpointOffset,
1263
- ...transactions.map((tx) => tx.offset)
1264
- ),
1265
- transactions: transactions.filter((tx) => tx.events.length > 0).map(renderTransaction)
1266
- };
1267
- }
1268
- async toPrettyTransaction(getTransactionResponse, partyId, ledgerClient) {
1269
- const tx = getTransactionResponse.transaction;
1270
- const parser = new TransactionParser(
1271
- tx,
1272
- ledgerClient,
1273
- partyId,
1274
- this.isMasterUser
1275
- );
1276
- const parsedTx = await parser.parseTransaction();
1277
- return renderTransaction(parsedTx);
1278
- }
1279
- async toPrettyTransactionsPerParty(updates, parties, ledgerClient) {
1280
- const all = await Promise.all(
1281
- parties.map(
1282
- async (partyId) => [
1283
- partyId,
1284
- await this.toPrettyTransactions(
1285
- updates,
1286
- partyId,
1287
- ledgerClient
1288
- )
1289
- ]
1290
- )
1291
- );
1292
- return new Map(all);
1293
- }
1294
- // returns object with JsActiveContract content
1295
- // and contractId and interface view value extracted from it as separate fields for convenience
1296
- toPrettyContract(interfaceId, response, offset) {
1297
- const activeContract = response.contractEntry.JsActiveContract;
1298
- const { createdEvent } = activeContract;
1299
- return {
1300
- contractId: createdEvent.contractId,
1301
- activeContract,
1302
- interfaceViewValue: ensureInterfaceViewIsPresent(
1303
- createdEvent,
1304
- interfaceId
1305
- ).viewValue,
1306
- fetchedAtOffset: offset
1307
- };
1308
- }
1309
- toQualifiedMemberId(memberId) {
1310
- if (!memberId) throw new Error("memberId is required");
1311
- return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
1312
- }
1313
- };
1314
- var AllocationService = class {
1315
- constructor(core, logger) {
1316
- this.core = core;
1317
- this.logger = logger;
1318
- }
1319
- async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
1320
- const allocationSpecificationNormalized = {
1321
- ...allocationSpecification,
1322
- settlement: {
1323
- ...allocationSpecification.settlement,
1324
- meta: allocationSpecification.settlement.meta ?? { values: {} }
1325
- },
1326
- transferLeg: {
1327
- ...allocationSpecification.transferLeg,
1328
- meta: allocationSpecification.transferLeg.meta ?? {
1329
- values: {}
1330
- }
1331
- }
1332
- };
1333
- const inputHoldingCids = await this.core.getInputHoldingsCids(
1334
- allocationSpecificationNormalized.transferLeg.sender,
1335
- inputUtxos
1336
- );
1337
- return {
1338
- expectedAdmin,
1339
- allocation: allocationSpecificationNormalized,
1340
- requestedAt: requestedAt ?? new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
1341
- inputHoldingCids,
1342
- extraArgs: {
1343
- context: { values: {} },
1344
- meta: { values: {} }
1345
- }
1346
- };
1347
- }
1348
- async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
1349
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocation-instruction/v1/allocation-factory", {
1350
- choiceArguments: choiceArgs,
1351
- excludeDebugFields
1352
- });
1353
- }
1354
- async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
1355
- choiceArgs.extraArgs.context = {
1356
- ...choiceContext.choiceContextData,
1357
- values: choiceContext.choiceContextData?.values ?? {}
1358
- };
1359
- const exercise = {
1360
- templateId: coreTokenStandard.ALLOCATION_FACTORY_INTERFACE_ID,
1361
- contractId: factoryId,
1362
- choice: "AllocationFactory_Allocate",
1363
- choiceArgument: choiceArgs
1364
- };
1365
- return [exercise, choiceContext.disclosedContracts];
1366
- }
1367
- async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
1368
- const choiceArgs = await this.buildAllocationFactoryChoiceArgs(
1369
- allocationSpecification,
1370
- expectedAdmin,
1371
- inputUtxos,
1372
- requestedAt
1373
- );
1374
- if (prefetchedRegistryChoiceContext) {
1375
- return this.createAllocationInstructionFromContext(
1376
- prefetchedRegistryChoiceContext.factoryId,
1377
- choiceArgs,
1378
- prefetchedRegistryChoiceContext.choiceContext
1379
- );
1380
- }
1381
- const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(
1382
- registryUrl,
1383
- choiceArgs
1384
- );
1385
- return this.createAllocationInstructionFromContext(
1386
- factoryId,
1387
- choiceArgs,
1388
- choiceContext
1389
- );
1390
- }
1391
- buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
1392
- const exercise = {
1393
- templateId,
1394
- contractId,
1395
- choice,
1396
- choiceArgument: {
1397
- extraArgs: {
1398
- context: choiceContext.choiceContextData,
1399
- meta: EMPTY_META
1400
- }
1401
- }
1402
- };
1403
- return [exercise, choiceContext.disclosedContracts ?? []];
1404
- }
1405
- async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
1406
- return this.core.getTokenStandardClient(registryUrl).post(
1407
- "/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer",
1408
- {
1409
- excludeDebugFields: true
1410
- },
1411
- {
1412
- path: {
1413
- allocationId
1414
- }
1415
- }
1416
- );
1417
- }
1418
- createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
1419
- return this.buildAllocationExerciseWithContext(
1420
- coreTokenStandard.ALLOCATION_INTERFACE_ID,
1421
- allocationCid,
1422
- "Allocation_ExecuteTransfer",
1423
- choiceContext
1424
- );
1425
- }
1426
- async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1427
- if (prefetchedRegistryChoiceContext) {
1428
- return this.createExecuteTransferAllocationFromContext(
1429
- allocationCid,
1430
- prefetchedRegistryChoiceContext
1431
- );
1432
- }
1433
- const choiceContext = await this.fetchExecuteTransferChoiceContext(
1434
- allocationCid,
1435
- registryUrl
1436
- );
1437
- return this.createExecuteTransferAllocationFromContext(
1438
- allocationCid,
1439
- choiceContext
1440
- );
1441
- }
1442
- async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
1443
- return this.core.getTokenStandardClient(registryUrl).post(
1444
- "/registry/allocations/v1/{allocationId}/choice-contexts/withdraw",
1445
- {
1446
- excludeDebugFields: true
1447
- },
1448
- { path: { allocationId: allocationCid } }
1449
- );
1450
- }
1451
- createWithdrawAllocationFromContext(allocationCid, choiceContext) {
1452
- return this.buildAllocationExerciseWithContext(
1453
- coreTokenStandard.ALLOCATION_INTERFACE_ID,
1454
- allocationCid,
1455
- "Allocation_Withdraw",
1456
- choiceContext
1457
- );
1458
- }
1459
- async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1460
- if (prefetchedRegistryChoiceContext) {
1461
- return this.createWithdrawAllocationFromContext(
1462
- allocationCid,
1463
- prefetchedRegistryChoiceContext
1464
- );
1465
- }
1466
- const choiceContext = await this.fetchWithdrawAllocationChoiceContext(
1467
- allocationCid,
1468
- registryUrl
1469
- );
1470
- return this.createWithdrawAllocationFromContext(
1471
- allocationCid,
1472
- choiceContext
1473
- );
1474
- }
1475
- async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
1476
- return this.core.getTokenStandardClient(registryUrl).post(
1477
- "/registry/allocations/v1/{allocationId}/choice-contexts/cancel",
1478
- {
1479
- excludeDebugFields: true
1480
- },
1481
- { path: { allocationId: allocationCid } }
1482
- );
1483
- }
1484
- createCancelAllocationFromContext(allocationCid, choiceContext) {
1485
- return this.buildAllocationExerciseWithContext(
1486
- coreTokenStandard.ALLOCATION_INTERFACE_ID,
1487
- allocationCid,
1488
- "Allocation_Cancel",
1489
- choiceContext
1490
- );
1491
- }
1492
- async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1493
- if (prefetchedRegistryChoiceContext) {
1494
- return this.createCancelAllocationFromContext(
1495
- allocationCid,
1496
- prefetchedRegistryChoiceContext
1497
- );
1498
- }
1499
- const choiceContext = await this.fetchCancelAllocationChoiceContext(
1500
- allocationCid,
1501
- registryUrl
1502
- );
1503
- return this.createCancelAllocationFromContext(
1504
- allocationCid,
1505
- choiceContext
1506
- );
1507
- }
1508
- async createWithdrawAllocationInstruction(allocationInstructionCid) {
1509
- const exercise = {
1510
- templateId: coreTokenStandard.ALLOCATION_INSTRUCTION_INTERFACE_ID,
1511
- contractId: allocationInstructionCid,
1512
- choice: "AllocationInstruction_Withdraw",
1513
- choiceArgument: {
1514
- extraArgs: {
1515
- context: { values: {} },
1516
- meta: { values: {} }
1517
- }
1518
- }
1519
- };
1520
- return [exercise, []];
1521
- }
1522
- async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
1523
- const exercise = {
1524
- templateId: coreTokenStandard.ALLOCATION_INSTRUCTION_INTERFACE_ID,
1525
- contractId: allocationInstructionCid,
1526
- choice: "AllocationInstruction_Update",
1527
- choiceArgument: {
1528
- extraActors,
1529
- extraArgs: {
1530
- context: { values: extraArgsContext },
1531
- meta: { values: extraArgsMeta }
1532
- }
1533
- }
1534
- };
1535
- return [exercise, []];
1536
- }
1537
- async createRejectAllocationRequest(allocationRequestCid, actor) {
1538
- const exercise = {
1539
- templateId: coreTokenStandard.ALLOCATION_REQUEST_INTERFACE_ID,
1540
- contractId: allocationRequestCid,
1541
- choice: "AllocationRequest_Reject",
1542
- choiceArgument: {
1543
- actor,
1544
- extraArgs: {
1545
- context: { values: {} },
1546
- meta: { values: {} }
1547
- }
1548
- }
1549
- };
1550
- return [exercise, []];
1551
- }
1552
- async createWithdrawAllocationRequest(allocationRequestCid) {
1553
- const exercise = {
1554
- templateId: coreTokenStandard.ALLOCATION_REQUEST_INTERFACE_ID,
1555
- contractId: allocationRequestCid,
1556
- choice: "AllocationRequest_Withdraw",
1557
- choiceArgument: {
1558
- extraArgs: {
1559
- context: { values: {} },
1560
- meta: { values: {} }
1561
- }
1562
- }
1563
- };
1564
- return [exercise, []];
1565
- }
1566
- };
1567
- var TransferService = class {
1568
- constructor(core, logger) {
1569
- this.core = core;
1570
- this.logger = logger;
1571
- }
1572
- async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion) {
1573
- const inputHoldingCids = await this.core.getInputHoldingsCids(
1574
- sender,
1575
- inputUtxos,
1576
- parseFloat(amount),
1577
- continueUntilCompletion
1578
- );
1579
- return {
1580
- expectedAdmin: instrumentAdmin,
1581
- transfer: {
1582
- sender,
1583
- receiver,
1584
- amount,
1585
- instrumentId: { admin: instrumentAdmin, id: instrumentId },
1586
- requestedAt: new Date(
1587
- Date.now() - REQUESTED_AT_SKEW_MS
1588
- ).toISOString(),
1589
- executeBefore: (expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1e3)).toISOString(),
1590
- inputHoldingCids,
1591
- meta: {
1592
- values: {
1593
- [TokenStandardService.MEMO_KEY]: memo || "",
1594
- ...meta?.values
1595
- }
1596
- }
1597
- },
1598
- extraArgs: {
1599
- context: { values: {} },
1600
- meta: { values: {} }
1601
- }
1602
- };
1603
- }
1604
- async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
1605
- return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
1606
- choiceArguments: choiceArgs,
1607
- excludeDebugFields
1608
- });
1609
- }
1610
- async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
1611
- this.logger.debug("Creating transfer from pre-fetched context...");
1612
- choiceArgs.extraArgs.context = {
1613
- ...choiceContext.choiceContextData,
1614
- values: choiceContext.choiceContextData?.values ?? {}
1615
- };
1616
- const exercise = {
1617
- templateId: coreTokenStandard.TRANSFER_FACTORY_INTERFACE_ID,
1618
- contractId: factoryId,
1619
- choice: "TransferFactory_Transfer",
1620
- choiceArgument: choiceArgs
1621
- };
1622
- return [exercise, choiceContext.disclosedContracts];
1623
- }
1624
- // TODO: use named parameters
1625
- async createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext, continueUntilCompletion) {
1626
- try {
1627
- const choiceArgs = await this.buildTransferChoiceArgs(
1628
- sender,
1629
- receiver,
1630
- amount,
1631
- instrumentAdmin,
1632
- instrumentId,
1633
- inputUtxos,
1634
- memo,
1635
- expiryDate,
1636
- meta,
1637
- continueUntilCompletion
1638
- );
1639
- if (prefetchedRegistryChoiceContext) {
1640
- return this.createTransferFromContext(
1641
- prefetchedRegistryChoiceContext.factoryId,
1642
- choiceArgs,
1643
- prefetchedRegistryChoiceContext.choiceContext
1644
- );
1645
- }
1646
- const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(
1647
- registryUrl,
1648
- choiceArgs
1649
- );
1650
- return this.createTransferFromContext(
1651
- factoryId,
1652
- choiceArgs,
1653
- choiceContext
1654
- );
1655
- } catch (e) {
1656
- this.logger.error("Failed to execute transfer:", e);
1657
- throw e;
1658
- }
1659
- }
1660
- async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
1661
- const client = this.core.getTokenStandardClient(registryUrl);
1662
- const choiceContext = await client.post(
1663
- "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept",
1664
- {
1665
- excludeDebugFields: true
1666
- },
1667
- {
1668
- path: {
1669
- transferInstructionId: transferInstructionCid
1670
- }
1671
- }
1672
- );
1673
- return {
1674
- choiceContextData: choiceContext.choiceContextData,
1675
- disclosedContracts: choiceContext.disclosedContracts
1676
- };
1677
- }
1678
- async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
1679
- try {
1680
- const exercise = {
1681
- templateId: coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID,
1682
- contractId: transferInstructionCid,
1683
- choice: "TransferInstruction_Accept",
1684
- choiceArgument: {
1685
- extraArgs: {
1686
- context: choiceContext.choiceContextData,
1687
- meta: { values: {} }
1688
- }
1689
- }
1690
- };
1691
- return [exercise, choiceContext.disclosedContracts];
1692
- } catch (e) {
1693
- this.logger.error(
1694
- "Failed to create accept transfer instruction:",
1695
- e
1696
- );
1697
- throw e;
1698
- }
1699
- }
1700
- async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1701
- const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(
1702
- transferInstructionCid,
1703
- registryUrl.href
1704
- );
1705
- const choiceArgs = {
1706
- cid: acceptTransferInstructionContext.contractId,
1707
- proxyArg: {
1708
- featuredAppRightCid,
1709
- beneficiaries,
1710
- choiceArg: acceptTransferInstructionContext.choiceArgument
1711
- }
1712
- };
1713
- return [
1714
- {
1715
- templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1716
- contractId: proxyCid,
1717
- choice: "DelegateProxy_TransferInstruction_Accept",
1718
- choiceArgument: choiceArgs
1719
- },
1720
- disclosedContracts
1721
- ];
1722
- }
1723
- async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1724
- const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(
1725
- transferInstructionCid,
1726
- registryUrl.href
1727
- );
1728
- const choiceArgs = {
1729
- cid: rejectTransferInstructionContext.contractId,
1730
- proxyArg: {
1731
- featuredAppRightCid,
1732
- beneficiaries,
1733
- choiceArg: rejectTransferInstructionContext.choiceArgument
1734
- }
1735
- };
1736
- return [
1737
- {
1738
- templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1739
- contractId: proxyCid,
1740
- choice: "DelegateProxy_TransferInstruction_Reject",
1741
- choiceArgument: choiceArgs
1742
- },
1743
- disclosedContracts
1744
- ];
1745
- }
1746
- async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1747
- const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(
1748
- transferInstructionCid,
1749
- registryUrl.href
1750
- );
1751
- const sumOfWeights = beneficiaries.reduce(
1752
- (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
1753
- 0
1754
- );
1755
- if (sumOfWeights > 1) {
1756
- throw new Error("Sum of beneficiary weights is larger than 1.");
1757
- }
1758
- const choiceArgs = {
1759
- cid: withdrawTransferInstructionContext.contractId,
1760
- proxyArg: {
1761
- featuredAppRightCid,
1762
- beneficiaries,
1763
- choiceArg: withdrawTransferInstructionContext.choiceArgument
1764
- }
1765
- };
1766
- return [
1767
- {
1768
- templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1769
- contractId: proxyCid,
1770
- choice: "DelegateProxy_TransferInstruction_Withdraw",
1771
- choiceArgument: choiceArgs
1772
- },
1773
- disclosedContracts
1774
- ];
1775
- }
1776
- async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
1777
- if (prefetchedRegistryChoiceContext) {
1778
- return this.createAcceptTransferInstructionFromContext(
1779
- transferInstructionCid,
1780
- {
1781
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
1782
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
1783
- }
1784
- );
1785
- }
1786
- const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(
1787
- transferInstructionCid,
1788
- registryUrl
1789
- );
1790
- return this.createAcceptTransferInstructionFromContext(
1791
- transferInstructionCid,
1792
- choiceContext
1793
- );
1794
- }
1795
- async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
1796
- const client = this.core.getTokenStandardClient(registryUrl);
1797
- const choiceContext = await client.post(
1798
- "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject",
1799
- {
1800
- excludeDebugFields: true
1801
- },
1802
- {
1803
- path: {
1804
- transferInstructionId: transferInstructionCid
1805
- }
1806
- }
1807
- );
1808
- return {
1809
- choiceContextData: choiceContext.choiceContextData,
1810
- disclosedContracts: choiceContext.disclosedContracts
1811
- };
1812
- }
1813
- async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
1814
- try {
1815
- const exercise = {
1816
- templateId: coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID,
1817
- contractId: transferInstructionCid,
1818
- choice: "TransferInstruction_Reject",
1819
- choiceArgument: {
1820
- extraArgs: {
1821
- context: choiceContext.choiceContextData,
1822
- meta: { values: {} }
1823
- }
1824
- }
1825
- };
1826
- return [exercise, choiceContext.disclosedContracts];
1827
- } catch (e) {
1828
- this.logger.error(
1829
- "Failed to create reject transfer instruction:",
1830
- e
1831
- );
1832
- throw e;
1833
- }
1834
- }
1835
- async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
1836
- if (prefetchedRegistryChoiceContext) {
1837
- return this.createRejectTransferInstructionFromContext(
1838
- transferInstructionCid,
1839
- {
1840
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
1841
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
1842
- }
1843
- );
1844
- }
1845
- const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(
1846
- transferInstructionCid,
1847
- registryUrl
1848
- );
1849
- return this.createRejectTransferInstructionFromContext(
1850
- transferInstructionCid,
1851
- choiceContext
1852
- );
1853
- }
1854
- async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
1855
- const client = this.core.getTokenStandardClient(registryUrl);
1856
- const choiceContext = await client.post(
1857
- "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw",
1858
- {
1859
- excludeDebugFields: true
1860
- },
1861
- {
1862
- path: {
1863
- transferInstructionId: transferInstructionCid
1864
- }
7
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
+
9
+ var createClient__default = /*#__PURE__*/_interopDefault(createClient);
10
+
11
+ var __defProp = Object.defineProperty;
12
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
14
+ var COMPLETIONS_LIMIT = "100";
15
+ var COMPLETIONS_STREAM_IDLE_TIMEOUT_MS = "1000";
16
+ async function awaitCompletion(ledgerClient, ledgerEnd, partyId, userId, commandIdOrSubmissionId) {
17
+ const responses = await ledgerClient.postWithRetry(
18
+ "/v2/commands/completions",
19
+ {
20
+ userId,
21
+ parties: [partyId],
22
+ beginExclusive: ledgerEnd
23
+ },
24
+ defaultRetryableOptions,
25
+ {
26
+ query: {
27
+ limit: COMPLETIONS_LIMIT,
28
+ stream_idle_timeout_ms: COMPLETIONS_STREAM_IDLE_TIMEOUT_MS
1865
29
  }
1866
- );
1867
- return {
1868
- choiceContextData: choiceContext.choiceContextData,
1869
- disclosedContracts: choiceContext.disclosedContracts
1870
- };
1871
- }
1872
- async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
1873
- try {
1874
- const exercise = {
1875
- templateId: coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID,
1876
- contractId: transferInstructionCid,
1877
- choice: "TransferInstruction_Withdraw",
1878
- choiceArgument: {
1879
- extraArgs: {
1880
- context: choiceContext.choiceContextData,
1881
- meta: { values: {} }
1882
- }
1883
- }
1884
- };
1885
- return [exercise, choiceContext.disclosedContracts];
1886
- } catch (e) {
1887
- this.logger.error(
1888
- "Failed to create withdraw transfer instruction:",
1889
- e
1890
- );
1891
- throw e;
1892
30
  }
1893
- }
1894
- async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
1895
- if (prefetchedRegistryChoiceContext) {
1896
- return this.createWithdrawTransferInstructionFromContext(
1897
- transferInstructionCid,
1898
- {
1899
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
1900
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
1901
- }
1902
- );
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);
1903
39
  }
1904
- const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(
1905
- transferInstructionCid,
1906
- registryUrl
1907
- );
1908
- return this.createWithdrawTransferInstructionFromContext(
1909
- transferInstructionCid,
1910
- choiceContext
1911
- );
1912
- }
1913
- async createTransferInstruction(transferInstructionCid, registryUrl, instructionChoice, prefetchedRegistryChoiceContext) {
1914
- switch (instructionChoice) {
1915
- case "Accept":
1916
- return this.createAcceptTransferInstruction(
1917
- transferInstructionCid,
1918
- registryUrl,
1919
- prefetchedRegistryChoiceContext
1920
- );
1921
- case "Reject":
1922
- return this.createRejectTransferInstruction(
1923
- transferInstructionCid,
1924
- registryUrl,
1925
- prefetchedRegistryChoiceContext
1926
- );
1927
- case "Withdraw":
1928
- return this.createWithdrawTransferInstruction(
1929
- transferInstructionCid,
1930
- registryUrl,
1931
- prefetchedRegistryChoiceContext
1932
- );
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);
1933
47
  }
1934
- }
1935
- };
1936
- var TokenStandardService = class {
1937
- constructor(ledgerClient, logger, accessTokenProvider, isMasterUser) {
1938
- this.ledgerClient = ledgerClient;
1939
- this.logger = logger;
1940
- this.accessTokenProvider = accessTokenProvider;
1941
- this.isMasterUser = isMasterUser;
1942
- __publicField(this, "core");
1943
- __publicField(this, "allocation");
1944
- __publicField(this, "transfer");
1945
- 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(
1946
53
  ledgerClient,
1947
- logger,
1948
- accessTokenProvider,
1949
- isMasterUser,
1950
- void 0,
1951
- void 0
54
+ newLedgerEnd || ledgerEnd,
55
+ // !newLedgerEnd implies response was empty
56
+ partyId,
57
+ userId,
58
+ commandIdOrSubmissionId
1952
59
  );
1953
- this.allocation = new AllocationService(this.core, this.logger);
1954
- this.transfer = new TransferService(this.core, this.logger);
1955
60
  }
1956
- async getInstrumentById(registryUrl, instrumentId) {
1957
- try {
1958
- const params = {
1959
- path: {
1960
- instrumentId
1961
- }
1962
- };
1963
- const client = this.core.getTokenStandardClient(registryUrl);
1964
- return client.get(
1965
- "/registry/metadata/v1/instruments/{instrumentId}",
1966
- params
1967
- );
1968
- } catch (e) {
1969
- this.logger.error(e);
1970
- throw new Error(
1971
- `Instrument id ${instrumentId} does not exist for this instrument admin.`
1972
- );
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);
1973
72
  }
1974
73
  }
1975
- async getInstrumentAdmin(registryUrl) {
1976
- const client = this.core.getTokenStandardClient(registryUrl);
1977
- const info = await client.get("/registry/metadata/v1/info");
1978
- return info.adminId;
1979
- }
1980
- async listInstruments(registryUrl, pageSize, pageToken) {
1981
- const client = this.core.getTokenStandardClient(registryUrl);
1982
- return client.get("/registry/metadata/v1/instruments", {
1983
- query: {
1984
- ...pageSize && { pageSize },
1985
- ...pageToken && { pageToken }
1986
- }
1987
- });
1988
- }
1989
- // <T> is shape of viewValue related to queried interface.
1990
- // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
1991
- async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
1992
- return this.core.listContractsByInterface(
1993
- interfaceId,
1994
- partyId,
1995
- limit,
1996
- offset,
1997
- continueUntilCompletion
1998
- );
1999
- }
2000
- 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++) {
2001
89
  try {
2002
- this.logger.debug("Set or query offset");
2003
- const afterOffsetOrLatest = Number(afterOffset) || (await this.ledgerClient.getWithRetry(
2004
- "/v2/state/latest-pruned-offsets"
2005
- )).participantPrunedUpToInclusive;
2006
- const beforeOffsetOrLatest = Number(beforeOffset) || (await this.ledgerClient.getWithRetry("/v2/state/ledger-end")).offset;
2007
- this.logger.debug(afterOffsetOrLatest, "Using offset");
2008
- const updatesResponse = await this.ledgerClient.postWithRetry("/v2/updates/flats", {
2009
- updateFormat: {
2010
- includeTransactions: {
2011
- eventFormat: coreLedgerClientTypes.EventFilterBySetup({
2012
- interfaceIds: TokenStandardTransactionInterfaces,
2013
- isMasterUser: this.isMasterUser,
2014
- partyId,
2015
- includeWildcard: true
2016
- }),
2017
- transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
2018
- }
2019
- },
2020
- beginExclusive: afterOffsetOrLatest,
2021
- endInclusive: beforeOffsetOrLatest,
2022
- verbose: false
2023
- });
2024
- return this.core.toPrettyTransactions(
2025
- updatesResponse,
2026
- partyId,
2027
- this.ledgerClient
2028
- );
90
+ return await fn();
2029
91
  } catch (err) {
2030
- this.logger.error("Failed to list holding transactions.", err);
2031
- throw err;
2032
- }
2033
- }
2034
- async getTransactionById(updateId, partyId) {
2035
- const transactionFormat = {
2036
- eventFormat: coreLedgerClientTypes.EventFilterBySetup({
2037
- interfaceIds: TokenStandardTransactionInterfaces,
2038
- isMasterUser: this.isMasterUser,
2039
- partyId,
2040
- includeWildcard: true
2041
- }),
2042
- transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
2043
- };
2044
- const getTransactionResponse = await this.ledgerClient.postWithRetry(
2045
- "/v2/updates/transaction-by-id",
2046
- {
2047
- updateId,
2048
- 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;
2049
106
  }
2050
- );
2051
- return this.core.toPrettyTransaction(
2052
- getTransactionResponse,
2053
- partyId,
2054
- this.ledgerClient
2055
- );
2056
- }
2057
- async getInputHoldingsCids(sender, inputUtxos, amount) {
2058
- return this.core.getInputHoldingsCids(sender, inputUtxos, amount);
2059
- }
2060
- async createDelegateProxyTranfser(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, featuredAppRightCid, proxyCid, beneficiaries, inputUtxos, memo, expiryDate, meta) {
2061
- const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(
2062
- sender,
2063
- receiver,
2064
- amount,
2065
- instrumentAdmin,
2066
- instrumentId,
2067
- registryUrl,
2068
- inputUtxos,
2069
- memo,
2070
- expiryDate,
2071
- meta
2072
- );
2073
- const sumOfWeights = beneficiaries.reduce(
2074
- (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
2075
- 0
2076
- );
2077
- if (sumOfWeights > 1) {
2078
- throw new Error("Sum of beneficiary weights is larger than 1.");
2079
107
  }
2080
- const choiceArgs = {
2081
- cid: transferCommand.contractId,
2082
- proxyArg: {
2083
- featuredAppRightCid,
2084
- beneficiaries,
2085
- choiceArg: transferCommand.choiceArgument
2086
- }
2087
- };
2088
- const exercise = {
2089
- templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
2090
- contractId: proxyCid,
2091
- choice: "DelegateProxy_TransferFactory_Transfer",
2092
- choiceArgument: choiceArgs
2093
- };
2094
- return [exercise, disclosedContracts];
2095
- }
2096
- async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
2097
- const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(
2098
- transferInstructionCid,
2099
- registryUrl
2100
- );
2101
- const choiceArgs = {
2102
- cid: acceptTransferInstructionContext.contractId,
2103
- proxyArg: {
2104
- featuredAppRightCid,
2105
- beneficiaries: [
2106
- {
2107
- beneficiary: exchangeParty,
2108
- weight: 1
2109
- }
2110
- ],
2111
- choiceArg: acceptTransferInstructionContext.choiceArgument
2112
- }
2113
- };
2114
- return [
2115
- {
2116
- templateId: "#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy",
2117
- contractId: proxyCid,
2118
- choice: "DelegateProxy_TransferInstruction_Accept",
2119
- choiceArgument: choiceArgs
2120
- },
2121
- disclosedContracts
2122
- ];
2123
108
  }
2124
- static isHoldingLocked(holding, currentTime = /* @__PURE__ */ new Date()) {
2125
- const lock = holding.lock;
2126
- if (!lock) return false;
2127
- const expiresAt = lock.expiresAt;
2128
- if (!expiresAt) return true;
2129
- const expiresAtDate = new Date(expiresAt);
2130
- 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;
2131
117
  }
2132
118
  };
2133
- __publicField(TokenStandardService, "MEMO_KEY", "splice.lfdecentralizedtrust.org/reason");
2134
-
2135
- // src/amulet-service.ts
2136
- var REQUESTED_AT_SKEW_MS2 = 6e4;
2137
- var AmuletService = class {
2138
- constructor(tokenStandard, scanProxyClient, scanClient) {
2139
- this.tokenStandard = tokenStandard;
2140
- this.scanProxyClient = scanProxyClient;
2141
- this.scanClient = scanClient;
2142
- }
2143
- async getTransferPreApprovalByParty(partyId) {
2144
- const { transfer_preapproval } = await this.scanProxyClient.get(
2145
- "/v0/scan-proxy/transfer-preapprovals/by-party/{party}",
2146
- {
2147
- path: {
2148
- party: partyId
2149
- }
2150
- }
2151
- );
2152
- return transfer_preapproval;
2153
- }
2154
- async getFeaturedAppsByParty(partyId) {
2155
- const { featured_app_right } = await this.scanProxyClient.get(
2156
- "/v0/scan-proxy/featured-apps/{provider_party_id}",
2157
- {
2158
- path: {
2159
- provider_party_id: partyId
2160
- }
2161
- }
2162
- );
2163
- return featured_app_right;
2164
- }
2165
- async buyMemberTraffic(dso, provider, trafficAmount, synchronizerId, memberId, migrationId, inputUtxos) {
2166
- const amuletRules = await this.scanProxyClient.getAmuletRules();
2167
- const activeRound = await this.scanProxyClient.getActiveOpenMiningRound();
2168
- const inputHoldings = await this.tokenStandard.getInputHoldingsCids(
2169
- provider,
2170
- inputUtxos,
2171
- trafficAmount
2172
- );
2173
- if (!amuletRules) {
2174
- throw new Error("AmuletRules contract not found");
2175
- }
2176
- if (!activeRound) {
2177
- throw new Error(
2178
- "OpenMiningRound active at current moment not found"
2179
- );
2180
- }
2181
- const disclosed = [
2182
- {
2183
- templateId: amuletRules.template_id,
2184
- contractId: amuletRules.contract_id,
2185
- createdEventBlob: amuletRules.created_event_blob,
2186
- synchronizerId
2187
- },
2188
- {
2189
- templateId: activeRound.template_id,
2190
- contractId: activeRound.contract_id,
2191
- createdEventBlob: activeRound.created_event_blob,
2192
- synchronizerId
2193
- }
2194
- ];
2195
- const context = {
2196
- openMiningRound: activeRound.contract_id,
2197
- issuingMiningRounds: [],
2198
- validatorRights: [],
2199
- featuredAppRight: null
2200
- };
2201
- const choiceArgs = {
2202
- context,
2203
- inputs: inputHoldings.map((cid) => ({
2204
- tag: "InputAmulet",
2205
- value: cid
2206
- })),
2207
- provider,
2208
- memberId: this.tokenStandard.core.toQualifiedMemberId(memberId),
2209
- synchronizerId,
2210
- migrationId,
2211
- trafficAmount,
2212
- expectedDso: dso
2213
- };
2214
- const exercise = {
2215
- templateId: "#splice-amulet:Splice.AmuletRules:AmuletRules",
2216
- contractId: amuletRules.contract_id,
2217
- choice: "AmuletRules_BuyMemberTraffic",
2218
- choiceArgument: choiceArgs
2219
- };
2220
- 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;
2221
128
  }
2222
- async getMemberTrafficStatus(domainId, memberId) {
2223
- if (!this.scanClient) {
2224
- throw new Error("Scan API URL was not provided");
2225
- }
2226
- return this.scanClient.get(
2227
- "/v0/domains/{domain_id}/members/{member_id}/traffic-status",
2228
- {
2229
- path: {
2230
- domain_id: domainId,
2231
- 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 {
2232
139
  }
2233
- }
2234
- );
2235
- }
2236
- async selfGrantFeatureAppRight(providerPartyId, synchronizerId) {
2237
- const amuletRules = await this.scanProxyClient.getAmuletRules();
2238
- const disclosedContracts = {
2239
- templateId: amuletRules.template_id,
2240
- contractId: amuletRules.contract_id,
2241
- createdEventBlob: amuletRules.created_event_blob,
2242
- synchronizerId
2243
- };
2244
- return [
2245
- {
2246
- templateId: amuletRules.template_id,
2247
- contractId: amuletRules.contract_id,
2248
- choice: "AmuletRules_DevNet_FeatureApp",
2249
- choiceArgument: {
2250
- 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 {
2251
146
  }
2252
- },
2253
- [disclosedContracts]
2254
- ];
2255
- }
2256
- async cancelTransferPreapproval(contractId, templateId, actor) {
2257
- const exercise = {
2258
- templateId,
2259
- contractId,
2260
- choice: "TransferPreapproval_Cancel",
2261
- choiceArgument: { p: actor }
2262
- };
2263
- return [exercise, []];
2264
- }
2265
- async renewTransferPreapproval(contractId, templateId, provider, synchronizerId, newExpiresAt, inputUtxos) {
2266
- const amuletRules = await this.scanProxyClient.getAmuletRules();
2267
- const activeRound = await this.scanProxyClient.getActiveOpenMiningRound();
2268
- if (!amuletRules) {
2269
- throw new Error("AmuletRules contract not found");
2270
- }
2271
- if (!activeRound) {
2272
- throw new Error(
2273
- "OpenMiningRound active at current moment not found"
2274
- );
2275
- }
2276
- const disclosed = [
2277
- {
2278
- templateId: amuletRules.template_id,
2279
- contractId: amuletRules.contract_id,
2280
- createdEventBlob: amuletRules.created_event_blob,
2281
- synchronizerId
2282
- },
2283
- {
2284
- templateId: activeRound.template_id,
2285
- contractId: activeRound.contract_id,
2286
- createdEventBlob: activeRound.created_event_blob,
2287
- synchronizerId
2288
- }
2289
- ];
2290
- const inputHoldings = await this.tokenStandard.getInputHoldingsCids(
2291
- provider,
2292
- inputUtxos
2293
- );
2294
- const context = {
2295
- context: {
2296
- openMiningRound: activeRound.contract_id,
2297
- issuingMiningRounds: [],
2298
- validatorRights: [],
2299
- featuredAppRight: null
2300
- },
2301
- amuletRules: amuletRules.contract_id
2302
- };
2303
- const effectiveNewExpiresAt = newExpiresAt ?? new Date(Date.now() + 90 * 24 * 3600 * 1e3);
2304
- const exercise = {
2305
- templateId,
2306
- contractId,
2307
- choice: "TransferPreapproval_Renew",
2308
- choiceArgument: {
2309
- context,
2310
- inputs: inputHoldings.map((cid) => ({
2311
- tag: "InputAmulet",
2312
- value: cid
2313
- })),
2314
- newExpiresAt: effectiveNewExpiresAt.toISOString()
2315
- }
2316
- };
2317
- return [exercise, disclosed];
2318
- }
2319
- async createTap(receiver, amount, instrumentAdmin, instrumentId, registryUrl) {
2320
- const now = /* @__PURE__ */ new Date();
2321
- const tomorrow = new Date(now);
2322
- tomorrow.setDate(tomorrow.getDate() + 1);
2323
- const choiceArgs = {
2324
- expectedAdmin: instrumentAdmin,
2325
- transfer: {
2326
- sender: instrumentAdmin,
2327
- receiver,
2328
- amount,
2329
- instrumentId: { admin: instrumentAdmin, id: instrumentId },
2330
- lock: null,
2331
- requestedAt: new Date(
2332
- Date.now() - REQUESTED_AT_SKEW_MS2
2333
- ).toISOString(),
2334
- executeBefore: tomorrow.toISOString(),
2335
- inputHoldingCids: [],
2336
- meta: { values: {} }
2337
- },
2338
- extraArgs: {
2339
- context: { values: {} },
2340
- meta: { values: {} }
2341
147
  }
2342
- };
2343
- const disclosedContracts = (await this.tokenStandard.transfer.fetchTransferFactoryChoiceContext(
2344
- registryUrl,
2345
- choiceArgs
2346
- )).choiceContext.disclosedContracts;
2347
- const amuletRules = await this.scanProxyClient.getAmuletRules();
2348
- if (!amuletRules) {
2349
- throw new Error("AmuletRules contract not found");
2350
- }
2351
- const latestOpenMiningRound = await this.scanProxyClient.getActiveOpenMiningRound();
2352
- if (!latestOpenMiningRound) {
2353
- throw new Error(
2354
- "OpenMiningRound active at current moment not found"
2355
- );
2356
148
  }
2357
- return [
2358
- {
2359
- templateId: amuletRules.template_id,
2360
- contractId: amuletRules.contract_id,
2361
- choice: "AmuletRules_DevNet_Tap",
2362
- choiceArgument: {
2363
- receiver,
2364
- amount,
2365
- openRound: latestOpenMiningRound.contract_id
2366
- }
2367
- },
2368
- disclosedContracts
2369
- ];
149
+ } else {
150
+ throw e;
2370
151
  }
152
+ return { code, message, errorInfo, retryInfo };
2371
153
  };
2372
154
 
2373
155
  // src/acs/acs-container.ts
@@ -2888,11 +670,9 @@ var LedgerClient = class {
2888
670
  }
2889
671
  async init() {
2890
672
  if (!this.initialized) {
2891
- this.logger.debug(
2892
- "Initializing LedgerClient with version %s for url %s",
2893
- this.clientVersion,
2894
- this.baseUrl.href
2895
- );
673
+ this.logger.debug({
674
+ message: `Initializing LedgerClient with version ${this.clientVersion} for url ${this.baseUrl.href}`
675
+ });
2896
676
  const versionFromClient = await this.currentClient.GET("/v2/version");
2897
677
  this.logger.debug(versionFromClient, "getV2Version response");
2898
678
  this.clientVersion = this.parseSupportedVersions(
@@ -3269,6 +1049,12 @@ var LedgerClient = class {
3269
1049
  ).filter((event) => event.consuming);
3270
1050
  const createdEvents = data.events?.filter((event) => "CreatedEvent" in event).map(
3271
1051
  (event) => event.CreatedEvent
1052
+ ).filter(
1053
+ (event) => Object.keys(
1054
+ activeContractsArgs.filter?.filtersByParty ?? {}
1055
+ ).includes(
1056
+ event.createArgument?.owner ?? ""
1057
+ )
3272
1058
  );
3273
1059
  exercisedEvents?.forEach((event) => {
3274
1060
  exercisedContracts.add(event.contractId);
@@ -3456,12 +1242,7 @@ var WSSupportWithBackOffSwitch = class {
3456
1242
 
3457
1243
  exports.ACSContainer = ACSContainer;
3458
1244
  exports.ACS_UPDATE_CONFIG = ACS_UPDATE_CONFIG;
3459
- exports.AmuletService = AmuletService;
3460
- exports.CoreService = CoreService;
3461
1245
  exports.LedgerClient = LedgerClient;
3462
- exports.TokenStandardService = TokenStandardService;
3463
- exports.TokenStandardTransactionInterfaces = TokenStandardTransactionInterfaces;
3464
- exports.TransactionParser = TransactionParser;
3465
1246
  exports.WSSupportWithBackOffSwitch = WSSupportWithBackOffSwitch;
3466
1247
  exports.asJsCantonError = asJsCantonError;
3467
1248
  exports.awaitCompletion = awaitCompletion;
@@ -3469,11 +1250,5 @@ exports.defaultRetryableOptions = defaultRetryableOptions;
3469
1250
  exports.isJsCantonError = isJsCantonError;
3470
1251
  exports.promiseWithTimeout = promiseWithTimeout;
3471
1252
  exports.supportedVersions = supportedVersions;
3472
- Object.keys(coreLedgerClientTypes).forEach(function (k) {
3473
- if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
3474
- enumerable: true,
3475
- get: function () { return coreLedgerClientTypes[k]; }
3476
- });
3477
- });
3478
1253
  //# sourceMappingURL=index.cjs.map
3479
1254
  //# sourceMappingURL=index.cjs.map