@canton-network/core-ledger-client 0.15.0 → 0.17.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.
Files changed (44) hide show
  1. package/dist/acs/acs-container.d.ts +36 -0
  2. package/dist/acs/acs-container.d.ts.map +1 -0
  3. package/dist/acs/acs-helper.d.ts +39 -0
  4. package/dist/acs/acs-helper.d.ts.map +1 -0
  5. package/dist/acs/types.d.ts +10 -0
  6. package/dist/acs/types.d.ts.map +1 -0
  7. package/dist/acs/ws-support.d.ts +18 -0
  8. package/dist/acs/ws-support.d.ts.map +1 -0
  9. package/dist/index.cjs +3306 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.ts +3 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +3286 -7
  14. package/dist/index.js.map +1 -0
  15. package/dist/ledger-api-utils.d.ts +3 -1
  16. package/dist/ledger-api-utils.d.ts.map +1 -1
  17. package/dist/ledger-client.d.ts +32 -4
  18. package/dist/ledger-client.d.ts.map +1 -1
  19. package/dist/token-standard-service.d.ts +11 -9
  20. package/dist/token-standard-service.d.ts.map +1 -1
  21. package/dist/topology-write-service.d.ts +4 -2
  22. package/dist/topology-write-service.d.ts.map +1 -1
  23. package/dist/txparse/parser.d.ts.map +1 -1
  24. package/dist/txparse/test-data/mock/eventsByContractIdResponses.d.ts +153 -0
  25. package/dist/txparse/test-data/mock/eventsByContractIdResponses.d.ts.map +1 -1
  26. package/dist/txparse/types.d.ts +5 -2
  27. package/dist/txparse/types.d.ts.map +1 -1
  28. package/package.json +23 -11
  29. package/dist/constants.js +0 -47
  30. package/dist/generated-clients/openapi-3.3.0-SNAPSHOT.js +0 -5
  31. package/dist/generated-clients/openapi-3.4.0-SNAPSHOT.js +0 -5
  32. package/dist/ledger-api-utils.js +0 -432
  33. package/dist/ledger-client.js +0 -321
  34. package/dist/token-standard-service.js +0 -871
  35. package/dist/topology-write-service.js +0 -283
  36. package/dist/txparse/parser.js +0 -581
  37. package/dist/txparse/parser.test.d.ts +0 -2
  38. package/dist/txparse/parser.test.d.ts.map +0 -1
  39. package/dist/txparse/parser.test.js +0 -97
  40. package/dist/txparse/strict.js +0 -19
  41. package/dist/txparse/test-data/expected/txs.js +0 -2303
  42. package/dist/txparse/test-data/mock/eventsByContractIdResponses.js +0 -2973
  43. package/dist/txparse/test-data/mock/txs.js +0 -6788
  44. package/dist/txparse/types.js +0 -58
package/dist/index.cjs ADDED
@@ -0,0 +1,3306 @@
1
+ 'use strict';
2
+
3
+ var crypto = require('crypto');
4
+ var coreLedgerProto = require('@canton-network/core-ledger-proto');
5
+ var grpcTransport = require('@protobuf-ts/grpc-transport');
6
+ var grpcJs = require('@grpc/grpc-js');
7
+ var fs = require('fs');
8
+ var coreTokenStandard = require('@canton-network/core-token-standard');
9
+ var BigNumber = require('bignumber.js');
10
+ var createClient = require('openapi-fetch');
11
+ var typescriptLruCache = require('typescript-lru-cache');
12
+
13
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
+
15
+ var fs__default = /*#__PURE__*/_interopDefault(fs);
16
+ var BigNumber__default = /*#__PURE__*/_interopDefault(BigNumber);
17
+ var createClient__default = /*#__PURE__*/_interopDefault(createClient);
18
+
19
+ var __defProp = Object.defineProperty;
20
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
21
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
+ function prefixedInt(value, bytes) {
23
+ const buffer = Buffer.alloc(4 + bytes.length);
24
+ buffer.writeUInt32BE(value, 0);
25
+ Buffer.from(bytes).copy(buffer, 4);
26
+ return buffer;
27
+ }
28
+ function signingPublicKeyFromEd25519(publicKey) {
29
+ return {
30
+ format: coreLedgerProto.CryptoKeyFormat.RAW,
31
+ publicKey: Buffer.from(publicKey, "base64"),
32
+ scheme: coreLedgerProto.SigningKeyScheme.ED25519,
33
+ keySpec: coreLedgerProto.SigningKeySpec.EC_CURVE25519,
34
+ usage: []
35
+ };
36
+ }
37
+ function computeSha256CantonHash(purpose, bytes) {
38
+ const hashInput = prefixedInt(purpose, bytes);
39
+ const hash = crypto.createHash("sha256").update(hashInput).digest();
40
+ const multiprefix = Buffer.from([18, 32]);
41
+ return Buffer.concat([multiprefix, hash]).toString("hex");
42
+ }
43
+ function createGrpcTransport(options) {
44
+ const { useTls = false, tls } = options;
45
+ if (useTls) {
46
+ const readMaybeFile = (value) => typeof value === "string" ? fs__default.default.readFileSync(value) : value;
47
+ const rootCert = readMaybeFile(tls?.rootCert);
48
+ const clientCert = readMaybeFile(tls?.clientCert);
49
+ const clientKey = readMaybeFile(tls?.clientKey);
50
+ if (tls?.mutual) {
51
+ if (!clientCert || !clientKey) {
52
+ throw new Error(
53
+ "mTLS enabled but clientCert or clientKey are missing"
54
+ );
55
+ }
56
+ return grpcJs.ChannelCredentials.createSsl(rootCert, clientKey, clientCert);
57
+ } else {
58
+ return grpcJs.ChannelCredentials.createSsl(rootCert);
59
+ }
60
+ } else {
61
+ return grpcJs.ChannelCredentials.createInsecure();
62
+ }
63
+ }
64
+ var TopologyWriteService = class _TopologyWriteService {
65
+ constructor(synchronizerId, userAdminUrl, ledgerClient, accessToken = "", accessTokenProvider, grpcClientOptions) {
66
+ this.synchronizerId = synchronizerId;
67
+ __publicField(this, "topologyClient");
68
+ __publicField(this, "topologyReadService");
69
+ __publicField(this, "ledgerClient");
70
+ __publicField(this, "accessTokenProvider");
71
+ __publicField(this, "accessToken");
72
+ __publicField(this, "storeId", () => coreLedgerProto.StoreId.create({
73
+ store: {
74
+ oneofKind: "synchronizer",
75
+ synchronizer: coreLedgerProto.StoreId_Synchronizer.create({
76
+ id: this.synchronizerId
77
+ })
78
+ }
79
+ }));
80
+ let transport;
81
+ if (grpcClientOptions) {
82
+ transport = new grpcTransport.GrpcTransport({
83
+ host: userAdminUrl,
84
+ channelCredentials: createGrpcTransport(grpcClientOptions)
85
+ });
86
+ } else {
87
+ transport = new grpcTransport.GrpcTransport({
88
+ host: userAdminUrl,
89
+ channelCredentials: grpcJs.ChannelCredentials.createInsecure()
90
+ });
91
+ }
92
+ this.topologyClient = new coreLedgerProto.TopologyManagerWriteServiceClient(transport);
93
+ this.topologyReadService = new coreLedgerProto.TopologyManagerReadServiceClient(
94
+ transport
95
+ );
96
+ this.ledgerClient = ledgerClient;
97
+ this.accessTokenProvider = accessTokenProvider;
98
+ this.accessToken = accessToken;
99
+ }
100
+ static combineHashes(hashes) {
101
+ const sortedHashes = hashes.sort(
102
+ (a, b) => a.toString("hex").localeCompare(b.toString("hex"))
103
+ );
104
+ const combinedHashes = Buffer.alloc(4);
105
+ combinedHashes.writeUInt32BE(sortedHashes.length, 0);
106
+ let concatenatedHashes = combinedHashes;
107
+ for (const h of sortedHashes) {
108
+ const lengthBuffer = Buffer.alloc(4);
109
+ lengthBuffer.writeUInt32BE(h.length, 0);
110
+ concatenatedHashes = Buffer.concat([
111
+ concatenatedHashes,
112
+ lengthBuffer,
113
+ h
114
+ ]);
115
+ }
116
+ const predefineHashPurpose = computeSha256CantonHash(
117
+ 55,
118
+ concatenatedHashes
119
+ );
120
+ return Buffer.from(predefineHashPurpose, "hex").toString("base64");
121
+ }
122
+ static createFingerprintFromKey(publicKey) {
123
+ let key;
124
+ if (typeof publicKey === "string") {
125
+ key = signingPublicKeyFromEd25519(publicKey);
126
+ } else {
127
+ key = publicKey;
128
+ }
129
+ const hashPurpose = 12;
130
+ return computeSha256CantonHash(hashPurpose, key.publicKey);
131
+ }
132
+ /** @deprecated only for grpc/protobuf implementation */
133
+ static toSignedTopologyTransaction(txHashes, serializedTransaction, signature, namespace) {
134
+ return coreLedgerProto.SignedTopologyTransaction.create({
135
+ transaction: serializedTransaction,
136
+ proposal: true,
137
+ signatures: [],
138
+ multiTransactionSignatures: [
139
+ coreLedgerProto.MultiTransactionSignatures.create({
140
+ transactionHashes: txHashes,
141
+ signatures: [
142
+ coreLedgerProto.Signature.create({
143
+ format: coreLedgerProto.SignatureFormat.RAW,
144
+ signature: Buffer.from(signature, "base64"),
145
+ signedBy: namespace,
146
+ signingAlgorithmSpec: coreLedgerProto.SigningAlgorithmSpec.ED25519
147
+ })
148
+ ]
149
+ })
150
+ ]
151
+ });
152
+ }
153
+ /** @deprecated */
154
+ generateTransactionsRequest(namespace, partyId, publicKey, confirmingThreshold = 1, hostingParticipantRights) {
155
+ const namespaceDelegation = coreLedgerProto.TopologyMapping.create({
156
+ mapping: {
157
+ oneofKind: "namespaceDelegation",
158
+ namespaceDelegation: coreLedgerProto.NamespaceDelegation.create({
159
+ namespace,
160
+ targetKey: publicKey,
161
+ isRootDelegation: true,
162
+ restriction: {
163
+ oneofKind: void 0
164
+ }
165
+ })
166
+ }
167
+ });
168
+ const hostingParticipants = [...hostingParticipantRights].map(
169
+ ([participantUid, permission]) => coreLedgerProto.PartyToParticipant_HostingParticipant.create({
170
+ participantUid,
171
+ permission
172
+ })
173
+ );
174
+ const partyToParticipant = coreLedgerProto.TopologyMapping.create({
175
+ mapping: {
176
+ oneofKind: "partyToParticipant",
177
+ partyToParticipant: coreLedgerProto.PartyToParticipant.create({
178
+ party: partyId,
179
+ threshold: confirmingThreshold,
180
+ participants: hostingParticipants
181
+ })
182
+ }
183
+ });
184
+ const partyToKeyMapping = coreLedgerProto.TopologyMapping.create({
185
+ mapping: {
186
+ oneofKind: "partyToKeyMapping",
187
+ partyToKeyMapping: coreLedgerProto.PartyToKeyMapping.create({
188
+ party: partyId,
189
+ threshold: 1,
190
+ signingKeys: [publicKey]
191
+ })
192
+ }
193
+ });
194
+ return coreLedgerProto.GenerateTransactionsRequest.create({
195
+ proposals: [
196
+ namespaceDelegation,
197
+ partyToParticipant,
198
+ partyToKeyMapping
199
+ ].map(
200
+ (mapping) => coreLedgerProto.GenerateTransactionsRequest_Proposal.create({
201
+ mapping,
202
+ serial: 1,
203
+ store: this.storeId(),
204
+ operation: coreLedgerProto.Enums_TopologyChangeOp.ADD_REPLACE
205
+ })
206
+ )
207
+ });
208
+ }
209
+ /** @deprecated use allocateExternalParty() instead */
210
+ async submitExternalPartyTopology(signedTopologyTxs, partyId) {
211
+ await this.addTransactions(signedTopologyTxs);
212
+ await this.authorizePartyToParticipant(partyId);
213
+ }
214
+ /** @deprecated use generateTopology() */
215
+ async generateTransactions(publicKey, partyId, confirmingThreshold = 1, hostingParticipantRights) {
216
+ const signingPublicKey = signingPublicKeyFromEd25519(publicKey);
217
+ const namespace = _TopologyWriteService.createFingerprintFromKey(signingPublicKey);
218
+ let participantRights = hostingParticipantRights;
219
+ if (!participantRights || participantRights.size === 0) {
220
+ const { participantId } = await this.ledgerClient.getWithRetry(
221
+ "/v2/parties/participant-id"
222
+ );
223
+ participantRights = /* @__PURE__ */ new Map([
224
+ [participantId, coreLedgerProto.Enums_ParticipantPermission.CONFIRMATION]
225
+ ]);
226
+ }
227
+ const req = this.generateTransactionsRequest(
228
+ namespace,
229
+ partyId,
230
+ signingPublicKey,
231
+ confirmingThreshold,
232
+ participantRights
233
+ );
234
+ const adminAccessToken = this.accessTokenProvider ? await this.accessTokenProvider.getAdminAccessToken() : this.accessToken;
235
+ return this.topologyClient.generateTransactions(req, {
236
+ meta: {
237
+ Authorization: `Bearer ${adminAccessToken}`
238
+ }
239
+ }).response;
240
+ }
241
+ /** @deprecated */
242
+ async addTransactions(signedTopologyTxs) {
243
+ const request = coreLedgerProto.AddTransactionsRequest.create({
244
+ transactions: signedTopologyTxs,
245
+ forceChanges: [],
246
+ store: this.storeId()
247
+ });
248
+ const adminAccessToken = this.accessTokenProvider ? await this.accessTokenProvider.getAdminAccessToken() : this.accessToken;
249
+ return this.topologyClient.addTransactions(request, {
250
+ meta: {
251
+ Authorization: `Bearer ${adminAccessToken}`
252
+ }
253
+ }).response;
254
+ }
255
+ /** @deprecated */
256
+ async waitForPartyToParticipantProposal(partyId) {
257
+ let counter = 0;
258
+ return new Promise((resolve, reject) => {
259
+ const interval = setInterval(async () => {
260
+ const result = await this.topologyReadService.listPartyToParticipant(
261
+ coreLedgerProto.ListPartyToParticipantRequest.create({
262
+ baseQuery: coreLedgerProto.BaseQuery.create({
263
+ store: this.storeId(),
264
+ proposals: true,
265
+ timeQuery: {
266
+ oneofKind: "headState",
267
+ headState: coreLedgerProto.Empty.create()
268
+ }
269
+ }),
270
+ filterParty: partyId
271
+ })
272
+ );
273
+ if (result.response.results.length > 0) {
274
+ clearInterval(interval);
275
+ resolve(result.response.results[0].context?.transactionHash);
276
+ }
277
+ counter += 1;
278
+ if (counter > 10) {
279
+ clearInterval(interval);
280
+ reject("Timeout waiting for party to participant proposal");
281
+ }
282
+ }, 1e3);
283
+ });
284
+ }
285
+ /** @deprecated */
286
+ async authorizePartyToParticipant(partyId) {
287
+ const hash = await this.waitForPartyToParticipantProposal(partyId);
288
+ if (!hash) {
289
+ throw new Error("No topology transaction found for authorization");
290
+ }
291
+ const request = coreLedgerProto.AuthorizeRequest.create({
292
+ type: {
293
+ oneofKind: "transactionHash",
294
+ transactionHash: Buffer.from(hash).toString("hex")
295
+ },
296
+ mustFullyAuthorize: false,
297
+ store: this.storeId()
298
+ });
299
+ const adminAccessToken = this.accessTokenProvider ? await this.accessTokenProvider.getAdminAccessToken() : this.accessToken;
300
+ return this.topologyClient.authorize(request, {
301
+ meta: {
302
+ Authorization: `Bearer ${adminAccessToken}`
303
+ }
304
+ }).response;
305
+ }
306
+ };
307
+ function splitInterfaceId(interfaceId) {
308
+ const regExp = /^#?([^:]+):([^:]+):([^:]+)$/;
309
+ const match = regExp.exec(interfaceId);
310
+ if (!match) return null;
311
+ const [, packageName, moduleName, entityName] = match;
312
+ return {
313
+ packageName,
314
+ moduleName,
315
+ entityName
316
+ };
317
+ }
318
+ function matchInterfaceIds(a, b) {
319
+ const aParts = splitInterfaceId(a);
320
+ const bParts = splitInterfaceId(b);
321
+ return aParts !== null && bParts !== null && aParts.moduleName === bParts.moduleName && aParts.entityName === bParts.entityName;
322
+ }
323
+ var TokenStandardTransactionInterfaces = [
324
+ coreTokenStandard.HOLDING_INTERFACE_ID,
325
+ coreTokenStandard.TRANSFER_FACTORY_INTERFACE_ID,
326
+ coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID,
327
+ coreTokenStandard.ALLOCATION_FACTORY_INTERFACE_ID,
328
+ coreTokenStandard.ALLOCATION_INSTRUCTION_INTERFACE_ID,
329
+ coreTokenStandard.ALLOCATION_INTERFACE_ID,
330
+ coreTokenStandard.ALLOCATION_REQUEST_INTERFACE_ID
331
+ ];
332
+ var SpliceMetaKeyPrefix = "splice.lfdecentralizedtrust.org/";
333
+ var TxKindMetaKey = `${SpliceMetaKeyPrefix}tx-kind`;
334
+ var SenderMetaKey = `${SpliceMetaKeyPrefix}sender`;
335
+ var ReasonMetaKey = `${SpliceMetaKeyPrefix}reason`;
336
+ var BurnedMetaKey = `${SpliceMetaKeyPrefix}burned`;
337
+ var AllKnownMetaKeys = [
338
+ TxKindMetaKey,
339
+ SenderMetaKey,
340
+ ReasonMetaKey,
341
+ BurnedMetaKey
342
+ ];
343
+ function TransactionFilterBySetup(interfaceNames, options = { includeWildcard: false, isMasterUser: false }) {
344
+ const interfaceArrayed = Array.isArray(interfaceNames) ? interfaceNames : [interfaceNames];
345
+ if (options.isMasterUser)
346
+ return {
347
+ filtersByParty: {},
348
+ filtersForAnyParty: filtersForAnyParty(
349
+ interfaceArrayed,
350
+ options.includeWildcard ?? false
351
+ ) ?? {}
352
+ };
353
+ else if (!options.partyId || options.partyId === void 0)
354
+ throw new Error("Party must be provided for non-master users");
355
+ else
356
+ return {
357
+ filtersByParty: filtersByParty(
358
+ options.partyId,
359
+ interfaceArrayed,
360
+ options.includeWildcard ?? false
361
+ ) ?? {}
362
+ };
363
+ }
364
+ function EventFilterBySetup(interfaceNames, options = { includeWildcard: false, isMasterUser: false }) {
365
+ const interfaceArrayed = Array.isArray(interfaceNames) ? interfaceNames : [interfaceNames];
366
+ if (options.isMasterUser)
367
+ return {
368
+ filtersByParty: {},
369
+ filtersForAnyParty: filtersForAnyParty(
370
+ interfaceArrayed,
371
+ options.includeWildcard ?? false
372
+ ) ?? {},
373
+ verbose: options.verbose ?? false
374
+ };
375
+ else if (!options.partyId || options.partyId === void 0)
376
+ throw new Error("Party must be provided for non-master users");
377
+ else
378
+ return {
379
+ filtersByParty: filtersByParty(
380
+ options.partyId,
381
+ interfaceArrayed,
382
+ options.includeWildcard ?? false
383
+ ) ?? {},
384
+ verbose: options.verbose ?? false
385
+ };
386
+ }
387
+ function filtersByParty(party, interfaceNames, includeWildcard) {
388
+ const wildcardFilter = includeWildcard ? [
389
+ {
390
+ identifierFilter: {
391
+ WildcardFilter: {
392
+ value: {
393
+ includeCreatedEventBlob: true
394
+ }
395
+ }
396
+ }
397
+ }
398
+ ] : [];
399
+ return {
400
+ [party]: {
401
+ cumulative: [
402
+ ...interfaceNames.map((interfaceName) => {
403
+ return {
404
+ identifierFilter: {
405
+ InterfaceFilter: {
406
+ value: {
407
+ interfaceId: interfaceName,
408
+ includeInterfaceView: true,
409
+ includeCreatedEventBlob: true
410
+ }
411
+ }
412
+ }
413
+ };
414
+ }),
415
+ ...wildcardFilter
416
+ ]
417
+ }
418
+ };
419
+ }
420
+ function filtersForAnyParty(interfaceNames, includeWildcard) {
421
+ const wildcardFilter = includeWildcard ? [
422
+ {
423
+ identifierFilter: {
424
+ WildcardFilter: {
425
+ value: {
426
+ includeCreatedEventBlob: true
427
+ }
428
+ }
429
+ }
430
+ }
431
+ ] : [];
432
+ return {
433
+ cumulative: [
434
+ ...interfaceNames.map((interfaceName) => {
435
+ return {
436
+ identifierFilter: {
437
+ InterfaceFilter: {
438
+ value: {
439
+ interfaceId: interfaceName,
440
+ includeInterfaceView: true,
441
+ includeCreatedEventBlob: true
442
+ }
443
+ }
444
+ }
445
+ };
446
+ }),
447
+ ...wildcardFilter
448
+ ]
449
+ };
450
+ }
451
+ function hasInterface(interfaceId, event) {
452
+ return (event.implementedInterfaces || []).some(
453
+ (id) => matchInterfaceIds(id, interfaceId)
454
+ );
455
+ }
456
+ function getInterfaceView(createdEvent) {
457
+ const interfaceViews = createdEvent.interfaceViews || null;
458
+ return interfaceViews && interfaceViews[0] || null;
459
+ }
460
+ function getKnownInterfaceView(createdEvent) {
461
+ const interfaceView = getInterfaceView(createdEvent);
462
+ if (!interfaceView) {
463
+ return null;
464
+ } else if (matchInterfaceIds(coreTokenStandard.HOLDING_INTERFACE_ID, interfaceView.interfaceId)) {
465
+ return {
466
+ type: "Holding",
467
+ viewValue: interfaceView.viewValue
468
+ };
469
+ } else if (matchInterfaceIds(
470
+ coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID,
471
+ interfaceView.interfaceId
472
+ )) {
473
+ return {
474
+ type: "TransferInstruction",
475
+ viewValue: interfaceView.viewValue
476
+ };
477
+ } else {
478
+ return null;
479
+ }
480
+ }
481
+ function ensureInterfaceViewIsPresent(createdEvent, interfaceId) {
482
+ const interfaceView = getInterfaceView(createdEvent);
483
+ if (!interfaceView) {
484
+ throw new Error(
485
+ `Expected to have interface views, but didn't: ${JSON.stringify(
486
+ createdEvent
487
+ )}`
488
+ );
489
+ }
490
+ if (!matchInterfaceIds(interfaceId, interfaceView.interfaceId)) {
491
+ throw new Error(
492
+ `Not a ${interfaceId} but a ${interfaceView.interfaceId}: ${JSON.stringify(createdEvent)}`
493
+ );
494
+ }
495
+ return interfaceView;
496
+ }
497
+ function mergeMetas(event, extra) {
498
+ const choiceArgument = event.choiceArgument;
499
+ const lastWriteWins = [
500
+ choiceArgument?.transfer?.meta,
501
+ choiceArgument?.extraArgs?.meta,
502
+ choiceArgument?.meta,
503
+ extra,
504
+ event.exerciseResult?.meta
505
+ ];
506
+ const result = {};
507
+ lastWriteWins.forEach((meta) => {
508
+ const values = meta?.values || {};
509
+ Object.entries(values).forEach(([k, v]) => {
510
+ result[k] = v;
511
+ });
512
+ });
513
+ if (Object.keys(result).length === 0) {
514
+ return void 0;
515
+ } else {
516
+ return { values: result };
517
+ }
518
+ }
519
+ function getMetaKeyValue(key, meta) {
520
+ return (meta?.values || {})[key] || null;
521
+ }
522
+ function removeParsedMetaKeys(meta) {
523
+ return {
524
+ values: Object.fromEntries(
525
+ Object.entries(meta?.values || {}).filter(
526
+ ([k]) => !AllKnownMetaKeys.includes(k)
527
+ )
528
+ )
529
+ };
530
+ }
531
+ var COMPLETIONS_LIMIT = "100";
532
+ var COMPLETIONS_STREAM_IDLE_TIMEOUT_MS = "1000";
533
+ async function awaitCompletion(ledgerClient, ledgerEnd, partyId, userId, commandIdOrSubmissionId) {
534
+ const responses = await ledgerClient.postWithRetry(
535
+ "/v2/commands/completions",
536
+ {
537
+ userId,
538
+ parties: [partyId],
539
+ beginExclusive: ledgerEnd
540
+ },
541
+ defaultRetryableOptions,
542
+ {
543
+ query: {
544
+ limit: COMPLETIONS_LIMIT,
545
+ stream_idle_timeout_ms: COMPLETIONS_STREAM_IDLE_TIMEOUT_MS
546
+ }
547
+ }
548
+ );
549
+ const completions = responses.filter(
550
+ (response) => !!response.completionResponse.Completion
551
+ );
552
+ const wantedCompletion = completions.find((response) => {
553
+ const completion = response.completionResponse.Completion;
554
+ if (!completion) return false;
555
+ if (completion.value.userId !== userId) return false;
556
+ if (completion.value.commandId === commandIdOrSubmissionId) return true;
557
+ if (completion.value.submissionId === commandIdOrSubmissionId)
558
+ return true;
559
+ return false;
560
+ });
561
+ if (wantedCompletion) {
562
+ const completion = wantedCompletion.completionResponse.Completion;
563
+ const status = completion.value.status;
564
+ if (status && status.code !== 0) {
565
+ throw asGrpcError(status);
566
+ }
567
+ return completion.value;
568
+ } else {
569
+ const lastCompletion = completions[completions.length - 1];
570
+ const newLedgerEnd = lastCompletion?.completionResponse.Completion.value.offset;
571
+ return awaitCompletion(
572
+ ledgerClient,
573
+ newLedgerEnd || ledgerEnd,
574
+ // !newLedgerEnd implies response was empty
575
+ partyId,
576
+ userId,
577
+ commandIdOrSubmissionId
578
+ );
579
+ }
580
+ }
581
+ async function promiseWithTimeout(promise, timeoutMs, errorMessage) {
582
+ let timeoutPid = null;
583
+ const timeoutPromise = new Promise((_resolve, reject) => {
584
+ timeoutPid = setTimeout(() => reject(errorMessage), timeoutMs);
585
+ });
586
+ try {
587
+ return await Promise.race([promise, timeoutPromise]);
588
+ } finally {
589
+ if (timeoutPid) {
590
+ clearTimeout(timeoutPid);
591
+ }
592
+ }
593
+ }
594
+ var defaultRetryableOptions = {
595
+ retries: 5,
596
+ delayMs: 3e3,
597
+ cantonErrorKeys: [
598
+ "SEQUENCER_REQUEST_FAILED",
599
+ "SEQUENCER_BACKPRESSURE",
600
+ "SUBMISSION_ALREADY_IN_FLIGHT",
601
+ "LOCAL_VERDICT_TIMEOUT",
602
+ "NOT_SEQUENCED_TIMEOUT",
603
+ "NO_VIEW_WITH_VALID_RECIPIENTS"
604
+ ]
605
+ };
606
+ async function retryable(fn, retryableOptions2, logger) {
607
+ for (let attempts = 1; attempts <= retryableOptions2.retries; attempts++) {
608
+ try {
609
+ return await fn();
610
+ } catch (err) {
611
+ const grpcError = asGrpcError(err);
612
+ const message = grpcError.message;
613
+ const shouldRetry = retryableOptions2.cantonErrorKeys.length === 0 || retryableOptions2.cantonErrorKeys.some(
614
+ (key) => message.includes(key)
615
+ );
616
+ if (attempts < retryableOptions2.retries && shouldRetry) {
617
+ logger?.warn(
618
+ `Caught retryiable error: ${message}. Retrying attempt ${attempts} of ${retryableOptions2.retries}...`
619
+ );
620
+ await new Promise(
621
+ (res) => setTimeout(res, retryableOptions2.delayMs)
622
+ );
623
+ } else {
624
+ throw grpcError;
625
+ }
626
+ }
627
+ }
628
+ throw new Error("retryable: Exceeded maximum retries without throwing.");
629
+ }
630
+ var isJsCantonError = (e) => typeof e === "object" && e !== null && "status" in e && "errorCategory" in e;
631
+ var asJsCantonError = (e) => {
632
+ if (isJsCantonError(e)) {
633
+ return e;
634
+ } else {
635
+ throw e;
636
+ }
637
+ };
638
+ var asGrpcError = (e) => {
639
+ let errorInfo = void 0;
640
+ let retryInfo = void 0;
641
+ let code = 500;
642
+ let message = e?.message || "";
643
+ if (typeof e === "object" && e !== null && "cause" in e) {
644
+ message = e.cause;
645
+ } else if (typeof e === "object" && e !== null && "message" in e) {
646
+ message = e.message;
647
+ }
648
+ if (typeof e === "object" && e !== null && "code" in e && "message" in e && "details" in e && Array.isArray(e.details)) {
649
+ code = e.code;
650
+ message = e.message;
651
+ for (const detail of e.details) {
652
+ if (detail.typeUrl === "type.googleapis.com/google.rpc.ErrorInfo" && typeof detail.value === "string") {
653
+ try {
654
+ errorInfo = coreLedgerProto.ErrorInfo.fromBinary(
655
+ Buffer.from(detail.value, "base64")
656
+ );
657
+ } catch {
658
+ }
659
+ } else if (detail.typeUrl === "type.googleapis.com/google.rpc.RetryInfo" && typeof detail.value === "string") {
660
+ try {
661
+ retryInfo = coreLedgerProto.RetryInfo.fromBinary(
662
+ Buffer.from(detail.value, "base64")
663
+ );
664
+ } catch {
665
+ }
666
+ }
667
+ }
668
+ } else {
669
+ throw e;
670
+ }
671
+ return { code, message, errorInfo, retryInfo };
672
+ };
673
+
674
+ // src/txparse/types.ts
675
+ var EmptyHoldingsChangeSummary = {
676
+ numInputs: 0,
677
+ inputAmount: "0",
678
+ numOutputs: 0,
679
+ outputAmount: "0",
680
+ amountChange: "0"
681
+ };
682
+ var renderTransaction = (t) => {
683
+ return { ...t, events: t.events.map(renderTransactionEvent) };
684
+ };
685
+ var renderTransactionEvent = (e) => {
686
+ const lockedHoldingsChangeSummary = renderHoldingsChangeSummary(
687
+ e.lockedHoldingsChangeSummary
688
+ );
689
+ const unlockedHoldingsChangeSummary = renderHoldingsChangeSummary(
690
+ e.unlockedHoldingsChangeSummary
691
+ );
692
+ const lockedHoldingsChange = renderHoldingsChange(e.lockedHoldingsChange);
693
+ const unlockedHoldingsChange = renderHoldingsChange(
694
+ e.unlockedHoldingsChange
695
+ );
696
+ return {
697
+ ...e,
698
+ lockedHoldingsChange: lockedHoldingsChange ? { ...lockedHoldingsChange } : void 0,
699
+ unlockedHoldingsChange: unlockedHoldingsChange ? { ...unlockedHoldingsChange } : void 0,
700
+ lockedHoldingsChangeSummary: lockedHoldingsChangeSummary ? { ...lockedHoldingsChangeSummary } : void 0,
701
+ unlockedHoldingsChangeSummary: unlockedHoldingsChangeSummary ? { ...unlockedHoldingsChangeSummary } : void 0
702
+ };
703
+ };
704
+ var renderHoldingsChangeSummary = (s) => {
705
+ if (s.numInputs === 0 && s.numOutputs === 0 && s.inputAmount === "0" && s.outputAmount === "0" && s.amountChange === "0") {
706
+ return void 0;
707
+ }
708
+ return {
709
+ ...s.numInputs !== 0 && { numInputs: s.numInputs },
710
+ ...s.inputAmount !== "0" && { inputAmount: s.inputAmount },
711
+ ...s.numOutputs !== 0 && { numOutputs: s.numOutputs },
712
+ ...s.outputAmount !== "0" && { outputAmount: s.outputAmount },
713
+ ...s.amountChange !== "0" && { amountChange: s.amountChange }
714
+ };
715
+ };
716
+ var renderHoldingsChange = (c) => {
717
+ if (c.creates.length === 0 && c.archives.length === 0) {
718
+ return void 0;
719
+ }
720
+ return {
721
+ ...c.creates.length !== 0 && { creates: c.creates },
722
+ ...c.archives.length !== 0 && { archives: c.archives }
723
+ };
724
+ };
725
+ var TransactionParser = class {
726
+ constructor(transaction, ledgerClient, partyId, isMasterUser) {
727
+ __publicField(this, "ledgerClient");
728
+ __publicField(this, "partyId");
729
+ __publicField(this, "transaction");
730
+ __publicField(this, "isMasterUser");
731
+ this.ledgerClient = ledgerClient;
732
+ this.partyId = partyId;
733
+ this.transaction = transaction;
734
+ this.isMasterUser = isMasterUser;
735
+ }
736
+ async parseTransaction() {
737
+ const tx = this.transaction;
738
+ const events = await this.parseEvents([...tx.events || []].reverse());
739
+ return {
740
+ updateId: tx.updateId,
741
+ offset: tx.offset,
742
+ recordTime: tx.recordTime,
743
+ synchronizerId: tx.synchronizerId,
744
+ events
745
+ };
746
+ }
747
+ async parseEvents(eventsStack) {
748
+ let callStack = [];
749
+ let continueAfterNodeId = -1;
750
+ const result = [];
751
+ while (eventsStack.length > 0) {
752
+ const currentEvent = eventsStack.pop();
753
+ const { nodeId, createdEvent, archivedEvent, exercisedEvent } = getNodeIdAndEvent(currentEvent);
754
+ callStack = callStack.filter((s) => s.untilNodeId <= nodeId);
755
+ const parentChoice = callStack[callStack.length - 1] && callStack[callStack.length - 1].parentChoiceName || "none (root node)";
756
+ let parsed;
757
+ if (nodeId <= continueAfterNodeId) {
758
+ parsed = null;
759
+ } else if (createdEvent) {
760
+ parsed = this.parseRawCreate(createdEvent, parentChoice);
761
+ } else if (archivedEvent) {
762
+ parsed = await this.parseRawArchive(archivedEvent, parentChoice);
763
+ } else if (exercisedEvent) {
764
+ parsed = await this.parseExercise(exercisedEvent);
765
+ } else {
766
+ throw new Error(
767
+ `Impossible event: ${JSON.stringify(currentEvent)}`
768
+ );
769
+ }
770
+ if (parsed && isLeafEventNode(parsed)) {
771
+ if (holdingChangesNonEmpty(parsed.event)) {
772
+ result.push({
773
+ ...parsed.event,
774
+ label: {
775
+ ...parsed.event.label,
776
+ meta: removeParsedMetaKeys(parsed.event.label.meta)
777
+ }
778
+ });
779
+ }
780
+ continueAfterNodeId = parsed.continueAfterNodeId;
781
+ } else if (parsed) {
782
+ callStack.push({
783
+ parentChoiceName: parsed.parentChoiceName,
784
+ untilNodeId: parsed.lastDescendantNodeId
785
+ });
786
+ }
787
+ }
788
+ return result;
789
+ }
790
+ parseRawCreate(create, parentChoice) {
791
+ return this.buildRawEvent(create, create.nodeId, (result) => {
792
+ return {
793
+ type: Number(result.lockedHoldingsChangeSummary.amountChange) > 0 ? "Lock" : "Create",
794
+ parentChoice,
795
+ contractId: create.contractId,
796
+ offset: create.offset,
797
+ templateId: create.templateId,
798
+ payload: result.payload,
799
+ packageName: create.packageName,
800
+ meta: void 0
801
+ };
802
+ });
803
+ }
804
+ async parseRawArchive(archive, parentChoice) {
805
+ const events = await this.getEventsForArchive(archive);
806
+ if (!events) {
807
+ return null;
808
+ }
809
+ return this.buildRawEvent(
810
+ events.created.createdEvent,
811
+ archive.nodeId,
812
+ (result) => {
813
+ return {
814
+ type: "Archive",
815
+ parentChoice,
816
+ contractId: archive.contractId,
817
+ offset: archive.offset,
818
+ templateId: archive.templateId,
819
+ packageName: archive.packageName,
820
+ actingParties: archive.actingParties || [],
821
+ payload: result.payload,
822
+ meta: void 0
823
+ };
824
+ }
825
+ );
826
+ }
827
+ buildRawEvent(originalCreate, nodeId, buildLabel) {
828
+ const view = getKnownInterfaceView(originalCreate);
829
+ let result;
830
+ switch (view?.type) {
831
+ case "Holding": {
832
+ const holdingView = view.viewValue;
833
+ if (this.partyId !== holdingView.owner) {
834
+ result = null;
835
+ } else {
836
+ const isLocked = !!holdingView.lock;
837
+ const summary = {
838
+ amountChange: holdingView.amount,
839
+ numInputs: 0,
840
+ inputAmount: "0",
841
+ numOutputs: 1,
842
+ outputAmount: holdingView.amount
843
+ };
844
+ result = {
845
+ payload: holdingView,
846
+ unlockedHoldingsChange: {
847
+ creates: isLocked ? [] : [holdingView],
848
+ archives: []
849
+ },
850
+ lockedHoldingsChange: {
851
+ creates: isLocked ? [holdingView] : [],
852
+ archives: []
853
+ },
854
+ lockedHoldingsChangeSummary: isLocked ? summary : EmptyHoldingsChangeSummary,
855
+ unlockedHoldingsChangeSummary: isLocked ? EmptyHoldingsChangeSummary : summary,
856
+ transferInstruction: null
857
+ };
858
+ }
859
+ break;
860
+ }
861
+ case "TransferInstruction": {
862
+ const transferInstructionView = view.viewValue;
863
+ if (![
864
+ transferInstructionView.transfer.sender,
865
+ transferInstructionView.transfer.receiver
866
+ ].some((stakeholder) => stakeholder === this.partyId)) {
867
+ result = null;
868
+ } else {
869
+ result = {
870
+ payload: transferInstructionView,
871
+ transferInstruction: transferInstructionView,
872
+ unlockedHoldingsChange: { creates: [], archives: [] },
873
+ lockedHoldingsChange: { creates: [], archives: [] },
874
+ unlockedHoldingsChangeSummary: EmptyHoldingsChangeSummary,
875
+ lockedHoldingsChangeSummary: EmptyHoldingsChangeSummary
876
+ };
877
+ }
878
+ break;
879
+ }
880
+ default:
881
+ result = null;
882
+ }
883
+ return result && {
884
+ continueAfterNodeId: nodeId,
885
+ event: {
886
+ label: buildLabel(result),
887
+ unlockedHoldingsChange: result.unlockedHoldingsChange,
888
+ lockedHoldingsChange: result.lockedHoldingsChange,
889
+ lockedHoldingsChangeSummary: result.lockedHoldingsChangeSummary,
890
+ unlockedHoldingsChangeSummary: result.unlockedHoldingsChangeSummary,
891
+ transferInstruction: result.transferInstruction
892
+ }
893
+ };
894
+ }
895
+ async parseExercise(exercise) {
896
+ let result = null;
897
+ const tokenStandardChoice = {
898
+ name: exercise.choice,
899
+ choiceArgument: exercise.choiceArgument,
900
+ exerciseResult: exercise.exerciseResult
901
+ };
902
+ switch (exercise.choice) {
903
+ case "TransferRule_Transfer":
904
+ case "TransferFactory_Transfer":
905
+ result = await this.buildTransfer(exercise, tokenStandardChoice);
906
+ break;
907
+ case "TransferInstruction_Accept":
908
+ case "TransferInstruction_Reject":
909
+ case "TransferInstruction_Withdraw":
910
+ case "TransferInstruction_Update":
911
+ result = await this.buildFromTransferInstructionExercise(
912
+ exercise,
913
+ tokenStandardChoice
914
+ );
915
+ break;
916
+ case "BurnMintFactory_BurnMint":
917
+ result = await this.buildMergeSplit(
918
+ exercise,
919
+ tokenStandardChoice
920
+ );
921
+ break;
922
+ default: {
923
+ const meta = mergeMetas(exercise);
924
+ const txKind = getMetaKeyValue(TxKindMetaKey, meta);
925
+ if (txKind) {
926
+ result = await this.parseViaTxKind(exercise, txKind);
927
+ }
928
+ break;
929
+ }
930
+ }
931
+ if (!result) {
932
+ return {
933
+ lastDescendantNodeId: exercise.lastDescendantNodeId,
934
+ parentChoiceName: exercise.choice
935
+ };
936
+ } else {
937
+ const lockedHoldingsChange = {
938
+ creates: result.children.creates.filter(
939
+ (h) => !!h.lock && h.owner === this.partyId
940
+ ),
941
+ archives: result.children.archives.filter(
942
+ (h) => !!h.lock && h.owner === this.partyId
943
+ )
944
+ };
945
+ const unlockedHoldingsChange = {
946
+ creates: result.children.creates.filter(
947
+ (h) => !h.lock && h.owner === this.partyId
948
+ ),
949
+ archives: result.children.archives.filter(
950
+ (h) => !h.lock && h.owner === this.partyId
951
+ )
952
+ };
953
+ return {
954
+ event: {
955
+ label: result.label,
956
+ lockedHoldingsChange,
957
+ lockedHoldingsChangeSummary: computeSummary(
958
+ lockedHoldingsChange,
959
+ this.partyId
960
+ ),
961
+ unlockedHoldingsChange,
962
+ unlockedHoldingsChangeSummary: computeSummary(
963
+ unlockedHoldingsChange,
964
+ this.partyId
965
+ ),
966
+ transferInstruction: result.transferInstruction
967
+ },
968
+ continueAfterNodeId: exercise.lastDescendantNodeId
969
+ };
970
+ }
971
+ }
972
+ async parseViaTxKind(exercisedEvent, txKind) {
973
+ switch (txKind) {
974
+ case "transfer":
975
+ return await this.buildTransfer(exercisedEvent, null);
976
+ case "merge-split":
977
+ case "burn":
978
+ case "mint":
979
+ return await this.buildMergeSplit(exercisedEvent, null);
980
+ case "unlock":
981
+ return await this.buildBasic(exercisedEvent, "Unlock", null);
982
+ case "expire-dust":
983
+ return await this.buildBasic(exercisedEvent, "ExpireDust", null);
984
+ default:
985
+ throw new Error(
986
+ `Unknown tx-kind '${txKind}' in ${JSON.stringify(exercisedEvent)}`
987
+ );
988
+ }
989
+ }
990
+ async buildTransfer(exercisedEvent, tokenStandardChoice, transferInstructions) {
991
+ const meta = mergeMetas(
992
+ exercisedEvent,
993
+ transferInstructions?.transfer?.meta
994
+ );
995
+ const reason = getMetaKeyValue(ReasonMetaKey, meta);
996
+ const choiceArgumentTransfer = exercisedEvent.choiceArgument.transfer;
997
+ const sender = transferInstructions?.transfer?.sender || getMetaKeyValue(SenderMetaKey, meta) || choiceArgumentTransfer.sender;
998
+ if (!sender) {
999
+ console.error(
1000
+ `Malformed transfer didn't contain sender. Will instead attempt to parse the children.
1001
+ Transfer: ${JSON.stringify(exercisedEvent)}`
1002
+ );
1003
+ return null;
1004
+ }
1005
+ const children = await this.getChildren(exercisedEvent);
1006
+ const receiverAmounts = /* @__PURE__ */ new Map();
1007
+ children.creates.filter((h) => h.owner !== sender).forEach(
1008
+ (holding) => receiverAmounts.set(
1009
+ holding.owner,
1010
+ (receiverAmounts.get(holding.owner) || BigNumber__default.default("0")).plus(
1011
+ BigNumber__default.default(holding.amount)
1012
+ )
1013
+ )
1014
+ );
1015
+ const amountChanges = computeAmountChanges(children, meta, this.partyId);
1016
+ let label;
1017
+ if (receiverAmounts.size === 0) {
1018
+ label = {
1019
+ ...amountChanges,
1020
+ type: "MergeSplit",
1021
+ tokenStandardChoice,
1022
+ reason,
1023
+ meta
1024
+ };
1025
+ } else if (sender === this.partyId) {
1026
+ label = {
1027
+ ...amountChanges,
1028
+ type: "TransferOut",
1029
+ receiverAmounts: [...receiverAmounts].map(([k, v]) => {
1030
+ return { receiver: k, amount: v.toString() };
1031
+ }),
1032
+ tokenStandardChoice,
1033
+ reason,
1034
+ meta
1035
+ };
1036
+ } else {
1037
+ label = {
1038
+ type: "TransferIn",
1039
+ // for Transfers, the burn/mint is always 0 for the receiving party (i.e., 0 for TransferIn)
1040
+ burnAmount: "0",
1041
+ mintAmount: "0",
1042
+ sender,
1043
+ tokenStandardChoice,
1044
+ reason,
1045
+ meta
1046
+ };
1047
+ }
1048
+ const transferInstruction = {
1049
+ originalInstructionCid: null,
1050
+ transfer: choiceArgumentTransfer,
1051
+ status: {
1052
+ before: null
1053
+ },
1054
+ meta: null
1055
+ };
1056
+ return {
1057
+ label,
1058
+ children,
1059
+ transferInstruction
1060
+ };
1061
+ }
1062
+ async buildMergeSplit(exercisedEvent, tokenStandardChoice) {
1063
+ let type;
1064
+ const meta = mergeMetas(exercisedEvent);
1065
+ switch (getMetaKeyValue(TxKindMetaKey, meta)) {
1066
+ case "burn":
1067
+ type = "Burn";
1068
+ break;
1069
+ case "mint":
1070
+ type = "Mint";
1071
+ break;
1072
+ default:
1073
+ type = "MergeSplit";
1074
+ }
1075
+ const reason = getMetaKeyValue(ReasonMetaKey, meta);
1076
+ const children = await this.getChildren(exercisedEvent);
1077
+ const amountChanges = computeAmountChanges(children, meta, this.partyId);
1078
+ const label = {
1079
+ ...amountChanges,
1080
+ type,
1081
+ tokenStandardChoice,
1082
+ reason,
1083
+ meta
1084
+ };
1085
+ return {
1086
+ label,
1087
+ children,
1088
+ transferInstruction: null
1089
+ };
1090
+ }
1091
+ async buildFromTransferInstructionExercise(exercisedEvent, tokenStandardChoice) {
1092
+ const transferInstructionEvents = await this.getEventsForArchive(exercisedEvent);
1093
+ if (!transferInstructionEvents) {
1094
+ return null;
1095
+ }
1096
+ const transferInstructionView = ensureInterfaceViewIsPresent(
1097
+ transferInstructionEvents.created.createdEvent,
1098
+ coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID
1099
+ ).viewValue;
1100
+ const transferInstruction = {
1101
+ originalInstructionCid: transferInstructionView.originalInstructionCid,
1102
+ transfer: transferInstructionView.transfer,
1103
+ meta: transferInstructionView.meta,
1104
+ status: {
1105
+ before: transferInstructionView.status
1106
+ }
1107
+ };
1108
+ const exerciseResultOutputTag = exercisedEvent.exerciseResult.output.tag;
1109
+ let result = null;
1110
+ switch (exerciseResultOutputTag) {
1111
+ case "TransferInstructionResult_Failed":
1112
+ case "TransferInstructionResult_Pending":
1113
+ result = await this.buildMergeSplit(
1114
+ exercisedEvent,
1115
+ tokenStandardChoice
1116
+ );
1117
+ break;
1118
+ case "TransferInstructionResult_Completed":
1119
+ result = await this.buildTransfer(
1120
+ exercisedEvent,
1121
+ tokenStandardChoice,
1122
+ transferInstruction
1123
+ );
1124
+ break;
1125
+ default:
1126
+ throw new Error(
1127
+ `Unknown TransferInstructionResult: ${exerciseResultOutputTag}`
1128
+ );
1129
+ }
1130
+ return result && {
1131
+ ...result,
1132
+ transferInstruction
1133
+ };
1134
+ }
1135
+ async buildBasic(exercisedEvent, type, tokenStandardChoice) {
1136
+ const children = await this.getChildren(exercisedEvent);
1137
+ const meta = mergeMetas(exercisedEvent);
1138
+ const amountChanges = computeAmountChanges(children, meta, this.partyId);
1139
+ const reason = getMetaKeyValue(ReasonMetaKey, meta);
1140
+ return {
1141
+ label: {
1142
+ ...amountChanges,
1143
+ type,
1144
+ tokenStandardChoice,
1145
+ reason,
1146
+ meta
1147
+ },
1148
+ children,
1149
+ transferInstruction: null
1150
+ };
1151
+ }
1152
+ async getChildren(exercisedEvent) {
1153
+ const mutatingResult = { creates: [], archives: [] };
1154
+ const childrenEventsSlice = (this.transaction.events || []).map(getNodeIdAndEvent).filter(
1155
+ ({ nodeId }) => nodeId > exercisedEvent.nodeId && nodeId <= exercisedEvent.lastDescendantNodeId
1156
+ );
1157
+ if (exercisedEvent.consuming && hasInterface(coreTokenStandard.HOLDING_INTERFACE_ID, exercisedEvent)) {
1158
+ const selfEvent = await this.getEventsForArchive(exercisedEvent);
1159
+ if (selfEvent) {
1160
+ const holdingView = ensureInterfaceViewIsPresent(
1161
+ selfEvent.created.createdEvent,
1162
+ coreTokenStandard.HOLDING_INTERFACE_ID
1163
+ ).viewValue;
1164
+ mutatingResult.archives.push({
1165
+ amount: holdingView.amount,
1166
+ instrumentId: holdingView.instrumentId,
1167
+ contractId: exercisedEvent.contractId,
1168
+ owner: holdingView.owner,
1169
+ meta: holdingView.meta,
1170
+ lock: holdingView.lock
1171
+ });
1172
+ }
1173
+ }
1174
+ for (const {
1175
+ createdEvent,
1176
+ archivedEvent,
1177
+ exercisedEvent: exercisedEvent2
1178
+ } of childrenEventsSlice) {
1179
+ if (createdEvent) {
1180
+ const interfaceView = getInterfaceView(createdEvent);
1181
+ if (interfaceView && matchInterfaceIds(
1182
+ coreTokenStandard.HOLDING_INTERFACE_ID,
1183
+ interfaceView.interfaceId
1184
+ )) {
1185
+ const holdingView = interfaceView.viewValue;
1186
+ mutatingResult.creates.push({
1187
+ amount: holdingView.amount,
1188
+ instrumentId: holdingView.instrumentId,
1189
+ contractId: createdEvent.contractId,
1190
+ owner: holdingView.owner,
1191
+ meta: holdingView.meta,
1192
+ lock: holdingView.lock
1193
+ });
1194
+ }
1195
+ } else if (archivedEvent && hasInterface(coreTokenStandard.HOLDING_INTERFACE_ID, archivedEvent) || exercisedEvent2 && exercisedEvent2.consuming && hasInterface(coreTokenStandard.HOLDING_INTERFACE_ID, exercisedEvent2)) {
1196
+ const contractEvents = await this.getEventsForArchive(
1197
+ archivedEvent || exercisedEvent2
1198
+ );
1199
+ if (contractEvents) {
1200
+ const holdingView = ensureInterfaceViewIsPresent(
1201
+ contractEvents.created?.createdEvent,
1202
+ coreTokenStandard.HOLDING_INTERFACE_ID
1203
+ ).viewValue;
1204
+ mutatingResult.archives.push({
1205
+ amount: holdingView.amount,
1206
+ instrumentId: holdingView.instrumentId,
1207
+ contractId: archivedEvent?.contractId || exercisedEvent2.contractId,
1208
+ owner: holdingView.owner,
1209
+ meta: holdingView.meta,
1210
+ lock: holdingView.lock
1211
+ });
1212
+ }
1213
+ }
1214
+ }
1215
+ return {
1216
+ // remove transient contracts
1217
+ creates: mutatingResult.creates.filter(
1218
+ (create) => !mutatingResult.archives.some(
1219
+ (archive) => create.contractId === archive.contractId
1220
+ )
1221
+ ),
1222
+ archives: mutatingResult.archives.filter(
1223
+ (archive) => !mutatingResult.creates.some(
1224
+ (create) => create.contractId === archive.contractId
1225
+ )
1226
+ )
1227
+ };
1228
+ }
1229
+ async getEventsForArchive(archivedEvent) {
1230
+ if (!(archivedEvent.witnessParties || []).includes(this.partyId)) {
1231
+ return null;
1232
+ }
1233
+ const basePayload = {
1234
+ contractId: archivedEvent.contractId,
1235
+ eventFormat: EventFilterBySetup(
1236
+ [coreTokenStandard.HOLDING_INTERFACE_ID, coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID],
1237
+ {
1238
+ isMasterUser: this.isMasterUser,
1239
+ partyId: this.partyId,
1240
+ verbose: true
1241
+ }
1242
+ )
1243
+ };
1244
+ const payload = this.ledgerClient.getCurrentClientVersion() === "3.3" ? { ...basePayload, requestingParties: [] } : basePayload;
1245
+ const events = await this.ledgerClient.postWithRetry("/v2/events/events-by-contract-id", payload).catch((err) => {
1246
+ if (err.code === "CONTRACT_EVENTS_NOT_FOUND") {
1247
+ return null;
1248
+ } else {
1249
+ throw err;
1250
+ }
1251
+ });
1252
+ if (!events) {
1253
+ return null;
1254
+ }
1255
+ const created = events.created;
1256
+ const archived = events.archived;
1257
+ if (!created || !archived) {
1258
+ throw new Error(
1259
+ `Archival of ${archivedEvent.contractId} does not have a corresponding create/archive event: ${JSON.stringify(
1260
+ events
1261
+ )}`
1262
+ );
1263
+ }
1264
+ return { created, archived };
1265
+ }
1266
+ };
1267
+ function isLeafEventNode(result) {
1268
+ return !!result.event;
1269
+ }
1270
+ function getNodeIdAndEvent(event) {
1271
+ if (event.ExercisedEvent) {
1272
+ if (event.ExercisedEvent.choice === "Archive") {
1273
+ return {
1274
+ nodeId: event.ExercisedEvent.nodeId,
1275
+ archivedEvent: event.ExercisedEvent
1276
+ };
1277
+ } else {
1278
+ return {
1279
+ nodeId: event.ExercisedEvent.nodeId,
1280
+ exercisedEvent: event.ExercisedEvent
1281
+ };
1282
+ }
1283
+ } else if (event.CreatedEvent) {
1284
+ return {
1285
+ nodeId: event.CreatedEvent.nodeId,
1286
+ createdEvent: event.CreatedEvent
1287
+ };
1288
+ } else if (event.ArchivedEvent) {
1289
+ return {
1290
+ nodeId: event.ArchivedEvent.nodeId,
1291
+ archivedEvent: event.ArchivedEvent
1292
+ };
1293
+ } else {
1294
+ throw new Error(`Impossible event type: ${event}`);
1295
+ }
1296
+ }
1297
+ function sumHoldingsChange(change, filter) {
1298
+ return sumHoldings(
1299
+ change.creates.filter((create) => filter(create.owner, create.lock))
1300
+ ).minus(
1301
+ sumHoldings(
1302
+ change.archives.filter(
1303
+ (archive) => filter(archive.owner, archive.lock)
1304
+ )
1305
+ )
1306
+ );
1307
+ }
1308
+ function sumHoldings(holdings) {
1309
+ return BigNumber__default.default.sum(
1310
+ ...holdings.map((h) => h.amount).concat(["0"])
1311
+ // avoid NaN
1312
+ );
1313
+ }
1314
+ function computeAmountChanges(children, meta, partyId) {
1315
+ const burnAmount = BigNumber__default.default(getMetaKeyValue(BurnedMetaKey, meta) || "0");
1316
+ const partyHoldingAmountChange = sumHoldingsChange(
1317
+ children,
1318
+ (owner) => owner === partyId
1319
+ );
1320
+ const otherPartiesHoldingAmountChange = sumHoldingsChange(
1321
+ children,
1322
+ (owner) => owner !== partyId
1323
+ );
1324
+ const mintAmount = partyHoldingAmountChange.plus(burnAmount).plus(otherPartiesHoldingAmountChange);
1325
+ return {
1326
+ burnAmount: burnAmount.toString(),
1327
+ mintAmount: mintAmount.toString()
1328
+ };
1329
+ }
1330
+ function computeSummary(changes, partyId) {
1331
+ const amountChange = sumHoldingsChange(
1332
+ changes,
1333
+ (owner) => owner === partyId
1334
+ );
1335
+ const outputAmount = sumHoldings(changes.creates);
1336
+ const inputAmount = sumHoldings(changes.archives);
1337
+ return {
1338
+ amountChange: amountChange.toString(),
1339
+ numOutputs: changes.creates.length,
1340
+ outputAmount: outputAmount.toString(),
1341
+ numInputs: changes.archives.length,
1342
+ inputAmount: inputAmount.toString()
1343
+ };
1344
+ }
1345
+ function holdingChangesNonEmpty(event) {
1346
+ return event.unlockedHoldingsChange.creates.length > 0 || event.unlockedHoldingsChange.archives.length > 0 || event.lockedHoldingsChange.creates.length > 0 || event.lockedHoldingsChange.archives.length > 0;
1347
+ }
1348
+
1349
+ // src/token-standard-service.ts
1350
+ var MEMO_KEY = "splice.lfdecentralizedtrust.org/reason";
1351
+ var REQUESTED_AT_SKEW_MS = 6e4;
1352
+ var EMPTY_META = { values: {} };
1353
+ var CoreService = class {
1354
+ constructor(ledgerClient, scanProxyClient, logger, accessTokenProvider, isMasterUser, isAdmin = false, accessToken = "") {
1355
+ this.ledgerClient = ledgerClient;
1356
+ this.scanProxyClient = scanProxyClient;
1357
+ this.logger = logger;
1358
+ this.accessTokenProvider = accessTokenProvider;
1359
+ this.isMasterUser = isMasterUser;
1360
+ this.isAdmin = isAdmin;
1361
+ this.accessToken = accessToken;
1362
+ }
1363
+ getTokenStandardClient(registryUrl) {
1364
+ return new coreTokenStandard.TokenStandardClient(
1365
+ registryUrl,
1366
+ this.logger,
1367
+ this.isAdmin,
1368
+ this.accessToken,
1369
+ this.accessTokenProvider
1370
+ );
1371
+ }
1372
+ async getInputHoldingsCids(sender, inputUtxos) {
1373
+ const now = /* @__PURE__ */ new Date();
1374
+ if (inputUtxos && inputUtxos.length > 0) {
1375
+ return inputUtxos;
1376
+ }
1377
+ const senderHoldings = await this.listContractsByInterface(
1378
+ coreTokenStandard.HOLDING_INTERFACE_ID,
1379
+ sender
1380
+ );
1381
+ if (senderHoldings.length === 0) {
1382
+ throw new Error(
1383
+ "Sender has no holdings, so transfer can't be executed."
1384
+ );
1385
+ }
1386
+ return senderHoldings.filter((utxo) => {
1387
+ const lock = utxo.interfaceViewValue.lock;
1388
+ if (!lock) return true;
1389
+ const expiresAt = lock.expiresAt;
1390
+ if (!expiresAt) return false;
1391
+ const expiresAtDate = new Date(expiresAt);
1392
+ return expiresAtDate <= now;
1393
+ }).map((h) => h.contractId);
1394
+ }
1395
+ async listContractsByInterface(interfaceId, partyId, limit) {
1396
+ try {
1397
+ const ledgerEnd = await this.ledgerClient.getWithRetry(
1398
+ "/v2/state/ledger-end"
1399
+ );
1400
+ const acsResponses = await this.ledgerClient.postWithRetry(
1401
+ "/v2/state/active-contracts",
1402
+ {
1403
+ filter: TransactionFilterBySetup(interfaceId, {
1404
+ isMasterUser: this.isMasterUser,
1405
+ partyId
1406
+ }),
1407
+ verbose: false,
1408
+ activeAtOffset: ledgerEnd.offset
1409
+ },
1410
+ defaultRetryableOptions,
1411
+ {
1412
+ query: limit ? { limit: limit.toString() } : {}
1413
+ }
1414
+ );
1415
+ const isActiveContractEntry = (acsResponse) => !!acsResponse.contractEntry.JsActiveContract?.createdEvent;
1416
+ const activeContractEntries = acsResponses.filter(
1417
+ isActiveContractEntry
1418
+ );
1419
+ return activeContractEntries.map(
1420
+ (response) => this.toPrettyContract(interfaceId, response)
1421
+ );
1422
+ } catch (err) {
1423
+ this.logger.error(
1424
+ `Failed to list contracts of interface ${interfaceId}`,
1425
+ err
1426
+ );
1427
+ throw err;
1428
+ }
1429
+ }
1430
+ async toPrettyTransactions(updates, partyId, ledgerClient) {
1431
+ const isOffsetCheckpointUpdate = (updateResponse) => !!updateResponse?.update?.OffsetCheckpoint;
1432
+ const isTransactionUpdate = (updateResponse) => !!updateResponse.update?.Transaction?.value;
1433
+ const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map((update) => update.update.OffsetCheckpoint.value.offset);
1434
+ const latestCheckpointOffset = Math.max(...offsetCheckpoints);
1435
+ const transactions = await Promise.all(
1436
+ updates.filter(isTransactionUpdate).map(async (update) => {
1437
+ const tx = update.update.Transaction.value;
1438
+ const parser = new TransactionParser(
1439
+ tx,
1440
+ ledgerClient,
1441
+ partyId,
1442
+ this.isMasterUser
1443
+ );
1444
+ return await parser.parseTransaction();
1445
+ })
1446
+ );
1447
+ return {
1448
+ // OffsetCheckpoint can be anywhere... or not at all, maybe
1449
+ nextOffset: Math.max(
1450
+ latestCheckpointOffset,
1451
+ ...transactions.map((tx) => tx.offset)
1452
+ ),
1453
+ transactions: transactions.filter((tx) => tx.events.length > 0).map(renderTransaction)
1454
+ };
1455
+ }
1456
+ async toPrettyTransaction(getTransactionResponse, partyId, ledgerClient) {
1457
+ const tx = getTransactionResponse.transaction;
1458
+ const parser = new TransactionParser(
1459
+ tx,
1460
+ ledgerClient,
1461
+ partyId,
1462
+ this.isMasterUser
1463
+ );
1464
+ const parsedTx = await parser.parseTransaction();
1465
+ return renderTransaction(parsedTx);
1466
+ }
1467
+ async toPrettyTransactionsPerParty(updates, parties, ledgerClient) {
1468
+ const all = await Promise.all(
1469
+ parties.map(
1470
+ async (partyId) => [
1471
+ partyId,
1472
+ await this.toPrettyTransactions(
1473
+ updates,
1474
+ partyId,
1475
+ ledgerClient
1476
+ )
1477
+ ]
1478
+ )
1479
+ );
1480
+ return new Map(all);
1481
+ }
1482
+ // returns object with JsActiveContract content
1483
+ // and contractId and interface view value extracted from it as separate fields for convenience
1484
+ toPrettyContract(interfaceId, response) {
1485
+ const activeContract = response.contractEntry.JsActiveContract;
1486
+ const { createdEvent } = activeContract;
1487
+ return {
1488
+ contractId: createdEvent.contractId,
1489
+ activeContract,
1490
+ interfaceViewValue: ensureInterfaceViewIsPresent(
1491
+ createdEvent,
1492
+ interfaceId
1493
+ ).viewValue
1494
+ };
1495
+ }
1496
+ };
1497
+ var AllocationService = class {
1498
+ constructor(core, logger) {
1499
+ this.core = core;
1500
+ this.logger = logger;
1501
+ }
1502
+ async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
1503
+ const allocationSpecificationNormalized = {
1504
+ ...allocationSpecification,
1505
+ settlement: {
1506
+ ...allocationSpecification.settlement,
1507
+ meta: allocationSpecification.settlement.meta ?? { values: {} }
1508
+ },
1509
+ transferLeg: {
1510
+ ...allocationSpecification.transferLeg,
1511
+ meta: allocationSpecification.transferLeg.meta ?? {
1512
+ values: {}
1513
+ }
1514
+ }
1515
+ };
1516
+ const inputHoldingCids = await this.core.getInputHoldingsCids(
1517
+ allocationSpecificationNormalized.transferLeg.sender,
1518
+ inputUtxos
1519
+ );
1520
+ return {
1521
+ expectedAdmin,
1522
+ allocation: allocationSpecificationNormalized,
1523
+ requestedAt: requestedAt ?? new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
1524
+ inputHoldingCids,
1525
+ extraArgs: {
1526
+ context: { values: {} },
1527
+ meta: { values: {} }
1528
+ }
1529
+ };
1530
+ }
1531
+ async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs) {
1532
+ return this.core.getTokenStandardClient(registryUrl).post("/registry/allocation-instruction/v1/allocation-factory", {
1533
+ choiceArguments: choiceArgs
1534
+ });
1535
+ }
1536
+ async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
1537
+ choiceArgs.extraArgs.context = {
1538
+ ...choiceContext.choiceContextData,
1539
+ values: choiceContext.choiceContextData?.values ?? {}
1540
+ };
1541
+ const exercise = {
1542
+ templateId: coreTokenStandard.ALLOCATION_FACTORY_INTERFACE_ID,
1543
+ contractId: factoryId,
1544
+ choice: "AllocationFactory_Allocate",
1545
+ choiceArgument: choiceArgs
1546
+ };
1547
+ return [exercise, choiceContext.disclosedContracts];
1548
+ }
1549
+ async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
1550
+ const choiceArgs = await this.buildAllocationFactoryChoiceArgs(
1551
+ allocationSpecification,
1552
+ expectedAdmin,
1553
+ inputUtxos,
1554
+ requestedAt
1555
+ );
1556
+ if (prefetchedRegistryChoiceContext) {
1557
+ return this.createAllocationInstructionFromContext(
1558
+ prefetchedRegistryChoiceContext.factoryId,
1559
+ choiceArgs,
1560
+ prefetchedRegistryChoiceContext.choiceContext
1561
+ );
1562
+ }
1563
+ const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(
1564
+ registryUrl,
1565
+ choiceArgs
1566
+ );
1567
+ return this.createAllocationInstructionFromContext(
1568
+ factoryId,
1569
+ choiceArgs,
1570
+ choiceContext
1571
+ );
1572
+ }
1573
+ buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
1574
+ const exercise = {
1575
+ templateId,
1576
+ contractId,
1577
+ choice,
1578
+ choiceArgument: {
1579
+ extraArgs: {
1580
+ context: choiceContext.choiceContextData,
1581
+ meta: EMPTY_META
1582
+ }
1583
+ }
1584
+ };
1585
+ return [exercise, choiceContext.disclosedContracts ?? []];
1586
+ }
1587
+ async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
1588
+ return this.core.getTokenStandardClient(registryUrl).post(
1589
+ "/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer",
1590
+ {},
1591
+ {
1592
+ path: {
1593
+ allocationId
1594
+ }
1595
+ }
1596
+ );
1597
+ }
1598
+ createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
1599
+ return this.buildAllocationExerciseWithContext(
1600
+ coreTokenStandard.ALLOCATION_INTERFACE_ID,
1601
+ allocationCid,
1602
+ "Allocation_ExecuteTransfer",
1603
+ choiceContext
1604
+ );
1605
+ }
1606
+ async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1607
+ if (prefetchedRegistryChoiceContext) {
1608
+ return this.createExecuteTransferAllocationFromContext(
1609
+ allocationCid,
1610
+ prefetchedRegistryChoiceContext
1611
+ );
1612
+ }
1613
+ const choiceContext = await this.fetchExecuteTransferChoiceContext(
1614
+ allocationCid,
1615
+ registryUrl
1616
+ );
1617
+ return this.createExecuteTransferAllocationFromContext(
1618
+ allocationCid,
1619
+ choiceContext
1620
+ );
1621
+ }
1622
+ async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
1623
+ return this.core.getTokenStandardClient(registryUrl).post(
1624
+ "/registry/allocations/v1/{allocationId}/choice-contexts/withdraw",
1625
+ {},
1626
+ { path: { allocationId: allocationCid } }
1627
+ );
1628
+ }
1629
+ createWithdrawAllocationFromContext(allocationCid, choiceContext) {
1630
+ return this.buildAllocationExerciseWithContext(
1631
+ coreTokenStandard.ALLOCATION_INTERFACE_ID,
1632
+ allocationCid,
1633
+ "Allocation_Withdraw",
1634
+ choiceContext
1635
+ );
1636
+ }
1637
+ async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1638
+ if (prefetchedRegistryChoiceContext) {
1639
+ return this.createWithdrawAllocationFromContext(
1640
+ allocationCid,
1641
+ prefetchedRegistryChoiceContext
1642
+ );
1643
+ }
1644
+ const choiceContext = await this.fetchWithdrawAllocationChoiceContext(
1645
+ allocationCid,
1646
+ registryUrl
1647
+ );
1648
+ return this.createWithdrawAllocationFromContext(
1649
+ allocationCid,
1650
+ choiceContext
1651
+ );
1652
+ }
1653
+ async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
1654
+ return this.core.getTokenStandardClient(registryUrl).post(
1655
+ "/registry/allocations/v1/{allocationId}/choice-contexts/cancel",
1656
+ {},
1657
+ { path: { allocationId: allocationCid } }
1658
+ );
1659
+ }
1660
+ createCancelAllocationFromContext(allocationCid, choiceContext) {
1661
+ return this.buildAllocationExerciseWithContext(
1662
+ coreTokenStandard.ALLOCATION_INTERFACE_ID,
1663
+ allocationCid,
1664
+ "Allocation_Cancel",
1665
+ choiceContext
1666
+ );
1667
+ }
1668
+ async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1669
+ if (prefetchedRegistryChoiceContext) {
1670
+ return this.createCancelAllocationFromContext(
1671
+ allocationCid,
1672
+ prefetchedRegistryChoiceContext
1673
+ );
1674
+ }
1675
+ const choiceContext = await this.fetchCancelAllocationChoiceContext(
1676
+ allocationCid,
1677
+ registryUrl
1678
+ );
1679
+ return this.createCancelAllocationFromContext(
1680
+ allocationCid,
1681
+ choiceContext
1682
+ );
1683
+ }
1684
+ async createWithdrawAllocationInstruction(allocationInstructionCid) {
1685
+ const exercise = {
1686
+ templateId: coreTokenStandard.ALLOCATION_INSTRUCTION_INTERFACE_ID,
1687
+ contractId: allocationInstructionCid,
1688
+ choice: "AllocationInstruction_Withdraw",
1689
+ choiceArgument: {
1690
+ extraArgs: {
1691
+ context: { values: {} },
1692
+ meta: { values: {} }
1693
+ }
1694
+ }
1695
+ };
1696
+ return [exercise, []];
1697
+ }
1698
+ async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
1699
+ const exercise = {
1700
+ templateId: coreTokenStandard.ALLOCATION_INSTRUCTION_INTERFACE_ID,
1701
+ contractId: allocationInstructionCid,
1702
+ choice: "AllocationInstruction_Update",
1703
+ choiceArgument: {
1704
+ extraActors,
1705
+ extraArgs: {
1706
+ context: { values: extraArgsContext },
1707
+ meta: { values: extraArgsMeta }
1708
+ }
1709
+ }
1710
+ };
1711
+ return [exercise, []];
1712
+ }
1713
+ async createRejectAllocationRequest(allocationRequestCid, actor) {
1714
+ const exercise = {
1715
+ templateId: coreTokenStandard.ALLOCATION_REQUEST_INTERFACE_ID,
1716
+ contractId: allocationRequestCid,
1717
+ choice: "AllocationRequest_Reject",
1718
+ choiceArgument: {
1719
+ actor,
1720
+ extraArgs: {
1721
+ context: { values: {} },
1722
+ meta: { values: {} }
1723
+ }
1724
+ }
1725
+ };
1726
+ return [exercise, []];
1727
+ }
1728
+ async createWithdrawAllocationRequest(allocationRequestCid) {
1729
+ const exercise = {
1730
+ templateId: coreTokenStandard.ALLOCATION_REQUEST_INTERFACE_ID,
1731
+ contractId: allocationRequestCid,
1732
+ choice: "AllocationRequest_Withdraw",
1733
+ choiceArgument: {
1734
+ extraArgs: {
1735
+ context: { values: {} },
1736
+ meta: { values: {} }
1737
+ }
1738
+ }
1739
+ };
1740
+ return [exercise, []];
1741
+ }
1742
+ };
1743
+ var TransferService = class {
1744
+ constructor(core, logger) {
1745
+ this.core = core;
1746
+ this.logger = logger;
1747
+ }
1748
+ async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta) {
1749
+ const inputHoldingCids = await this.core.getInputHoldingsCids(
1750
+ sender,
1751
+ inputUtxos
1752
+ );
1753
+ return {
1754
+ expectedAdmin: instrumentAdmin,
1755
+ transfer: {
1756
+ sender,
1757
+ receiver,
1758
+ amount,
1759
+ instrumentId: { admin: instrumentAdmin, id: instrumentId },
1760
+ requestedAt: new Date(
1761
+ Date.now() - REQUESTED_AT_SKEW_MS
1762
+ ).toISOString(),
1763
+ executeBefore: (expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1e3)).toISOString(),
1764
+ inputHoldingCids,
1765
+ meta: { values: { [MEMO_KEY]: memo || "", ...meta?.values } }
1766
+ },
1767
+ extraArgs: {
1768
+ context: { values: {} },
1769
+ meta: { values: {} }
1770
+ }
1771
+ };
1772
+ }
1773
+ async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs) {
1774
+ return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
1775
+ choiceArguments: choiceArgs
1776
+ });
1777
+ }
1778
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
1779
+ this.logger.debug("Creating transfer from pre-fetched context...");
1780
+ choiceArgs.extraArgs.context = {
1781
+ ...choiceContext.choiceContextData,
1782
+ values: choiceContext.choiceContextData?.values ?? {}
1783
+ };
1784
+ const exercise = {
1785
+ templateId: coreTokenStandard.TRANSFER_FACTORY_INTERFACE_ID,
1786
+ contractId: factoryId,
1787
+ choice: "TransferFactory_Transfer",
1788
+ choiceArgument: choiceArgs
1789
+ };
1790
+ return [exercise, choiceContext.disclosedContracts];
1791
+ }
1792
+ async createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext) {
1793
+ try {
1794
+ const choiceArgs = await this.buildTransferChoiceArgs(
1795
+ sender,
1796
+ receiver,
1797
+ amount,
1798
+ instrumentAdmin,
1799
+ instrumentId,
1800
+ inputUtxos,
1801
+ memo,
1802
+ expiryDate,
1803
+ meta
1804
+ );
1805
+ if (prefetchedRegistryChoiceContext) {
1806
+ return this.createTransferFromContext(
1807
+ prefetchedRegistryChoiceContext.factoryId,
1808
+ choiceArgs,
1809
+ prefetchedRegistryChoiceContext.choiceContext
1810
+ );
1811
+ }
1812
+ const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(
1813
+ registryUrl,
1814
+ choiceArgs
1815
+ );
1816
+ return this.createTransferFromContext(
1817
+ factoryId,
1818
+ choiceArgs,
1819
+ choiceContext
1820
+ );
1821
+ } catch (e) {
1822
+ this.logger.error("Failed to execute transfer:", e);
1823
+ throw e;
1824
+ }
1825
+ }
1826
+ async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
1827
+ const client = this.core.getTokenStandardClient(registryUrl);
1828
+ const choiceContext = await client.post(
1829
+ "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept",
1830
+ {},
1831
+ {
1832
+ path: {
1833
+ transferInstructionId: transferInstructionCid
1834
+ }
1835
+ }
1836
+ );
1837
+ return {
1838
+ choiceContextData: choiceContext.choiceContextData,
1839
+ disclosedContracts: choiceContext.disclosedContracts
1840
+ };
1841
+ }
1842
+ async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
1843
+ try {
1844
+ const exercise = {
1845
+ templateId: coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID,
1846
+ contractId: transferInstructionCid,
1847
+ choice: "TransferInstruction_Accept",
1848
+ choiceArgument: {
1849
+ extraArgs: {
1850
+ context: choiceContext.choiceContextData,
1851
+ meta: { values: {} }
1852
+ }
1853
+ }
1854
+ };
1855
+ return [exercise, choiceContext.disclosedContracts];
1856
+ } catch (e) {
1857
+ this.logger.error(
1858
+ "Failed to create accept transfer instruction:",
1859
+ e
1860
+ );
1861
+ throw e;
1862
+ }
1863
+ }
1864
+ async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1865
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(
1866
+ transferInstructionCid,
1867
+ registryUrl.href
1868
+ );
1869
+ const choiceArgs = {
1870
+ cid: acceptTransferInstructionContext.contractId,
1871
+ proxyArg: {
1872
+ featuredAppRightCid,
1873
+ beneficiaries,
1874
+ choiceArg: acceptTransferInstructionContext.choiceArgument
1875
+ }
1876
+ };
1877
+ return [
1878
+ {
1879
+ templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1880
+ contractId: proxyCid,
1881
+ choice: "DelegateProxy_TransferInstruction_Accept",
1882
+ choiceArgument: choiceArgs
1883
+ },
1884
+ disclosedContracts
1885
+ ];
1886
+ }
1887
+ async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1888
+ const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(
1889
+ transferInstructionCid,
1890
+ registryUrl.href
1891
+ );
1892
+ const choiceArgs = {
1893
+ cid: rejectTransferInstructionContext.contractId,
1894
+ proxyArg: {
1895
+ featuredAppRightCid,
1896
+ beneficiaries,
1897
+ choiceArg: rejectTransferInstructionContext.choiceArgument
1898
+ }
1899
+ };
1900
+ return [
1901
+ {
1902
+ templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1903
+ contractId: proxyCid,
1904
+ choice: "DelegateProxy_TransferInstruction_Reject",
1905
+ choiceArgument: choiceArgs
1906
+ },
1907
+ disclosedContracts
1908
+ ];
1909
+ }
1910
+ async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1911
+ const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(
1912
+ transferInstructionCid,
1913
+ registryUrl.href
1914
+ );
1915
+ const sumOfWeights = beneficiaries.reduce(
1916
+ (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
1917
+ 0
1918
+ );
1919
+ if (sumOfWeights > 1) {
1920
+ throw new Error("Sum of beneficiary weights is larger than 1.");
1921
+ }
1922
+ const choiceArgs = {
1923
+ cid: withdrawTransferInstructionContext.contractId,
1924
+ proxyArg: {
1925
+ featuredAppRightCid,
1926
+ beneficiaries,
1927
+ choiceArg: withdrawTransferInstructionContext.choiceArgument
1928
+ }
1929
+ };
1930
+ return [
1931
+ {
1932
+ templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1933
+ contractId: proxyCid,
1934
+ choice: "DelegateProxy_TransferInstruction_Withdraw",
1935
+ choiceArgument: choiceArgs
1936
+ },
1937
+ disclosedContracts
1938
+ ];
1939
+ }
1940
+ async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
1941
+ if (prefetchedRegistryChoiceContext) {
1942
+ return this.createAcceptTransferInstructionFromContext(
1943
+ transferInstructionCid,
1944
+ {
1945
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
1946
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
1947
+ }
1948
+ );
1949
+ }
1950
+ const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(
1951
+ transferInstructionCid,
1952
+ registryUrl
1953
+ );
1954
+ return this.createAcceptTransferInstructionFromContext(
1955
+ transferInstructionCid,
1956
+ choiceContext
1957
+ );
1958
+ }
1959
+ async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
1960
+ const client = this.core.getTokenStandardClient(registryUrl);
1961
+ const choiceContext = await client.post(
1962
+ "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject",
1963
+ {},
1964
+ {
1965
+ path: {
1966
+ transferInstructionId: transferInstructionCid
1967
+ }
1968
+ }
1969
+ );
1970
+ return {
1971
+ choiceContextData: choiceContext.choiceContextData,
1972
+ disclosedContracts: choiceContext.disclosedContracts
1973
+ };
1974
+ }
1975
+ async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
1976
+ try {
1977
+ const exercise = {
1978
+ templateId: coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID,
1979
+ contractId: transferInstructionCid,
1980
+ choice: "TransferInstruction_Reject",
1981
+ choiceArgument: {
1982
+ extraArgs: {
1983
+ context: choiceContext.choiceContextData,
1984
+ meta: { values: {} }
1985
+ }
1986
+ }
1987
+ };
1988
+ return [exercise, choiceContext.disclosedContracts];
1989
+ } catch (e) {
1990
+ this.logger.error(
1991
+ "Failed to create reject transfer instruction:",
1992
+ e
1993
+ );
1994
+ throw e;
1995
+ }
1996
+ }
1997
+ async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
1998
+ if (prefetchedRegistryChoiceContext) {
1999
+ return this.createRejectTransferInstructionFromContext(
2000
+ transferInstructionCid,
2001
+ {
2002
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
2003
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
2004
+ }
2005
+ );
2006
+ }
2007
+ const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(
2008
+ transferInstructionCid,
2009
+ registryUrl
2010
+ );
2011
+ return this.createRejectTransferInstructionFromContext(
2012
+ transferInstructionCid,
2013
+ choiceContext
2014
+ );
2015
+ }
2016
+ async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
2017
+ const client = this.core.getTokenStandardClient(registryUrl);
2018
+ const choiceContext = await client.post(
2019
+ "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw",
2020
+ {},
2021
+ {
2022
+ path: {
2023
+ transferInstructionId: transferInstructionCid
2024
+ }
2025
+ }
2026
+ );
2027
+ return {
2028
+ choiceContextData: choiceContext.choiceContextData,
2029
+ disclosedContracts: choiceContext.disclosedContracts
2030
+ };
2031
+ }
2032
+ async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
2033
+ try {
2034
+ const exercise = {
2035
+ templateId: coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID,
2036
+ contractId: transferInstructionCid,
2037
+ choice: "TransferInstruction_Withdraw",
2038
+ choiceArgument: {
2039
+ extraArgs: {
2040
+ context: choiceContext.choiceContextData,
2041
+ meta: { values: {} }
2042
+ }
2043
+ }
2044
+ };
2045
+ return [exercise, choiceContext.disclosedContracts];
2046
+ } catch (e) {
2047
+ this.logger.error(
2048
+ "Failed to create withdraw transfer instruction:",
2049
+ e
2050
+ );
2051
+ throw e;
2052
+ }
2053
+ }
2054
+ async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
2055
+ if (prefetchedRegistryChoiceContext) {
2056
+ return this.createWithdrawTransferInstructionFromContext(
2057
+ transferInstructionCid,
2058
+ {
2059
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
2060
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
2061
+ }
2062
+ );
2063
+ }
2064
+ const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(
2065
+ transferInstructionCid,
2066
+ registryUrl
2067
+ );
2068
+ return this.createWithdrawTransferInstructionFromContext(
2069
+ transferInstructionCid,
2070
+ choiceContext
2071
+ );
2072
+ }
2073
+ };
2074
+ var TokenStandardService = class {
2075
+ constructor(ledgerClient, scanProxyClient, logger, accessTokenProvider, isMasterUser) {
2076
+ this.ledgerClient = ledgerClient;
2077
+ this.scanProxyClient = scanProxyClient;
2078
+ this.logger = logger;
2079
+ this.accessTokenProvider = accessTokenProvider;
2080
+ this.isMasterUser = isMasterUser;
2081
+ __publicField(this, "core");
2082
+ __publicField(this, "allocation");
2083
+ __publicField(this, "transfer");
2084
+ this.core = new CoreService(
2085
+ ledgerClient,
2086
+ scanProxyClient,
2087
+ logger,
2088
+ accessTokenProvider,
2089
+ isMasterUser
2090
+ );
2091
+ this.allocation = new AllocationService(this.core, this.logger);
2092
+ this.transfer = new TransferService(this.core, this.logger);
2093
+ }
2094
+ async getTransferPreApprovalByParty(partyId) {
2095
+ const { transfer_preapproval } = await this.scanProxyClient.get(
2096
+ "/v0/scan-proxy/transfer-preapprovals/by-party/{party}",
2097
+ {
2098
+ path: {
2099
+ party: partyId
2100
+ }
2101
+ }
2102
+ );
2103
+ return transfer_preapproval;
2104
+ }
2105
+ async getFeaturedAppsByParty(partyId) {
2106
+ const { featured_app_right } = await this.scanProxyClient.get(
2107
+ "/v0/scan-proxy/featured-apps/{provider_party_id}",
2108
+ {
2109
+ path: {
2110
+ provider_party_id: partyId
2111
+ }
2112
+ }
2113
+ );
2114
+ return featured_app_right;
2115
+ }
2116
+ async getInstrumentById(registryUrl, instrumentId) {
2117
+ try {
2118
+ const params = {
2119
+ path: {
2120
+ instrumentId
2121
+ }
2122
+ };
2123
+ const client = this.core.getTokenStandardClient(registryUrl);
2124
+ return client.get(
2125
+ "/registry/metadata/v1/instruments/{instrumentId}",
2126
+ params
2127
+ );
2128
+ } catch (e) {
2129
+ this.logger.error(e);
2130
+ throw new Error(
2131
+ `Instrument id ${instrumentId} does not exist for this instrument admin.`
2132
+ );
2133
+ }
2134
+ }
2135
+ async getInstrumentAdmin(registryUrl) {
2136
+ const client = this.core.getTokenStandardClient(registryUrl);
2137
+ const info = await client.get("/registry/metadata/v1/info");
2138
+ return info.adminId;
2139
+ }
2140
+ // <T> is shape of viewValue related to queried interface.
2141
+ // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
2142
+ async listContractsByInterface(interfaceId, partyId, limit) {
2143
+ return this.core.listContractsByInterface(
2144
+ interfaceId,
2145
+ partyId,
2146
+ limit
2147
+ );
2148
+ }
2149
+ async listHoldingTransactions(partyId, afterOffset, beforeOffset) {
2150
+ try {
2151
+ this.logger.debug("Set or query offset");
2152
+ const afterOffsetOrLatest = Number(afterOffset) || (await this.ledgerClient.getWithRetry(
2153
+ "/v2/state/latest-pruned-offsets"
2154
+ )).participantPrunedUpToInclusive;
2155
+ const beforeOffsetOrLatest = Number(beforeOffset) || (await this.ledgerClient.getWithRetry("/v2/state/ledger-end")).offset;
2156
+ this.logger.debug(afterOffsetOrLatest, "Using offset");
2157
+ const updatesResponse = await this.ledgerClient.postWithRetry("/v2/updates/flats", {
2158
+ updateFormat: {
2159
+ includeTransactions: {
2160
+ eventFormat: EventFilterBySetup(
2161
+ TokenStandardTransactionInterfaces,
2162
+ {
2163
+ includeWildcard: true,
2164
+ isMasterUser: this.isMasterUser,
2165
+ partyId
2166
+ }
2167
+ ),
2168
+ transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
2169
+ }
2170
+ },
2171
+ beginExclusive: afterOffsetOrLatest,
2172
+ endInclusive: beforeOffsetOrLatest,
2173
+ verbose: false
2174
+ });
2175
+ return this.core.toPrettyTransactions(
2176
+ updatesResponse,
2177
+ partyId,
2178
+ this.ledgerClient
2179
+ );
2180
+ } catch (err) {
2181
+ this.logger.error("Failed to list holding transactions.", err);
2182
+ throw err;
2183
+ }
2184
+ }
2185
+ async getTransactionById(updateId, partyId) {
2186
+ const transactionFormat = {
2187
+ eventFormat: EventFilterBySetup(
2188
+ TokenStandardTransactionInterfaces,
2189
+ {
2190
+ includeWildcard: true,
2191
+ isMasterUser: this.isMasterUser,
2192
+ partyId
2193
+ }
2194
+ ),
2195
+ transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
2196
+ };
2197
+ const getTransactionResponse = await this.ledgerClient.postWithRetry(
2198
+ "/v2/updates/transaction-by-id",
2199
+ {
2200
+ updateId,
2201
+ transactionFormat
2202
+ }
2203
+ );
2204
+ return this.core.toPrettyTransaction(
2205
+ getTransactionResponse,
2206
+ partyId,
2207
+ this.ledgerClient
2208
+ );
2209
+ }
2210
+ async getInputHoldingsCids(sender, inputUtxos) {
2211
+ return this.core.getInputHoldingsCids(sender, inputUtxos);
2212
+ }
2213
+ async createDelegateProxyTranfser(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, featuredAppRightCid, proxyCid, beneficiaries, inputUtxos, memo, expiryDate, meta) {
2214
+ const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(
2215
+ sender,
2216
+ receiver,
2217
+ amount,
2218
+ instrumentAdmin,
2219
+ instrumentId,
2220
+ registryUrl,
2221
+ inputUtxos,
2222
+ memo,
2223
+ expiryDate,
2224
+ meta
2225
+ );
2226
+ const sumOfWeights = beneficiaries.reduce(
2227
+ (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
2228
+ 0
2229
+ );
2230
+ if (sumOfWeights > 1) {
2231
+ throw new Error("Sum of beneficiary weights is larger than 1.");
2232
+ }
2233
+ const choiceArgs = {
2234
+ cid: transferCommand.contractId,
2235
+ proxyArg: {
2236
+ featuredAppRightCid,
2237
+ beneficiaries,
2238
+ choiceArg: transferCommand.choiceArgument
2239
+ }
2240
+ };
2241
+ const exercise = {
2242
+ templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
2243
+ contractId: proxyCid,
2244
+ choice: "DelegateProxy_TransferFactory_Transfer",
2245
+ choiceArgument: choiceArgs
2246
+ };
2247
+ return [exercise, disclosedContracts];
2248
+ }
2249
+ // TODO(#583) as it's not a part of token standard, should be moved somewhere else
2250
+ async createTap(receiver, amount, instrumentAdmin, instrumentId, registryUrl) {
2251
+ const now = /* @__PURE__ */ new Date();
2252
+ const tomorrow = new Date(now);
2253
+ tomorrow.setDate(tomorrow.getDate() + 1);
2254
+ const choiceArgs = {
2255
+ expectedAdmin: instrumentAdmin,
2256
+ transfer: {
2257
+ sender: instrumentAdmin,
2258
+ receiver,
2259
+ amount,
2260
+ instrumentId: { admin: instrumentAdmin, id: instrumentId },
2261
+ lock: null,
2262
+ requestedAt: new Date(
2263
+ Date.now() - REQUESTED_AT_SKEW_MS
2264
+ ).toISOString(),
2265
+ executeBefore: tomorrow.toISOString(),
2266
+ inputHoldingCids: [],
2267
+ meta: { values: {} }
2268
+ },
2269
+ extraArgs: {
2270
+ context: { values: {} },
2271
+ meta: { values: {} }
2272
+ }
2273
+ };
2274
+ const transferFactory = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
2275
+ choiceArguments: choiceArgs
2276
+ });
2277
+ const disclosedContracts = transferFactory.choiceContext.disclosedContracts;
2278
+ const amuletRules = await this.scanProxyClient.getAmuletRules();
2279
+ if (!amuletRules) {
2280
+ throw new Error("AmuletRules contract not found");
2281
+ }
2282
+ const latestOpenMiningRound = await this.scanProxyClient.getActiveOpenMiningRound();
2283
+ if (!latestOpenMiningRound) {
2284
+ throw new Error(
2285
+ "OpenMiningRound active at current moment not found"
2286
+ );
2287
+ }
2288
+ return [
2289
+ {
2290
+ templateId: amuletRules.template_id,
2291
+ contractId: amuletRules.contract_id,
2292
+ choice: "AmuletRules_DevNet_Tap",
2293
+ choiceArgument: {
2294
+ receiver,
2295
+ amount,
2296
+ openRound: latestOpenMiningRound.contract_id
2297
+ }
2298
+ },
2299
+ disclosedContracts
2300
+ ];
2301
+ }
2302
+ async selfGrantFeatureAppRight(providerPartyId, synchronizerId) {
2303
+ const amuletRules = await this.scanProxyClient.getAmuletRules();
2304
+ const disclosedContracts = {
2305
+ templateId: amuletRules.template_id,
2306
+ contractId: amuletRules.contract_id,
2307
+ createdEventBlob: amuletRules.created_event_blob,
2308
+ synchronizerId
2309
+ };
2310
+ return [
2311
+ {
2312
+ templateId: amuletRules.template_id,
2313
+ contractId: amuletRules.contract_id,
2314
+ choice: "AmuletRules_DevNet_FeatureApp",
2315
+ choiceArgument: {
2316
+ provider: providerPartyId
2317
+ }
2318
+ },
2319
+ [disclosedContracts]
2320
+ ];
2321
+ }
2322
+ async cancelTransferPreapproval(contractId, templateId, actor) {
2323
+ const exercise = {
2324
+ templateId,
2325
+ contractId,
2326
+ choice: "TransferPreapproval_Cancel",
2327
+ choiceArgument: { p: actor }
2328
+ };
2329
+ return [exercise, []];
2330
+ }
2331
+ async renewTransferPreapproval(contractId, templateId, provider, synchronizerId, newExpiresAt, inputUtxos) {
2332
+ const amuletRules = await this.scanProxyClient.getAmuletRules();
2333
+ const activeRound = await this.scanProxyClient.getActiveOpenMiningRound();
2334
+ if (!amuletRules) {
2335
+ throw new Error("AmuletRules contract not found");
2336
+ }
2337
+ if (!activeRound) {
2338
+ throw new Error(
2339
+ "OpenMiningRound active at current moment not found"
2340
+ );
2341
+ }
2342
+ const disclosed = [
2343
+ {
2344
+ templateId: amuletRules.template_id,
2345
+ contractId: amuletRules.contract_id,
2346
+ createdEventBlob: amuletRules.created_event_blob,
2347
+ synchronizerId
2348
+ },
2349
+ {
2350
+ templateId: activeRound.template_id,
2351
+ contractId: activeRound.contract_id,
2352
+ createdEventBlob: activeRound.created_event_blob,
2353
+ synchronizerId
2354
+ }
2355
+ ];
2356
+ const inputHoldings = await this.core.getInputHoldingsCids(
2357
+ provider,
2358
+ inputUtxos
2359
+ );
2360
+ const context = {
2361
+ context: {
2362
+ openMiningRound: activeRound.contract_id,
2363
+ issuingMiningRounds: [],
2364
+ validatorRights: [],
2365
+ featuredAppRight: null
2366
+ },
2367
+ amuletRules: amuletRules.contract_id
2368
+ };
2369
+ const effectiveNewExpiresAt = newExpiresAt ?? new Date(Date.now() + 90 * 24 * 3600 * 1e3);
2370
+ const exercise = {
2371
+ templateId,
2372
+ contractId,
2373
+ choice: "TransferPreapproval_Renew",
2374
+ choiceArgument: {
2375
+ context,
2376
+ inputs: inputHoldings.map((cid) => ({
2377
+ tag: "InputAmulet",
2378
+ value: cid
2379
+ })),
2380
+ newExpiresAt: effectiveNewExpiresAt.toISOString()
2381
+ }
2382
+ };
2383
+ return [exercise, disclosed];
2384
+ }
2385
+ async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
2386
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(
2387
+ transferInstructionCid,
2388
+ registryUrl
2389
+ );
2390
+ const choiceArgs = {
2391
+ cid: acceptTransferInstructionContext.contractId,
2392
+ proxyArg: {
2393
+ featuredAppRightCid,
2394
+ beneficiaries: [
2395
+ {
2396
+ beneficiary: exchangeParty,
2397
+ weight: 1
2398
+ }
2399
+ ],
2400
+ choiceArg: acceptTransferInstructionContext.choiceArgument
2401
+ }
2402
+ };
2403
+ return [
2404
+ {
2405
+ templateId: "#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy",
2406
+ contractId: proxyCid,
2407
+ choice: "DelegateProxy_TransferInstruction_Accept",
2408
+ choiceArgument: choiceArgs
2409
+ },
2410
+ disclosedContracts
2411
+ ];
2412
+ }
2413
+ };
2414
+
2415
+ // src/acs/acs-container.ts
2416
+ var ACS_UPDATE_CONFIG = {
2417
+ // How many events do we accumulate before we prune (compact) the ACS history - set to 0 to enable to compact all events, which is more efficient as long as application always ask for increasing (or equal) offsets
2418
+ maxEventsBeforePrune: 150,
2419
+ // When we compact the ACS history, we keep all events within this offset delta of the last seen update offset - set 0 to allow to compact everything
2420
+ safeOffsetDeltaForPrune: 200,
2421
+ // How many updates do we fetch at once when fetching updates - if there are more updates, we will fetch again until we have caught up (returned data is always complete to the requested endInclusive offset - even if that means multiple fetches)
2422
+ maxUpdatesToFetch: 100,
2423
+ // Timeout for receiving the first element from the WebSocket stream when reading the ACS - if this timeout is reached before the first element is returned, we fall back to HTTP
2424
+ // lower values will make the UI more responsive in case of problems, but may lead to unnecessary fallbacks
2425
+ wsTimeoutBeforeFirstElement: 1e4
2426
+ };
2427
+ if (typeof window !== "undefined") {
2428
+ window["ACS_UPDATE_CONFIG"] = ACS_UPDATE_CONFIG;
2429
+ }
2430
+ var ACSContainer = class _ACSContainer {
2431
+ constructor(orginalContainer = null, settings = { includeCreatedEventBlob: true }) {
2432
+ __publicField(this, "acsSet", null);
2433
+ __publicField(this, "settings");
2434
+ this.acsSet = orginalContainer ? orginalContainer.acsSet : null;
2435
+ this.settings = settings;
2436
+ }
2437
+ async update(offset, key, api, wsSupport) {
2438
+ if (this.acsSet === null) {
2439
+ const acs = await this.readACS(offset, key, api, wsSupport);
2440
+ this.acsSet = acs;
2441
+ return _ACSContainer.calculateAt(acs, offset);
2442
+ }
2443
+ if (this.acsSet.acsOffset > offset) {
2444
+ this.acsSet = null;
2445
+ return this.update(offset, key, api);
2446
+ }
2447
+ if (this.acsSet.updates.length >= ACS_UPDATE_CONFIG.maxEventsBeforePrune) {
2448
+ this.acsSet = await _ACSContainer.compact(this.acsSet);
2449
+ }
2450
+ const updates = await _ACSContainer.updateContracts(
2451
+ this.acsSet.lastUpdateOffset,
2452
+ offset,
2453
+ this.createEventFormat(key),
2454
+ api
2455
+ );
2456
+ const [newEvents, newOffset] = _ACSContainer.extractEvents(
2457
+ this.acsSet.lastUpdateOffset,
2458
+ updates
2459
+ );
2460
+ if (newOffset > this.acsSet.lastUpdateOffset) {
2461
+ this.acsSet = {
2462
+ ...this.acsSet,
2463
+ lastUpdateOffset: newOffset,
2464
+ updates: this.acsSet.updates.concat(newEvents)
2465
+ };
2466
+ }
2467
+ if (updates.length >= ACS_UPDATE_CONFIG.maxUpdatesToFetch) {
2468
+ return this.update(offset, key, api);
2469
+ }
2470
+ this.acsSet = {
2471
+ ...this.acsSet,
2472
+ lastUpdateOffset: offset
2473
+ // we have caught up
2474
+ };
2475
+ return _ACSContainer.calculateAt(this.acsSet, offset);
2476
+ }
2477
+ static calculateAt(acs, offset) {
2478
+ if (acs.acsOffset > offset) {
2479
+ return Promise.reject(
2480
+ Error(
2481
+ // This should never happen as we check this before calling calculateAt
2482
+ `Cannot calculate ACS at offset ${offset} when initial ACS is at ${acs.acsOffset}`
2483
+ )
2484
+ );
2485
+ }
2486
+ const addedContracts = [];
2487
+ const removedContractIds = /* @__PURE__ */ new Set();
2488
+ acs.updates.forEach((update) => {
2489
+ if (update.offset <= offset) {
2490
+ if (update.created) {
2491
+ const createdEv = update.created;
2492
+ const activeContract = {
2493
+ workflowId: update.workflowId ?? "",
2494
+ contractEntry: {
2495
+ JsActiveContract: {
2496
+ createdEvent: createdEv,
2497
+ synchronizerId: update.synchronizerId ?? "",
2498
+ reassignmentCounter: 0
2499
+ }
2500
+ }
2501
+ };
2502
+ addedContracts.push(activeContract);
2503
+ } else if (update.archivedContractId) {
2504
+ removedContractIds.add(update.archivedContractId);
2505
+ }
2506
+ }
2507
+ });
2508
+ const createdContracts = acs.initialAcs.concat(addedContracts);
2509
+ const result = createdContracts.filter(
2510
+ (contract) => !removedContractIds.has(
2511
+ contract.contractEntry.JsActiveContract?.createdEvent.contractId ?? ""
2512
+ )
2513
+ );
2514
+ return Promise.resolve(result);
2515
+ }
2516
+ static extractEvents(fromOffset, updates) {
2517
+ const newEvents = [];
2518
+ let newOffset = fromOffset;
2519
+ updates.forEach((update) => {
2520
+ if ("Transaction" in update.update) {
2521
+ const transaction = update.update.Transaction;
2522
+ const trOffset = transaction.value.offset;
2523
+ if (trOffset > newOffset) {
2524
+ const events = transaction.value.events ?? [];
2525
+ events.forEach((event) => {
2526
+ if ("CreatedEvent" in event) {
2527
+ const acUpdate = {
2528
+ created: event.CreatedEvent,
2529
+ archivedContractId: null,
2530
+ offset: trOffset,
2531
+ workflowId: transaction.value.workflowId,
2532
+ synchronizerId: transaction.value.synchronizerId
2533
+ };
2534
+ newEvents.push(acUpdate);
2535
+ newOffset = trOffset;
2536
+ } else if ("ArchivedEvent" in event) {
2537
+ const archivedEvent = event.ArchivedEvent;
2538
+ const acUpdate = {
2539
+ created: null,
2540
+ archivedContractId: archivedEvent.contractId,
2541
+ offset: trOffset,
2542
+ workflowId: transaction.value.workflowId,
2543
+ synchronizerId: transaction.value.synchronizerId
2544
+ };
2545
+ newEvents.push(acUpdate);
2546
+ newOffset = trOffset;
2547
+ }
2548
+ });
2549
+ }
2550
+ } else if ("OffsetCheckpoint" in update.update) {
2551
+ const checkpoint = update.update.OffsetCheckpoint;
2552
+ newOffset = checkpoint.value.offset;
2553
+ } else {
2554
+ console.log(
2555
+ `ACS Update got unknown update type: ${JSON.stringify(update.update)}`
2556
+ );
2557
+ }
2558
+ });
2559
+ return [newEvents, newOffset];
2560
+ }
2561
+ static async updateContracts(startOffset, endOffset, eventFormat, api) {
2562
+ const request = {
2563
+ beginExclusive: startOffset,
2564
+ endInclusive: endOffset,
2565
+ updateFormat: {
2566
+ includeTransactions: {
2567
+ eventFormat,
2568
+ transactionShape: "TRANSACTION_SHAPE_ACS_DELTA"
2569
+ }
2570
+ },
2571
+ verbose: false
2572
+ };
2573
+ const params = {
2574
+ query: {
2575
+ limit: ACS_UPDATE_CONFIG.maxUpdatesToFetch,
2576
+ stream_idle_timeout_ms: 1e3
2577
+ }
2578
+ };
2579
+ return api.postWithRetry(
2580
+ "/v2/updates/flats",
2581
+ request,
2582
+ defaultRetryableOptions,
2583
+ params
2584
+ );
2585
+ }
2586
+ static async compact(acs) {
2587
+ const newAcsOffset = Math.max(
2588
+ acs.acsOffset,
2589
+ acs.lastUpdateOffset - ACS_UPDATE_CONFIG.safeOffsetDeltaForPrune
2590
+ );
2591
+ if (newAcsOffset > acs.acsOffset) {
2592
+ const responses = await _ACSContainer.calculateAt(acs, newAcsOffset);
2593
+ return {
2594
+ acsOffset: newAcsOffset,
2595
+ initialAcs: responses,
2596
+ lastUpdateOffset: acs.lastUpdateOffset,
2597
+ updates: acs.updates.filter(
2598
+ (update) => update.offset > newAcsOffset
2599
+ )
2600
+ };
2601
+ }
2602
+ return acs;
2603
+ }
2604
+ async readACS(offset, key, api, wsSupport) {
2605
+ if (wsSupport && wsSupport.enabled()) {
2606
+ return this.readACSUsingWs(offset, key, wsSupport).catch(() => {
2607
+ console.log("Falling back to HTTP for ACS read");
2608
+ return this.readHttpACS(offset, key, api);
2609
+ });
2610
+ }
2611
+ return this.readHttpACS(offset, key, api);
2612
+ }
2613
+ async readHttpACS(offset, key, api) {
2614
+ const format = this.createEventFormat(key);
2615
+ const acs = await api.postWithRetry("/v2/state/active-contracts", {
2616
+ activeAtOffset: offset,
2617
+ verbose: false,
2618
+ eventFormat: format
2619
+ });
2620
+ return {
2621
+ acsOffset: offset,
2622
+ initialAcs: acs,
2623
+ lastUpdateOffset: offset,
2624
+ updates: []
2625
+ };
2626
+ }
2627
+ readACSUsingWs(offset, key, wsSupport) {
2628
+ const wsACSURL = `${wsSupport.baseUrl}/v2/state/active-contracts`;
2629
+ const format = this.createEventFormat(key);
2630
+ const request = {
2631
+ activeAtOffset: offset,
2632
+ verbose: false,
2633
+ eventFormat: format
2634
+ };
2635
+ return new Promise((resolve, reject) => {
2636
+ const ws = new WebSocket(wsACSURL, wsSupport.extractProtocols());
2637
+ const results = [];
2638
+ let finished = false;
2639
+ let error = null;
2640
+ setTimeout(() => {
2641
+ if (!finished && !error && results.length === 0) {
2642
+ error = Error(
2643
+ `No data received from WebSocket ${wsACSURL} within ${ACS_UPDATE_CONFIG.wsTimeoutBeforeFirstElement}ms`
2644
+ );
2645
+ wsSupport.reportError(error);
2646
+ reject(error);
2647
+ ws.close();
2648
+ }
2649
+ }, ACS_UPDATE_CONFIG.wsTimeoutBeforeFirstElement);
2650
+ ws.onopen = () => {
2651
+ ws.send(JSON.stringify(request));
2652
+ };
2653
+ ws.onmessage = (event) => {
2654
+ try {
2655
+ const data = JSON.parse(
2656
+ event.data
2657
+ );
2658
+ results.push(data);
2659
+ } catch (err) {
2660
+ console.error("Invalid JSON:", err);
2661
+ }
2662
+ };
2663
+ ws.onerror = () => {
2664
+ error = new Error("WebSocket error");
2665
+ wsSupport.reportError(error);
2666
+ reject(error);
2667
+ };
2668
+ ws.onclose = () => {
2669
+ finished = true;
2670
+ if (!error) {
2671
+ wsSupport.reportSuccess();
2672
+ resolve({
2673
+ acsOffset: offset,
2674
+ initialAcs: results,
2675
+ lastUpdateOffset: offset,
2676
+ updates: []
2677
+ });
2678
+ }
2679
+ };
2680
+ });
2681
+ }
2682
+ createInterfaceFilter(interfaceId) {
2683
+ return {
2684
+ cumulative: [
2685
+ {
2686
+ identifierFilter: {
2687
+ InterfaceFilter: {
2688
+ value: {
2689
+ interfaceId,
2690
+ includeInterfaceView: true,
2691
+ includeCreatedEventBlob: this.settings.includeCreatedEventBlob
2692
+ }
2693
+ }
2694
+ }
2695
+ }
2696
+ ]
2697
+ };
2698
+ }
2699
+ createTemplateFilter(templateId) {
2700
+ return {
2701
+ cumulative: [
2702
+ {
2703
+ identifierFilter: {
2704
+ TemplateFilter: {
2705
+ value: {
2706
+ templateId,
2707
+ includeCreatedEventBlob: this.settings.includeCreatedEventBlob
2708
+ }
2709
+ }
2710
+ }
2711
+ }
2712
+ ]
2713
+ };
2714
+ }
2715
+ createEventFormat(key) {
2716
+ const cumulativeFilter = key.templateId ? this.createTemplateFilter(key.templateId) : this.createInterfaceFilter(key.interfaceId ?? "");
2717
+ const baseFormat = {
2718
+ filtersByParty: {},
2719
+ verbose: false
2720
+ };
2721
+ if (key.party) {
2722
+ if (!key.interfaceId && !key.templateId) {
2723
+ baseFormat.filtersByParty[key.party] = {};
2724
+ return baseFormat;
2725
+ }
2726
+ baseFormat.filtersByParty[key.party] = cumulativeFilter;
2727
+ return baseFormat;
2728
+ }
2729
+ return {
2730
+ ...baseFormat,
2731
+ filtersForAnyParty: cumulativeFilter
2732
+ };
2733
+ }
2734
+ };
2735
+
2736
+ // src/acs/acs-helper.ts
2737
+ var DEFAULT_MAX_CACHE_SIZE = 50;
2738
+ var DEFAULT_ENTRY_EXPIRATION_TIME = 10 * 60 * 1e3;
2739
+ var ACSHelper = class _ACSHelper {
2740
+ constructor(apiInstance, _logger, options) {
2741
+ __publicField(this, "contractsSet");
2742
+ __publicField(this, "apiInstance");
2743
+ __publicField(this, "wsSupport");
2744
+ __publicField(this, "logger");
2745
+ __publicField(this, "includeCreatedEventBlob");
2746
+ __publicField(this, "hits", 0);
2747
+ __publicField(this, "misses", 0);
2748
+ __publicField(this, "evictions", 0);
2749
+ __publicField(this, "totalLookuptime", 0);
2750
+ __publicField(this, "totalCacheServeTime", 0);
2751
+ this.contractsSet = new typescriptLruCache.LRUCache({
2752
+ maxSize: options?.maxCacheSize ?? DEFAULT_MAX_CACHE_SIZE,
2753
+ entryExpirationTimeInMS: options?.entryExpirationTime ?? DEFAULT_ENTRY_EXPIRATION_TIME,
2754
+ // 10 minutes
2755
+ onEntryEvicted: (entry) => {
2756
+ this.logger.debug(
2757
+ `entry ${entry.key} isExpired = ${entry.isExpired}. evicting entry.`
2758
+ );
2759
+ this.evictions++;
2760
+ }
2761
+ });
2762
+ this.apiInstance = apiInstance;
2763
+ this.wsSupport = options?.wsSupport;
2764
+ this.logger = _logger.child({ component: "ACSHelper" });
2765
+ this.includeCreatedEventBlob = options?.includeCreatedEventBlob ?? true;
2766
+ }
2767
+ getCacheStats() {
2768
+ const totalCalls = this.hits + this.misses;
2769
+ const hitRate = totalCalls ? this.hits / totalCalls * 100 : 0;
2770
+ const avgLookupTime = totalCalls > 0 ? this.totalLookuptime / totalCalls : 0;
2771
+ return {
2772
+ totalCalls,
2773
+ hits: this.hits,
2774
+ misses: this.misses,
2775
+ evictions: this.evictions,
2776
+ cacheSize: this.contractsSet.size,
2777
+ hitRate: hitRate.toFixed(2) + "%",
2778
+ averageLookupTime: avgLookupTime.toFixed(3) + " ms",
2779
+ cacheServeTime: this.totalCacheServeTime.toFixed(3)
2780
+ };
2781
+ }
2782
+ static createKey(party, templateId, interfaceId) {
2783
+ return { party, templateId, interfaceId };
2784
+ }
2785
+ static keyToString(key) {
2786
+ return `${key.party ? key.party : "ANY"}_T:${key.templateId ?? "()"}_I:${key.interfaceId ?? "()"}`;
2787
+ }
2788
+ findACSContainer(key) {
2789
+ const keyStr = _ACSHelper.keyToString(key);
2790
+ const start = performance.now();
2791
+ const existing = this.contractsSet.get(keyStr);
2792
+ const end = performance.now();
2793
+ this.totalLookuptime += end - start;
2794
+ if (existing) {
2795
+ this.hits++;
2796
+ this.logger.debug("cache hit");
2797
+ return existing;
2798
+ }
2799
+ this.logger.debug("cache miss");
2800
+ this.misses++;
2801
+ const newContainer = new ACSContainer(void 0, {
2802
+ includeCreatedEventBlob: this.includeCreatedEventBlob
2803
+ });
2804
+ this.contractsSet.set(keyStr, newContainer);
2805
+ return newContainer;
2806
+ }
2807
+ async activeContractsForTemplate(offset, partyFilter, templateId) {
2808
+ const key = _ACSHelper.createKey(partyFilter, templateId, void 0);
2809
+ const start = performance.now();
2810
+ const container = this.findACSContainer(key);
2811
+ const result = container.update(
2812
+ offset,
2813
+ key,
2814
+ this.apiInstance,
2815
+ this.wsSupport
2816
+ );
2817
+ const end = performance.now();
2818
+ if (this.contractsSet.has(_ACSHelper.keyToString(key))) {
2819
+ this.totalCacheServeTime += end - start;
2820
+ }
2821
+ return result;
2822
+ }
2823
+ async activeContractsForInterface(offset, partyFilter, interfaceId) {
2824
+ const key = _ACSHelper.createKey(partyFilter, void 0, interfaceId);
2825
+ const start = performance.now();
2826
+ const container = this.findACSContainer(key);
2827
+ const result = container.update(
2828
+ offset,
2829
+ key,
2830
+ this.apiInstance,
2831
+ this.wsSupport
2832
+ );
2833
+ const end = performance.now();
2834
+ if (this.contractsSet.has(_ACSHelper.keyToString(key))) {
2835
+ this.totalCacheServeTime += end - start;
2836
+ }
2837
+ return result;
2838
+ }
2839
+ };
2840
+
2841
+ // src/ledger-client.ts
2842
+ var supportedVersions = ["3.3", "3.4"];
2843
+ var LedgerClient = class {
2844
+ constructor(baseUrl, _logger, isAdmin = false, accessToken, accessTokenProvider, version, acsHelperOptions) {
2845
+ // privately manage the active connected version and associated client codegen
2846
+ __publicField(this, "clients");
2847
+ __publicField(this, "clientVersion", "3.3");
2848
+ // default to 3.3 if not provided
2849
+ __publicField(this, "currentClient");
2850
+ __publicField(this, "initialized", false);
2851
+ __publicField(this, "accessTokenProvider");
2852
+ __publicField(this, "acsHelper");
2853
+ __publicField(this, "logger");
2854
+ this.logger = _logger.child({ component: "LedgerClient" });
2855
+ this.accessTokenProvider = accessTokenProvider;
2856
+ this.clients = {
2857
+ "3.3": createClient__default.default({
2858
+ baseUrl: baseUrl.href,
2859
+ fetch: async (url, options = {}) => {
2860
+ if (this.accessTokenProvider) {
2861
+ accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
2862
+ }
2863
+ return fetch(url, {
2864
+ ...options,
2865
+ headers: {
2866
+ ...options.headers || {},
2867
+ Authorization: `Bearer ${accessToken}`
2868
+ }
2869
+ });
2870
+ }
2871
+ }),
2872
+ "3.4": createClient__default.default({
2873
+ baseUrl: baseUrl.href,
2874
+ fetch: async (url, options = {}) => {
2875
+ if (this.accessTokenProvider) {
2876
+ accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
2877
+ }
2878
+ return fetch(url, {
2879
+ ...options,
2880
+ headers: {
2881
+ ...options.headers || {},
2882
+ Authorization: `Bearer ${accessToken}`
2883
+ }
2884
+ });
2885
+ }
2886
+ })
2887
+ };
2888
+ this.clientVersion = version ?? this.clientVersion;
2889
+ this.currentClient = this.clients[this.clientVersion];
2890
+ this.acsHelper = new ACSHelper(this, _logger, acsHelperOptions);
2891
+ }
2892
+ async init() {
2893
+ if (!this.initialized) {
2894
+ const versionFromClient = await this.currentClient.GET("/v2/version");
2895
+ this.clientVersion = this.parseSupportedVersions(
2896
+ versionFromClient.data?.version
2897
+ );
2898
+ this.initialized = true;
2899
+ }
2900
+ }
2901
+ getCurrentClientVersion() {
2902
+ return this.clientVersion;
2903
+ }
2904
+ parseSupportedVersions(version) {
2905
+ if (!version) {
2906
+ throw new Error("Client version missing from response");
2907
+ }
2908
+ const match = supportedVersions.find((v) => version.startsWith(v));
2909
+ if (!match) {
2910
+ throw new Error(`Unsupported version - found ${version}`);
2911
+ }
2912
+ return match;
2913
+ }
2914
+ /**
2915
+ * Check if a party exists
2916
+ *
2917
+ * @param partyId The ID of the party to look for
2918
+ * @returns A promise to resolves to a boolean.
2919
+ */
2920
+ async checkIfPartyExists(partyId) {
2921
+ try {
2922
+ const party = await this.get("/v2/parties/{party}", {
2923
+ path: { party: partyId }
2924
+ });
2925
+ return party.partyDetails !== void 0 && party.partyDetails[0].party === partyId;
2926
+ } catch {
2927
+ return false;
2928
+ }
2929
+ }
2930
+ /**
2931
+ * grant "Master User" rights to a user.
2932
+ *
2933
+ * this require running with an admin token.
2934
+ *
2935
+ * @param userId The ID of the user to grant rights to.
2936
+ * @param canReadAsAnyParty define if the user can read as any party.
2937
+ * @param canExecuteAsAnyParty define if the user can execute as any party.
2938
+ */
2939
+ async grantMasterUserRights(userId, canReadAsAnyParty, canExecuteAsAnyParty) {
2940
+ const rights = [];
2941
+ if (canReadAsAnyParty) {
2942
+ rights.push({
2943
+ kind: {
2944
+ CanReadAsAnyParty: { value: {} }
2945
+ }
2946
+ });
2947
+ }
2948
+ if (canExecuteAsAnyParty) {
2949
+ rights.push({
2950
+ kind: {
2951
+ CanExecuteAsAnyParty: {
2952
+ value: {}
2953
+ }
2954
+ }
2955
+ });
2956
+ }
2957
+ const result = await this.post(
2958
+ "/v2/users/{user-id}/rights",
2959
+ {
2960
+ identityProviderId: "",
2961
+ userId,
2962
+ rights
2963
+ },
2964
+ {
2965
+ path: {
2966
+ "user-id": userId
2967
+ }
2968
+ }
2969
+ );
2970
+ if (!result.newlyGrantedRights) {
2971
+ throw new Error("Failed to grant user rights");
2972
+ }
2973
+ }
2974
+ /**
2975
+ * Create a new user.
2976
+ *
2977
+ * @param userId The ID of the user to create.
2978
+ * @param primaryParty The primary party of the user.
2979
+ */
2980
+ async createUser(userId, primaryParty) {
2981
+ try {
2982
+ const existing = await this.get("/v2/users/{user-id}", {
2983
+ path: { "user-id": userId }
2984
+ });
2985
+ if (existing && existing.user) {
2986
+ return existing.user;
2987
+ }
2988
+ } catch {
2989
+ }
2990
+ return (await this.post("/v2/users", {
2991
+ user: {
2992
+ identityProviderId: "",
2993
+ id: userId,
2994
+ isDeactivated: false,
2995
+ primaryParty
2996
+ },
2997
+ rights: [
2998
+ {
2999
+ kind: {
3000
+ ParticipantAdmin: {
3001
+ value: {}
3002
+ }
3003
+ }
3004
+ }
3005
+ ]
3006
+ })).user;
3007
+ }
3008
+ /**
3009
+ * Grants a user the right to act as a party, while ensuring the party exists.
3010
+ *
3011
+ * @param userId The ID of the user to grant rights to.
3012
+ * @param partyId The ID of the party to grant rights for.
3013
+ * @returns A promise that resolves when the rights have been granted.
3014
+ */
3015
+ async waitForPartyAndGrantUserRights(userId, partyId) {
3016
+ await this.init();
3017
+ let partyFound = false;
3018
+ let tries = 0;
3019
+ const maxTries = 30;
3020
+ while (!partyFound && tries < maxTries) {
3021
+ partyFound = await this.checkIfPartyExists(partyId);
3022
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
3023
+ tries++;
3024
+ }
3025
+ if (tries >= maxTries) {
3026
+ throw new Error("timed out waiting for new party to appear");
3027
+ }
3028
+ const result = await this.grantRights(userId, {
3029
+ actAs: [partyId]
3030
+ });
3031
+ if (!result.newlyGrantedRights) {
3032
+ throw new Error("Failed to grant user rights");
3033
+ }
3034
+ return;
3035
+ }
3036
+ async grantRights(userId, userRightsOptions) {
3037
+ await this.init();
3038
+ const rights = [];
3039
+ for (const partyId of userRightsOptions.readAs ?? []) {
3040
+ rights.push({
3041
+ kind: {
3042
+ CanReadAs: {
3043
+ value: {
3044
+ party: partyId
3045
+ }
3046
+ }
3047
+ }
3048
+ });
3049
+ }
3050
+ for (const partyId of userRightsOptions.actAs ?? []) {
3051
+ rights.push({
3052
+ kind: {
3053
+ CanActAs: {
3054
+ value: {
3055
+ party: partyId
3056
+ }
3057
+ }
3058
+ }
3059
+ });
3060
+ }
3061
+ if (userRightsOptions.canReadAsAnyParty) {
3062
+ rights.push({
3063
+ kind: {
3064
+ CanReadAsAnyParty: { value: {} }
3065
+ }
3066
+ });
3067
+ }
3068
+ if (userRightsOptions.canExecuteAsAnyParty) {
3069
+ rights.push({
3070
+ kind: {
3071
+ CanExecuteAsAnyParty: {
3072
+ value: {}
3073
+ }
3074
+ }
3075
+ });
3076
+ }
3077
+ const result = await this.post(
3078
+ "/v2/users/{user-id}/rights",
3079
+ {
3080
+ identityProviderId: "",
3081
+ userId,
3082
+ rights
3083
+ },
3084
+ {
3085
+ path: {
3086
+ "user-id": userId
3087
+ }
3088
+ }
3089
+ );
3090
+ if (!result.newlyGrantedRights) {
3091
+ throw new Error("Failed to grant user rights");
3092
+ }
3093
+ return result;
3094
+ }
3095
+ /** TODO: simplify once 3.4 snapshot contains this endpoint */
3096
+ async allocateExternalParty(synchronizerId, onboardingTransactions, multiHashSignatures) {
3097
+ await this.init();
3098
+ if (this.clientVersion !== "3.3") {
3099
+ throw new Error(
3100
+ "allocateExternalParty is only supported on 3.3 clients"
3101
+ );
3102
+ }
3103
+ const client = this.clients["3.3"];
3104
+ const resp = await client.POST("/v2/parties/external/allocate", {
3105
+ body: {
3106
+ synchronizer: synchronizerId,
3107
+ identityProviderId: "",
3108
+ onboardingTransactions,
3109
+ multiHashSignatures
3110
+ }
3111
+ });
3112
+ return this.valueOrError(resp);
3113
+ }
3114
+ /** TODO: simplify once 3.4 snapshot contains this endpoint */
3115
+ async generateTopology(synchronizerId, publicKey, partyHint, localParticipantObservationOnly = false, confirmationThreshold = 1, otherConfirmingParticipantUids = [], observingParticipantUids = []) {
3116
+ await this.init();
3117
+ if (this.clientVersion !== "3.3") {
3118
+ throw new Error(
3119
+ "allocateExternalParty is only supported on 3.3 clients"
3120
+ );
3121
+ }
3122
+ const client = this.clients["3.3"];
3123
+ const body = {
3124
+ synchronizer: synchronizerId,
3125
+ partyHint,
3126
+ publicKey: {
3127
+ format: "CRYPTO_KEY_FORMAT_RAW",
3128
+ keyData: publicKey,
3129
+ keySpec: "SIGNING_KEY_SPEC_EC_CURVE25519"
3130
+ },
3131
+ localParticipantObservationOnly,
3132
+ confirmationThreshold,
3133
+ otherConfirmingParticipantUids,
3134
+ observingParticipantUids
3135
+ };
3136
+ this.logger.debug(body, "generateTopology request body");
3137
+ const resp = await client.POST(
3138
+ "/v2/parties/external/generate-topology",
3139
+ { body }
3140
+ );
3141
+ return this.valueOrError(resp);
3142
+ }
3143
+ async activeContracts(options) {
3144
+ const { offset, templateIds, parties, filterByParty } = options;
3145
+ this.logger.debug(options, "options for active contracts");
3146
+ if (templateIds?.length === 1 && parties?.length === 1) {
3147
+ const party = parties[0];
3148
+ const templateId = templateIds[0];
3149
+ return this.acsHelper.activeContractsForTemplate(
3150
+ offset,
3151
+ party,
3152
+ templateId
3153
+ );
3154
+ }
3155
+ if (filterByParty && !templateIds?.length && parties?.length === 1) {
3156
+ const party = parties[0];
3157
+ const r = this.acsHelper.activeContractsForInterface(
3158
+ offset,
3159
+ party,
3160
+ ""
3161
+ );
3162
+ this.logger.info(r);
3163
+ return r;
3164
+ }
3165
+ const filter = this.buildActiveContractsFilter(options);
3166
+ this.logger.debug("falling back to post request");
3167
+ return await this.postWithRetry("/v2/state/active-contracts", filter);
3168
+ }
3169
+ buildActiveContractsFilter(options) {
3170
+ const filter = {
3171
+ filter: {
3172
+ filtersByParty: {}
3173
+ },
3174
+ verbose: false,
3175
+ activeAtOffset: options?.offset
3176
+ };
3177
+ const buildTemplateFilter = (templateIds) => {
3178
+ if (!templateIds) return [];
3179
+ return [
3180
+ {
3181
+ identifierFilter: {
3182
+ TemplateFilter: {
3183
+ value: {
3184
+ templateId: templateIds[0],
3185
+ includeCreatedEventBlob: true
3186
+ //TODO: figure out if this should be configurable
3187
+ }
3188
+ }
3189
+ }
3190
+ }
3191
+ ];
3192
+ };
3193
+ if (options?.filterByParty && options.parties && options.parties.length > 0) {
3194
+ for (const party of options.parties) {
3195
+ filter.filter.filtersByParty[party] = {
3196
+ cumulative: options.templateIds ? buildTemplateFilter(options.templateIds) : []
3197
+ };
3198
+ }
3199
+ } else if (options?.templateIds) {
3200
+ filter.filter.filtersForAnyParty = {
3201
+ cumulative: buildTemplateFilter(options.templateIds)
3202
+ };
3203
+ }
3204
+ return filter;
3205
+ }
3206
+ async postWithRetry(path, body, retryOptions = defaultRetryableOptions, params, additionalOptions) {
3207
+ return await retryable(
3208
+ () => this.post(path, body, params, additionalOptions),
3209
+ retryOptions,
3210
+ this.logger
3211
+ ).catch((e) => {
3212
+ throw asJsCantonError(e);
3213
+ });
3214
+ }
3215
+ async getWithRetry(path, retryOptions = defaultRetryableOptions, params) {
3216
+ return await retryable(
3217
+ () => this.get(path, params),
3218
+ retryOptions,
3219
+ this.logger
3220
+ ).catch((e) => {
3221
+ throw asJsCantonError(e);
3222
+ });
3223
+ }
3224
+ getCacheStats() {
3225
+ return this.acsHelper.getCacheStats();
3226
+ }
3227
+ /**
3228
+ * @deprecated use postWithRetry instead, should be made private
3229
+ */
3230
+ async post(path, body, params, additionalOptions) {
3231
+ const options = { body, params, ...additionalOptions };
3232
+ const resp = await this.currentClient.POST(path, options);
3233
+ return this.valueOrError(resp);
3234
+ }
3235
+ /**
3236
+ * @deprecated use getWithRetry instead, should be made private
3237
+ */
3238
+ async get(path, params) {
3239
+ await this.init();
3240
+ const options = { params };
3241
+ const resp = await this.currentClient.GET(path, options);
3242
+ return this.valueOrError(resp);
3243
+ }
3244
+ async valueOrError(response) {
3245
+ if (response.data === void 0) {
3246
+ return Promise.reject(response.error);
3247
+ } else {
3248
+ return Promise.resolve(response.data);
3249
+ }
3250
+ }
3251
+ };
3252
+
3253
+ // src/acs/ws-support.ts
3254
+ var INITIAL_BACKOFF_MS = 1e3;
3255
+ var MAX_BACKOFF_MS = 10 * 60 * 1e3;
3256
+ var WSSupportWithBackOffSwitch = class {
3257
+ constructor(extractProtocols, baseUrl) {
3258
+ this.extractProtocols = extractProtocols;
3259
+ this.baseUrl = baseUrl;
3260
+ __publicField(this, "backOffUntil", null);
3261
+ __publicField(this, "backOffDurationMs", INITIAL_BACKOFF_MS);
3262
+ }
3263
+ enabled() {
3264
+ if (this.backOffUntil === null) {
3265
+ return true;
3266
+ }
3267
+ const now = Date.now();
3268
+ if (now >= this.backOffUntil) {
3269
+ this.backOffUntil = null;
3270
+ return true;
3271
+ }
3272
+ return false;
3273
+ }
3274
+ reportError(error) {
3275
+ console.error("WebSocket error reported:", error);
3276
+ const now = Date.now();
3277
+ if (this.backOffUntil !== null && now - this.backOffUntil < 500) {
3278
+ return;
3279
+ }
3280
+ this.backOffUntil = Date.now() + this.backOffDurationMs;
3281
+ this.backOffDurationMs = Math.min(
3282
+ this.backOffDurationMs * 1.6,
3283
+ MAX_BACKOFF_MS
3284
+ );
3285
+ }
3286
+ reportSuccess() {
3287
+ this.backOffUntil = null;
3288
+ this.backOffDurationMs = INITIAL_BACKOFF_MS;
3289
+ }
3290
+ };
3291
+
3292
+ exports.ACSContainer = ACSContainer;
3293
+ exports.ACS_UPDATE_CONFIG = ACS_UPDATE_CONFIG;
3294
+ exports.CoreService = CoreService;
3295
+ exports.LedgerClient = LedgerClient;
3296
+ exports.TokenStandardService = TokenStandardService;
3297
+ exports.TopologyWriteService = TopologyWriteService;
3298
+ exports.WSSupportWithBackOffSwitch = WSSupportWithBackOffSwitch;
3299
+ exports.asJsCantonError = asJsCantonError;
3300
+ exports.awaitCompletion = awaitCompletion;
3301
+ exports.defaultRetryableOptions = defaultRetryableOptions;
3302
+ exports.isJsCantonError = isJsCantonError;
3303
+ exports.promiseWithTimeout = promiseWithTimeout;
3304
+ exports.supportedVersions = supportedVersions;
3305
+ //# sourceMappingURL=index.cjs.map
3306
+ //# sourceMappingURL=index.cjs.map