@canton-network/core-ledger-client 0.15.0 → 0.16.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 +33 -0
  2. package/dist/acs/acs-container.d.ts.map +1 -0
  3. package/dist/acs/acs-helper.d.ts +37 -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 +3317 -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 +3297 -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 +31 -3
  18. package/dist/ledger-client.d.ts.map +1 -1
  19. package/dist/token-standard-service.d.ts +10 -7
  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,3317 @@
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
+ async getActiveOpenMiningRound() {
1497
+ const openMiningRounds = await this.scanProxyClient.getOpenMiningRounds();
1498
+ if (!(Array.isArray(openMiningRounds) && openMiningRounds.length)) {
1499
+ throw new Error("OpenMiningRound contract not found");
1500
+ }
1501
+ const nowForOpenMiningRounds = Date.now();
1502
+ const latestOpenMiningRound = openMiningRounds.findLast(
1503
+ (openMiningRound) => {
1504
+ const { opensAt, targetClosesAt } = openMiningRound.payload;
1505
+ const opensAtMs = Number(new Date(opensAt));
1506
+ const targetClosesAtMs = Number(new Date(targetClosesAt));
1507
+ return opensAtMs <= nowForOpenMiningRounds && targetClosesAtMs > nowForOpenMiningRounds;
1508
+ }
1509
+ );
1510
+ return latestOpenMiningRound ?? null;
1511
+ }
1512
+ };
1513
+ var AllocationService = class {
1514
+ constructor(core, logger) {
1515
+ this.core = core;
1516
+ this.logger = logger;
1517
+ }
1518
+ async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
1519
+ const allocationSpecificationNormalized = {
1520
+ ...allocationSpecification,
1521
+ settlement: {
1522
+ ...allocationSpecification.settlement,
1523
+ meta: allocationSpecification.settlement.meta ?? { values: {} }
1524
+ },
1525
+ transferLeg: {
1526
+ ...allocationSpecification.transferLeg,
1527
+ meta: allocationSpecification.transferLeg.meta ?? {
1528
+ values: {}
1529
+ }
1530
+ }
1531
+ };
1532
+ const inputHoldingCids = await this.core.getInputHoldingsCids(
1533
+ allocationSpecificationNormalized.transferLeg.sender,
1534
+ inputUtxos
1535
+ );
1536
+ return {
1537
+ expectedAdmin,
1538
+ allocation: allocationSpecificationNormalized,
1539
+ requestedAt: requestedAt ?? new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
1540
+ inputHoldingCids,
1541
+ extraArgs: {
1542
+ context: { values: {} },
1543
+ meta: { values: {} }
1544
+ }
1545
+ };
1546
+ }
1547
+ async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs) {
1548
+ return this.core.getTokenStandardClient(registryUrl).post("/registry/allocation-instruction/v1/allocation-factory", {
1549
+ choiceArguments: choiceArgs
1550
+ });
1551
+ }
1552
+ async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
1553
+ choiceArgs.extraArgs.context = {
1554
+ ...choiceContext.choiceContextData,
1555
+ values: choiceContext.choiceContextData?.values ?? {}
1556
+ };
1557
+ const exercise = {
1558
+ templateId: coreTokenStandard.ALLOCATION_FACTORY_INTERFACE_ID,
1559
+ contractId: factoryId,
1560
+ choice: "AllocationFactory_Allocate",
1561
+ choiceArgument: choiceArgs
1562
+ };
1563
+ return [exercise, choiceContext.disclosedContracts];
1564
+ }
1565
+ async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
1566
+ const choiceArgs = await this.buildAllocationFactoryChoiceArgs(
1567
+ allocationSpecification,
1568
+ expectedAdmin,
1569
+ inputUtxos,
1570
+ requestedAt
1571
+ );
1572
+ if (prefetchedRegistryChoiceContext) {
1573
+ return this.createAllocationInstructionFromContext(
1574
+ prefetchedRegistryChoiceContext.factoryId,
1575
+ choiceArgs,
1576
+ prefetchedRegistryChoiceContext.choiceContext
1577
+ );
1578
+ }
1579
+ const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(
1580
+ registryUrl,
1581
+ choiceArgs
1582
+ );
1583
+ return this.createAllocationInstructionFromContext(
1584
+ factoryId,
1585
+ choiceArgs,
1586
+ choiceContext
1587
+ );
1588
+ }
1589
+ buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
1590
+ const exercise = {
1591
+ templateId,
1592
+ contractId,
1593
+ choice,
1594
+ choiceArgument: {
1595
+ extraArgs: {
1596
+ context: choiceContext.choiceContextData,
1597
+ meta: EMPTY_META
1598
+ }
1599
+ }
1600
+ };
1601
+ return [exercise, choiceContext.disclosedContracts ?? []];
1602
+ }
1603
+ async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
1604
+ return this.core.getTokenStandardClient(registryUrl).post(
1605
+ "/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer",
1606
+ {},
1607
+ {
1608
+ path: {
1609
+ allocationId
1610
+ }
1611
+ }
1612
+ );
1613
+ }
1614
+ createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
1615
+ return this.buildAllocationExerciseWithContext(
1616
+ coreTokenStandard.ALLOCATION_INTERFACE_ID,
1617
+ allocationCid,
1618
+ "Allocation_ExecuteTransfer",
1619
+ choiceContext
1620
+ );
1621
+ }
1622
+ async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1623
+ if (prefetchedRegistryChoiceContext) {
1624
+ return this.createExecuteTransferAllocationFromContext(
1625
+ allocationCid,
1626
+ prefetchedRegistryChoiceContext
1627
+ );
1628
+ }
1629
+ const choiceContext = await this.fetchExecuteTransferChoiceContext(
1630
+ allocationCid,
1631
+ registryUrl
1632
+ );
1633
+ return this.createExecuteTransferAllocationFromContext(
1634
+ allocationCid,
1635
+ choiceContext
1636
+ );
1637
+ }
1638
+ async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
1639
+ return this.core.getTokenStandardClient(registryUrl).post(
1640
+ "/registry/allocations/v1/{allocationId}/choice-contexts/withdraw",
1641
+ {},
1642
+ { path: { allocationId: allocationCid } }
1643
+ );
1644
+ }
1645
+ createWithdrawAllocationFromContext(allocationCid, choiceContext) {
1646
+ return this.buildAllocationExerciseWithContext(
1647
+ coreTokenStandard.ALLOCATION_INTERFACE_ID,
1648
+ allocationCid,
1649
+ "Allocation_Withdraw",
1650
+ choiceContext
1651
+ );
1652
+ }
1653
+ async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1654
+ if (prefetchedRegistryChoiceContext) {
1655
+ return this.createWithdrawAllocationFromContext(
1656
+ allocationCid,
1657
+ prefetchedRegistryChoiceContext
1658
+ );
1659
+ }
1660
+ const choiceContext = await this.fetchWithdrawAllocationChoiceContext(
1661
+ allocationCid,
1662
+ registryUrl
1663
+ );
1664
+ return this.createWithdrawAllocationFromContext(
1665
+ allocationCid,
1666
+ choiceContext
1667
+ );
1668
+ }
1669
+ async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
1670
+ return this.core.getTokenStandardClient(registryUrl).post(
1671
+ "/registry/allocations/v1/{allocationId}/choice-contexts/cancel",
1672
+ {},
1673
+ { path: { allocationId: allocationCid } }
1674
+ );
1675
+ }
1676
+ createCancelAllocationFromContext(allocationCid, choiceContext) {
1677
+ return this.buildAllocationExerciseWithContext(
1678
+ coreTokenStandard.ALLOCATION_INTERFACE_ID,
1679
+ allocationCid,
1680
+ "Allocation_Cancel",
1681
+ choiceContext
1682
+ );
1683
+ }
1684
+ async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
1685
+ if (prefetchedRegistryChoiceContext) {
1686
+ return this.createCancelAllocationFromContext(
1687
+ allocationCid,
1688
+ prefetchedRegistryChoiceContext
1689
+ );
1690
+ }
1691
+ const choiceContext = await this.fetchCancelAllocationChoiceContext(
1692
+ allocationCid,
1693
+ registryUrl
1694
+ );
1695
+ return this.createCancelAllocationFromContext(
1696
+ allocationCid,
1697
+ choiceContext
1698
+ );
1699
+ }
1700
+ async createWithdrawAllocationInstruction(allocationInstructionCid) {
1701
+ const exercise = {
1702
+ templateId: coreTokenStandard.ALLOCATION_INSTRUCTION_INTERFACE_ID,
1703
+ contractId: allocationInstructionCid,
1704
+ choice: "AllocationInstruction_Withdraw",
1705
+ choiceArgument: {
1706
+ extraArgs: {
1707
+ context: { values: {} },
1708
+ meta: { values: {} }
1709
+ }
1710
+ }
1711
+ };
1712
+ return [exercise, []];
1713
+ }
1714
+ async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
1715
+ const exercise = {
1716
+ templateId: coreTokenStandard.ALLOCATION_INSTRUCTION_INTERFACE_ID,
1717
+ contractId: allocationInstructionCid,
1718
+ choice: "AllocationInstruction_Update",
1719
+ choiceArgument: {
1720
+ extraActors,
1721
+ extraArgs: {
1722
+ context: { values: extraArgsContext },
1723
+ meta: { values: extraArgsMeta }
1724
+ }
1725
+ }
1726
+ };
1727
+ return [exercise, []];
1728
+ }
1729
+ async createRejectAllocationRequest(allocationRequestCid, actor) {
1730
+ const exercise = {
1731
+ templateId: coreTokenStandard.ALLOCATION_REQUEST_INTERFACE_ID,
1732
+ contractId: allocationRequestCid,
1733
+ choice: "AllocationRequest_Reject",
1734
+ choiceArgument: {
1735
+ actor,
1736
+ extraArgs: {
1737
+ context: { values: {} },
1738
+ meta: { values: {} }
1739
+ }
1740
+ }
1741
+ };
1742
+ return [exercise, []];
1743
+ }
1744
+ async createWithdrawAllocationRequest(allocationRequestCid) {
1745
+ const exercise = {
1746
+ templateId: coreTokenStandard.ALLOCATION_REQUEST_INTERFACE_ID,
1747
+ contractId: allocationRequestCid,
1748
+ choice: "AllocationRequest_Withdraw",
1749
+ choiceArgument: {
1750
+ extraArgs: {
1751
+ context: { values: {} },
1752
+ meta: { values: {} }
1753
+ }
1754
+ }
1755
+ };
1756
+ return [exercise, []];
1757
+ }
1758
+ };
1759
+ var TransferService = class {
1760
+ constructor(core, logger) {
1761
+ this.core = core;
1762
+ this.logger = logger;
1763
+ }
1764
+ async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta) {
1765
+ const inputHoldingCids = await this.core.getInputHoldingsCids(
1766
+ sender,
1767
+ inputUtxos
1768
+ );
1769
+ return {
1770
+ expectedAdmin: instrumentAdmin,
1771
+ transfer: {
1772
+ sender,
1773
+ receiver,
1774
+ amount,
1775
+ instrumentId: { admin: instrumentAdmin, id: instrumentId },
1776
+ requestedAt: new Date(
1777
+ Date.now() - REQUESTED_AT_SKEW_MS
1778
+ ).toISOString(),
1779
+ executeBefore: (expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1e3)).toISOString(),
1780
+ inputHoldingCids,
1781
+ meta: { values: { [MEMO_KEY]: memo || "", ...meta?.values } }
1782
+ },
1783
+ extraArgs: {
1784
+ context: { values: {} },
1785
+ meta: { values: {} }
1786
+ }
1787
+ };
1788
+ }
1789
+ async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs) {
1790
+ return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
1791
+ choiceArguments: choiceArgs
1792
+ });
1793
+ }
1794
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
1795
+ this.logger.debug("Creating transfer from pre-fetched context...");
1796
+ choiceArgs.extraArgs.context = {
1797
+ ...choiceContext.choiceContextData,
1798
+ values: choiceContext.choiceContextData?.values ?? {}
1799
+ };
1800
+ const exercise = {
1801
+ templateId: coreTokenStandard.TRANSFER_FACTORY_INTERFACE_ID,
1802
+ contractId: factoryId,
1803
+ choice: "TransferFactory_Transfer",
1804
+ choiceArgument: choiceArgs
1805
+ };
1806
+ return [exercise, choiceContext.disclosedContracts];
1807
+ }
1808
+ async createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext) {
1809
+ try {
1810
+ const choiceArgs = await this.buildTransferChoiceArgs(
1811
+ sender,
1812
+ receiver,
1813
+ amount,
1814
+ instrumentAdmin,
1815
+ instrumentId,
1816
+ inputUtxos,
1817
+ memo,
1818
+ expiryDate,
1819
+ meta
1820
+ );
1821
+ if (prefetchedRegistryChoiceContext) {
1822
+ return this.createTransferFromContext(
1823
+ prefetchedRegistryChoiceContext.factoryId,
1824
+ choiceArgs,
1825
+ prefetchedRegistryChoiceContext.choiceContext
1826
+ );
1827
+ }
1828
+ const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(
1829
+ registryUrl,
1830
+ choiceArgs
1831
+ );
1832
+ return this.createTransferFromContext(
1833
+ factoryId,
1834
+ choiceArgs,
1835
+ choiceContext
1836
+ );
1837
+ } catch (e) {
1838
+ this.logger.error("Failed to execute transfer:", e);
1839
+ throw e;
1840
+ }
1841
+ }
1842
+ async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
1843
+ const client = this.core.getTokenStandardClient(registryUrl);
1844
+ const choiceContext = await client.post(
1845
+ "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept",
1846
+ {},
1847
+ {
1848
+ path: {
1849
+ transferInstructionId: transferInstructionCid
1850
+ }
1851
+ }
1852
+ );
1853
+ return {
1854
+ choiceContextData: choiceContext.choiceContextData,
1855
+ disclosedContracts: choiceContext.disclosedContracts
1856
+ };
1857
+ }
1858
+ async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
1859
+ try {
1860
+ const exercise = {
1861
+ templateId: coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID,
1862
+ contractId: transferInstructionCid,
1863
+ choice: "TransferInstruction_Accept",
1864
+ choiceArgument: {
1865
+ extraArgs: {
1866
+ context: choiceContext.choiceContextData,
1867
+ meta: { values: {} }
1868
+ }
1869
+ }
1870
+ };
1871
+ return [exercise, choiceContext.disclosedContracts];
1872
+ } catch (e) {
1873
+ this.logger.error(
1874
+ "Failed to create accept transfer instruction:",
1875
+ e
1876
+ );
1877
+ throw e;
1878
+ }
1879
+ }
1880
+ async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1881
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(
1882
+ transferInstructionCid,
1883
+ registryUrl.href
1884
+ );
1885
+ const choiceArgs = {
1886
+ cid: acceptTransferInstructionContext.contractId,
1887
+ proxyArg: {
1888
+ featuredAppRightCid,
1889
+ beneficiaries,
1890
+ choiceArg: acceptTransferInstructionContext.choiceArgument
1891
+ }
1892
+ };
1893
+ return [
1894
+ {
1895
+ templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1896
+ contractId: proxyCid,
1897
+ choice: "DelegateProxy_TransferInstruction_Accept",
1898
+ choiceArgument: choiceArgs
1899
+ },
1900
+ disclosedContracts
1901
+ ];
1902
+ }
1903
+ async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1904
+ const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(
1905
+ transferInstructionCid,
1906
+ registryUrl.href
1907
+ );
1908
+ const choiceArgs = {
1909
+ cid: rejectTransferInstructionContext.contractId,
1910
+ proxyArg: {
1911
+ featuredAppRightCid,
1912
+ beneficiaries,
1913
+ choiceArg: rejectTransferInstructionContext.choiceArgument
1914
+ }
1915
+ };
1916
+ return [
1917
+ {
1918
+ templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1919
+ contractId: proxyCid,
1920
+ choice: "DelegateProxy_TransferInstruction_Reject",
1921
+ choiceArgument: choiceArgs
1922
+ },
1923
+ disclosedContracts
1924
+ ];
1925
+ }
1926
+ async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
1927
+ const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(
1928
+ transferInstructionCid,
1929
+ registryUrl.href
1930
+ );
1931
+ const sumOfWeights = beneficiaries.reduce(
1932
+ (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
1933
+ 0
1934
+ );
1935
+ if (sumOfWeights > 1) {
1936
+ throw new Error("Sum of beneficiary weights is larger than 1.");
1937
+ }
1938
+ const choiceArgs = {
1939
+ cid: withdrawTransferInstructionContext.contractId,
1940
+ proxyArg: {
1941
+ featuredAppRightCid,
1942
+ beneficiaries,
1943
+ choiceArg: withdrawTransferInstructionContext.choiceArgument
1944
+ }
1945
+ };
1946
+ return [
1947
+ {
1948
+ templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1949
+ contractId: proxyCid,
1950
+ choice: "DelegateProxy_TransferInstruction_Withdraw",
1951
+ choiceArgument: choiceArgs
1952
+ },
1953
+ disclosedContracts
1954
+ ];
1955
+ }
1956
+ async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
1957
+ if (prefetchedRegistryChoiceContext) {
1958
+ return this.createAcceptTransferInstructionFromContext(
1959
+ transferInstructionCid,
1960
+ {
1961
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
1962
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
1963
+ }
1964
+ );
1965
+ }
1966
+ const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(
1967
+ transferInstructionCid,
1968
+ registryUrl
1969
+ );
1970
+ return this.createAcceptTransferInstructionFromContext(
1971
+ transferInstructionCid,
1972
+ choiceContext
1973
+ );
1974
+ }
1975
+ async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
1976
+ const client = this.core.getTokenStandardClient(registryUrl);
1977
+ const choiceContext = await client.post(
1978
+ "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject",
1979
+ {},
1980
+ {
1981
+ path: {
1982
+ transferInstructionId: transferInstructionCid
1983
+ }
1984
+ }
1985
+ );
1986
+ return {
1987
+ choiceContextData: choiceContext.choiceContextData,
1988
+ disclosedContracts: choiceContext.disclosedContracts
1989
+ };
1990
+ }
1991
+ async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
1992
+ try {
1993
+ const exercise = {
1994
+ templateId: coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID,
1995
+ contractId: transferInstructionCid,
1996
+ choice: "TransferInstruction_Reject",
1997
+ choiceArgument: {
1998
+ extraArgs: {
1999
+ context: choiceContext.choiceContextData,
2000
+ meta: { values: {} }
2001
+ }
2002
+ }
2003
+ };
2004
+ return [exercise, choiceContext.disclosedContracts];
2005
+ } catch (e) {
2006
+ this.logger.error(
2007
+ "Failed to create reject transfer instruction:",
2008
+ e
2009
+ );
2010
+ throw e;
2011
+ }
2012
+ }
2013
+ async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
2014
+ if (prefetchedRegistryChoiceContext) {
2015
+ return this.createRejectTransferInstructionFromContext(
2016
+ transferInstructionCid,
2017
+ {
2018
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
2019
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
2020
+ }
2021
+ );
2022
+ }
2023
+ const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(
2024
+ transferInstructionCid,
2025
+ registryUrl
2026
+ );
2027
+ return this.createRejectTransferInstructionFromContext(
2028
+ transferInstructionCid,
2029
+ choiceContext
2030
+ );
2031
+ }
2032
+ async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
2033
+ const client = this.core.getTokenStandardClient(registryUrl);
2034
+ const choiceContext = await client.post(
2035
+ "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw",
2036
+ {},
2037
+ {
2038
+ path: {
2039
+ transferInstructionId: transferInstructionCid
2040
+ }
2041
+ }
2042
+ );
2043
+ return {
2044
+ choiceContextData: choiceContext.choiceContextData,
2045
+ disclosedContracts: choiceContext.disclosedContracts
2046
+ };
2047
+ }
2048
+ async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
2049
+ try {
2050
+ const exercise = {
2051
+ templateId: coreTokenStandard.TRANSFER_INSTRUCTION_INTERFACE_ID,
2052
+ contractId: transferInstructionCid,
2053
+ choice: "TransferInstruction_Withdraw",
2054
+ choiceArgument: {
2055
+ extraArgs: {
2056
+ context: choiceContext.choiceContextData,
2057
+ meta: { values: {} }
2058
+ }
2059
+ }
2060
+ };
2061
+ return [exercise, choiceContext.disclosedContracts];
2062
+ } catch (e) {
2063
+ this.logger.error(
2064
+ "Failed to create withdraw transfer instruction:",
2065
+ e
2066
+ );
2067
+ throw e;
2068
+ }
2069
+ }
2070
+ async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
2071
+ if (prefetchedRegistryChoiceContext) {
2072
+ return this.createWithdrawTransferInstructionFromContext(
2073
+ transferInstructionCid,
2074
+ {
2075
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
2076
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
2077
+ }
2078
+ );
2079
+ }
2080
+ const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(
2081
+ transferInstructionCid,
2082
+ registryUrl
2083
+ );
2084
+ return this.createWithdrawTransferInstructionFromContext(
2085
+ transferInstructionCid,
2086
+ choiceContext
2087
+ );
2088
+ }
2089
+ };
2090
+ var TokenStandardService = class {
2091
+ constructor(ledgerClient, scanProxyClient, logger, accessTokenProvider, isMasterUser) {
2092
+ this.ledgerClient = ledgerClient;
2093
+ this.scanProxyClient = scanProxyClient;
2094
+ this.logger = logger;
2095
+ this.accessTokenProvider = accessTokenProvider;
2096
+ this.isMasterUser = isMasterUser;
2097
+ __publicField(this, "core");
2098
+ __publicField(this, "allocation");
2099
+ __publicField(this, "transfer");
2100
+ this.core = new CoreService(
2101
+ ledgerClient,
2102
+ scanProxyClient,
2103
+ logger,
2104
+ accessTokenProvider,
2105
+ isMasterUser
2106
+ );
2107
+ this.allocation = new AllocationService(this.core, this.logger);
2108
+ this.transfer = new TransferService(this.core, this.logger);
2109
+ }
2110
+ async getTransferPreApprovalByParty(partyId) {
2111
+ const { transfer_preapproval } = await this.scanProxyClient.get(
2112
+ "/v0/scan-proxy/transfer-preapprovals/by-party/{party}",
2113
+ {
2114
+ path: {
2115
+ party: partyId
2116
+ }
2117
+ }
2118
+ );
2119
+ return transfer_preapproval;
2120
+ }
2121
+ async getFeaturedAppsByParty(partyId) {
2122
+ const { featured_app_right } = await this.scanProxyClient.get(
2123
+ "/v0/scan-proxy/featured-apps/{provider_party_id}",
2124
+ {
2125
+ path: {
2126
+ provider_party_id: partyId
2127
+ }
2128
+ }
2129
+ );
2130
+ return featured_app_right;
2131
+ }
2132
+ async getInstrumentById(registryUrl, instrumentId) {
2133
+ try {
2134
+ const params = {
2135
+ path: {
2136
+ instrumentId
2137
+ }
2138
+ };
2139
+ const client = this.core.getTokenStandardClient(registryUrl);
2140
+ return client.get(
2141
+ "/registry/metadata/v1/instruments/{instrumentId}",
2142
+ params
2143
+ );
2144
+ } catch (e) {
2145
+ this.logger.error(e);
2146
+ throw new Error(
2147
+ `Instrument id ${instrumentId} does not exist for this instrument admin.`
2148
+ );
2149
+ }
2150
+ }
2151
+ async getInstrumentAdmin(registryUrl) {
2152
+ const client = this.core.getTokenStandardClient(registryUrl);
2153
+ const info = await client.get("/registry/metadata/v1/info");
2154
+ return info.adminId;
2155
+ }
2156
+ // <T> is shape of viewValue related to queried interface.
2157
+ // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
2158
+ async listContractsByInterface(interfaceId, partyId, limit) {
2159
+ return this.core.listContractsByInterface(
2160
+ interfaceId,
2161
+ partyId,
2162
+ limit
2163
+ );
2164
+ }
2165
+ async listHoldingTransactions(partyId, afterOffset, beforeOffset) {
2166
+ try {
2167
+ this.logger.debug("Set or query offset");
2168
+ const afterOffsetOrLatest = Number(afterOffset) || (await this.ledgerClient.getWithRetry(
2169
+ "/v2/state/latest-pruned-offsets"
2170
+ )).participantPrunedUpToInclusive;
2171
+ const beforeOffsetOrLatest = Number(beforeOffset) || (await this.ledgerClient.getWithRetry("/v2/state/ledger-end")).offset;
2172
+ this.logger.debug(afterOffsetOrLatest, "Using offset");
2173
+ const updatesResponse = await this.ledgerClient.postWithRetry("/v2/updates/flats", {
2174
+ updateFormat: {
2175
+ includeTransactions: {
2176
+ eventFormat: EventFilterBySetup(
2177
+ TokenStandardTransactionInterfaces,
2178
+ {
2179
+ includeWildcard: true,
2180
+ isMasterUser: this.isMasterUser,
2181
+ partyId
2182
+ }
2183
+ ),
2184
+ transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
2185
+ }
2186
+ },
2187
+ beginExclusive: afterOffsetOrLatest,
2188
+ endInclusive: beforeOffsetOrLatest,
2189
+ verbose: false
2190
+ });
2191
+ return this.core.toPrettyTransactions(
2192
+ updatesResponse,
2193
+ partyId,
2194
+ this.ledgerClient
2195
+ );
2196
+ } catch (err) {
2197
+ this.logger.error("Failed to list holding transactions.", err);
2198
+ throw err;
2199
+ }
2200
+ }
2201
+ async getTransactionById(updateId, partyId) {
2202
+ const transactionFormat = {
2203
+ eventFormat: EventFilterBySetup(
2204
+ TokenStandardTransactionInterfaces,
2205
+ {
2206
+ includeWildcard: true,
2207
+ isMasterUser: this.isMasterUser,
2208
+ partyId
2209
+ }
2210
+ ),
2211
+ transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
2212
+ };
2213
+ const getTransactionResponse = await this.ledgerClient.postWithRetry(
2214
+ "/v2/updates/transaction-by-id",
2215
+ {
2216
+ updateId,
2217
+ transactionFormat
2218
+ }
2219
+ );
2220
+ return this.core.toPrettyTransaction(
2221
+ getTransactionResponse,
2222
+ partyId,
2223
+ this.ledgerClient
2224
+ );
2225
+ }
2226
+ async getInputHoldingsCids(sender, inputUtxos) {
2227
+ return this.core.getInputHoldingsCids(sender, inputUtxos);
2228
+ }
2229
+ async createDelegateProxyTranfser(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, featuredAppRightCid, proxyCid, beneficiaries, inputUtxos, memo, expiryDate, meta) {
2230
+ const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(
2231
+ sender,
2232
+ receiver,
2233
+ amount,
2234
+ instrumentAdmin,
2235
+ instrumentId,
2236
+ registryUrl,
2237
+ inputUtxos,
2238
+ memo,
2239
+ expiryDate,
2240
+ meta
2241
+ );
2242
+ const sumOfWeights = beneficiaries.reduce(
2243
+ (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
2244
+ 0
2245
+ );
2246
+ if (sumOfWeights > 1) {
2247
+ throw new Error("Sum of beneficiary weights is larger than 1.");
2248
+ }
2249
+ const choiceArgs = {
2250
+ cid: transferCommand.contractId,
2251
+ proxyArg: {
2252
+ featuredAppRightCid,
2253
+ beneficiaries,
2254
+ choiceArg: transferCommand.choiceArgument
2255
+ }
2256
+ };
2257
+ const exercise = {
2258
+ templateId: coreTokenStandard.FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
2259
+ contractId: proxyCid,
2260
+ choice: "DelegateProxy_TransferFactory_Transfer",
2261
+ choiceArgument: choiceArgs
2262
+ };
2263
+ return [exercise, disclosedContracts];
2264
+ }
2265
+ // TODO(#583) as it's not a part of token standard, should be moved somewhere else
2266
+ async createTap(receiver, amount, instrumentAdmin, instrumentId, registryUrl) {
2267
+ const now = /* @__PURE__ */ new Date();
2268
+ const tomorrow = new Date(now);
2269
+ tomorrow.setDate(tomorrow.getDate() + 1);
2270
+ const choiceArgs = {
2271
+ expectedAdmin: instrumentAdmin,
2272
+ transfer: {
2273
+ sender: instrumentAdmin,
2274
+ receiver,
2275
+ amount,
2276
+ instrumentId: { admin: instrumentAdmin, id: instrumentId },
2277
+ lock: null,
2278
+ requestedAt: new Date(
2279
+ Date.now() - REQUESTED_AT_SKEW_MS
2280
+ ).toISOString(),
2281
+ executeBefore: tomorrow.toISOString(),
2282
+ inputHoldingCids: [],
2283
+ meta: { values: {} }
2284
+ },
2285
+ extraArgs: {
2286
+ context: { values: {} },
2287
+ meta: { values: {} }
2288
+ }
2289
+ };
2290
+ const transferFactory = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
2291
+ choiceArguments: choiceArgs
2292
+ });
2293
+ const disclosedContracts = transferFactory.choiceContext.disclosedContracts;
2294
+ const amuletRules = await this.scanProxyClient.getAmuletRules();
2295
+ if (!amuletRules) {
2296
+ throw new Error("AmuletRules contract not found");
2297
+ }
2298
+ const latestOpenMiningRound = await this.core.getActiveOpenMiningRound();
2299
+ if (!latestOpenMiningRound) {
2300
+ throw new Error(
2301
+ "OpenMiningRound active at current moment not found"
2302
+ );
2303
+ }
2304
+ return [
2305
+ {
2306
+ templateId: amuletRules.template_id,
2307
+ contractId: amuletRules.contract_id,
2308
+ choice: "AmuletRules_DevNet_Tap",
2309
+ choiceArgument: {
2310
+ receiver,
2311
+ amount,
2312
+ openRound: latestOpenMiningRound.contract_id
2313
+ }
2314
+ },
2315
+ disclosedContracts
2316
+ ];
2317
+ }
2318
+ async selfGrantFeatureAppRight(providerPartyId, synchronizerId) {
2319
+ const amuletRules = await this.scanProxyClient.getAmuletRules();
2320
+ const disclosedContracts = {
2321
+ templateId: amuletRules.template_id,
2322
+ contractId: amuletRules.contract_id,
2323
+ createdEventBlob: amuletRules.created_event_blob,
2324
+ synchronizerId
2325
+ };
2326
+ return [
2327
+ {
2328
+ templateId: amuletRules.template_id,
2329
+ contractId: amuletRules.contract_id,
2330
+ choice: "AmuletRules_DevNet_FeatureApp",
2331
+ choiceArgument: {
2332
+ provider: providerPartyId
2333
+ }
2334
+ },
2335
+ [disclosedContracts]
2336
+ ];
2337
+ }
2338
+ async cancelTransferPreapproval(contractId, templateId, actor) {
2339
+ const exercise = {
2340
+ templateId,
2341
+ contractId,
2342
+ choice: "TransferPreapproval_Cancel",
2343
+ choiceArgument: { p: actor }
2344
+ };
2345
+ return [exercise, []];
2346
+ }
2347
+ async renewTransferPreapproval(contractId, templateId, provider, synchronizerId, newExpiresAt, inputUtxos) {
2348
+ const amuletRules = await this.scanProxyClient.getAmuletRules();
2349
+ const activeRound = await this.core.getActiveOpenMiningRound();
2350
+ if (!amuletRules) {
2351
+ throw new Error("AmuletRules contract not found");
2352
+ }
2353
+ if (!activeRound) {
2354
+ throw new Error(
2355
+ "OpenMiningRound active at current moment not found"
2356
+ );
2357
+ }
2358
+ const disclosed = [
2359
+ {
2360
+ templateId: amuletRules.template_id,
2361
+ contractId: amuletRules.contract_id,
2362
+ createdEventBlob: amuletRules.created_event_blob,
2363
+ synchronizerId
2364
+ },
2365
+ {
2366
+ templateId: activeRound.template_id,
2367
+ contractId: activeRound.contract_id,
2368
+ createdEventBlob: activeRound.created_event_blob,
2369
+ synchronizerId
2370
+ }
2371
+ ];
2372
+ const inputHoldings = await this.core.getInputHoldingsCids(
2373
+ provider,
2374
+ inputUtxos
2375
+ );
2376
+ const context = {
2377
+ context: {
2378
+ openMiningRound: activeRound.contract_id,
2379
+ issuingMiningRounds: [],
2380
+ validatorRights: [],
2381
+ featuredAppRight: null
2382
+ },
2383
+ amuletRules: amuletRules.contract_id
2384
+ };
2385
+ const effectiveNewExpiresAt = newExpiresAt ?? new Date(Date.now() + 90 * 24 * 3600 * 1e3);
2386
+ const exercise = {
2387
+ templateId,
2388
+ contractId,
2389
+ choice: "TransferPreapproval_Renew",
2390
+ choiceArgument: {
2391
+ context,
2392
+ inputs: inputHoldings.map((cid) => ({
2393
+ tag: "InputAmulet",
2394
+ value: cid
2395
+ })),
2396
+ newExpiresAt: effectiveNewExpiresAt.toISOString()
2397
+ }
2398
+ };
2399
+ return [exercise, disclosed];
2400
+ }
2401
+ async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
2402
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(
2403
+ transferInstructionCid,
2404
+ registryUrl
2405
+ );
2406
+ const choiceArgs = {
2407
+ cid: acceptTransferInstructionContext.contractId,
2408
+ proxyArg: {
2409
+ featuredAppRightCid,
2410
+ beneficiaries: [
2411
+ {
2412
+ beneficiary: exchangeParty,
2413
+ weight: 1
2414
+ }
2415
+ ],
2416
+ choiceArg: acceptTransferInstructionContext.choiceArgument
2417
+ }
2418
+ };
2419
+ return [
2420
+ {
2421
+ templateId: "#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy",
2422
+ contractId: proxyCid,
2423
+ choice: "DelegateProxy_TransferInstruction_Accept",
2424
+ choiceArgument: choiceArgs
2425
+ },
2426
+ disclosedContracts
2427
+ ];
2428
+ }
2429
+ };
2430
+
2431
+ // src/acs/acs-container.ts
2432
+ var ACS_UPDATE_CONFIG = {
2433
+ // 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
2434
+ maxEventsBeforePrune: 150,
2435
+ // 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
2436
+ safeOffsetDeltaForPrune: 200,
2437
+ // 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)
2438
+ maxUpdatesToFetch: 100,
2439
+ // 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
2440
+ // lower values will make the UI more responsive in case of problems, but may lead to unnecessary fallbacks
2441
+ wsTimeoutBeforeFirstElement: 1e4
2442
+ };
2443
+ if (typeof window !== "undefined") {
2444
+ window["ACS_UPDATE_CONFIG"] = ACS_UPDATE_CONFIG;
2445
+ }
2446
+ var ACSContainer = class _ACSContainer {
2447
+ constructor(orginalContainer = null) {
2448
+ __publicField(this, "acsSet", null);
2449
+ this.acsSet = orginalContainer ? orginalContainer.acsSet : null;
2450
+ }
2451
+ async update(offset, key, api, wsSupport) {
2452
+ if (this.acsSet === null) {
2453
+ const acs = await _ACSContainer.readACS(offset, key, api, wsSupport);
2454
+ this.acsSet = acs;
2455
+ return _ACSContainer.calculateAt(acs, offset);
2456
+ }
2457
+ if (this.acsSet.acsOffset > offset) {
2458
+ this.acsSet = null;
2459
+ return this.update(offset, key, api);
2460
+ }
2461
+ if (this.acsSet.updates.length >= ACS_UPDATE_CONFIG.maxEventsBeforePrune) {
2462
+ this.acsSet = await _ACSContainer.compact(this.acsSet);
2463
+ }
2464
+ const updates = await _ACSContainer.updateContracts(
2465
+ this.acsSet.lastUpdateOffset,
2466
+ offset,
2467
+ _ACSContainer.createEventFormat(key),
2468
+ api
2469
+ );
2470
+ const [newEvents, newOffset] = _ACSContainer.extractEvents(
2471
+ this.acsSet.lastUpdateOffset,
2472
+ updates
2473
+ );
2474
+ if (newOffset > this.acsSet.lastUpdateOffset) {
2475
+ this.acsSet = {
2476
+ ...this.acsSet,
2477
+ lastUpdateOffset: newOffset,
2478
+ updates: this.acsSet.updates.concat(newEvents)
2479
+ };
2480
+ }
2481
+ if (updates.length >= ACS_UPDATE_CONFIG.maxUpdatesToFetch) {
2482
+ return this.update(offset, key, api);
2483
+ }
2484
+ this.acsSet = {
2485
+ ...this.acsSet,
2486
+ lastUpdateOffset: offset
2487
+ // we have caught up
2488
+ };
2489
+ return _ACSContainer.calculateAt(this.acsSet, offset);
2490
+ }
2491
+ static calculateAt(acs, offset) {
2492
+ if (acs.acsOffset > offset) {
2493
+ return Promise.reject(
2494
+ Error(
2495
+ // This should never happen as we check this before calling calculateAt
2496
+ `Cannot calculate ACS at offset ${offset} when initial ACS is at ${acs.acsOffset}`
2497
+ )
2498
+ );
2499
+ }
2500
+ const addedContracts = [];
2501
+ const removedContractIds = /* @__PURE__ */ new Set();
2502
+ acs.updates.forEach((update) => {
2503
+ if (update.offset <= offset) {
2504
+ if (update.created) {
2505
+ const createdEv = update.created;
2506
+ const activeContract = {
2507
+ workflowId: update.workflowId ?? "",
2508
+ contractEntry: {
2509
+ JsActiveContract: {
2510
+ createdEvent: createdEv,
2511
+ synchronizerId: update.synchronizerId ?? "",
2512
+ reassignmentCounter: 0
2513
+ }
2514
+ }
2515
+ };
2516
+ addedContracts.push(activeContract);
2517
+ } else if (update.archivedContractId) {
2518
+ removedContractIds.add(update.archivedContractId);
2519
+ }
2520
+ }
2521
+ });
2522
+ const createdContracts = acs.initialAcs.concat(addedContracts);
2523
+ const result = createdContracts.filter(
2524
+ (contract) => !removedContractIds.has(
2525
+ contract.contractEntry.JsActiveContract?.createdEvent.contractId ?? ""
2526
+ )
2527
+ );
2528
+ return Promise.resolve(result);
2529
+ }
2530
+ static extractEvents(fromOffset, updates) {
2531
+ const newEvents = [];
2532
+ let newOffset = fromOffset;
2533
+ updates.forEach((update) => {
2534
+ if ("Transaction" in update.update) {
2535
+ const transaction = update.update.Transaction;
2536
+ const trOffset = transaction.value.offset;
2537
+ if (trOffset > newOffset) {
2538
+ const events = transaction.value.events ?? [];
2539
+ events.forEach((event) => {
2540
+ if ("CreatedEvent" in event) {
2541
+ const acUpdate = {
2542
+ created: event.CreatedEvent,
2543
+ archivedContractId: null,
2544
+ offset: trOffset,
2545
+ workflowId: transaction.value.workflowId,
2546
+ synchronizerId: transaction.value.synchronizerId
2547
+ };
2548
+ newEvents.push(acUpdate);
2549
+ newOffset = trOffset;
2550
+ } else if ("ArchivedEvent" in event) {
2551
+ const archivedEvent = event.ArchivedEvent;
2552
+ const acUpdate = {
2553
+ created: null,
2554
+ archivedContractId: archivedEvent.contractId,
2555
+ offset: trOffset,
2556
+ workflowId: transaction.value.workflowId,
2557
+ synchronizerId: transaction.value.synchronizerId
2558
+ };
2559
+ newEvents.push(acUpdate);
2560
+ newOffset = trOffset;
2561
+ }
2562
+ });
2563
+ }
2564
+ } else if ("OffsetCheckpoint" in update.update) {
2565
+ const checkpoint = update.update.OffsetCheckpoint;
2566
+ newOffset = checkpoint.value.offset;
2567
+ } else {
2568
+ console.log(
2569
+ `ACS Update got unknown update type: ${JSON.stringify(update.update)}`
2570
+ );
2571
+ }
2572
+ });
2573
+ return [newEvents, newOffset];
2574
+ }
2575
+ static async updateContracts(startOffset, endOffset, eventFormat, api) {
2576
+ const request = {
2577
+ beginExclusive: startOffset,
2578
+ endInclusive: endOffset,
2579
+ updateFormat: {
2580
+ includeTransactions: {
2581
+ eventFormat,
2582
+ transactionShape: "TRANSACTION_SHAPE_ACS_DELTA"
2583
+ }
2584
+ },
2585
+ verbose: false
2586
+ };
2587
+ const params = {
2588
+ query: {
2589
+ limit: ACS_UPDATE_CONFIG.maxUpdatesToFetch,
2590
+ stream_idle_timeout_ms: 1e3
2591
+ }
2592
+ };
2593
+ return api.postWithRetry(
2594
+ "/v2/updates/flats",
2595
+ request,
2596
+ defaultRetryableOptions,
2597
+ params
2598
+ );
2599
+ }
2600
+ static async compact(acs) {
2601
+ const newAcsOffset = Math.max(
2602
+ acs.acsOffset,
2603
+ acs.lastUpdateOffset - ACS_UPDATE_CONFIG.safeOffsetDeltaForPrune
2604
+ );
2605
+ if (newAcsOffset > acs.acsOffset) {
2606
+ const responses = await _ACSContainer.calculateAt(acs, newAcsOffset);
2607
+ return {
2608
+ acsOffset: newAcsOffset,
2609
+ initialAcs: responses,
2610
+ lastUpdateOffset: acs.lastUpdateOffset,
2611
+ updates: acs.updates.filter(
2612
+ (update) => update.offset > newAcsOffset
2613
+ )
2614
+ };
2615
+ }
2616
+ return acs;
2617
+ }
2618
+ static async readACS(offset, key, api, wsSupport) {
2619
+ if (wsSupport && wsSupport.enabled()) {
2620
+ return _ACSContainer.readACSUsingWs(offset, key, wsSupport).catch(
2621
+ () => {
2622
+ console.log("Falling back to HTTP for ACS read");
2623
+ return _ACSContainer.readHttpACS(offset, key, api);
2624
+ }
2625
+ );
2626
+ }
2627
+ return _ACSContainer.readHttpACS(offset, key, api);
2628
+ }
2629
+ static async readHttpACS(offset, key, api) {
2630
+ const format = _ACSContainer.createEventFormat(key);
2631
+ const acs = await api.postWithRetry("/v2/state/active-contracts", {
2632
+ activeAtOffset: offset,
2633
+ verbose: false,
2634
+ eventFormat: format
2635
+ });
2636
+ return {
2637
+ acsOffset: offset,
2638
+ initialAcs: acs,
2639
+ lastUpdateOffset: offset,
2640
+ updates: []
2641
+ };
2642
+ }
2643
+ static readACSUsingWs(offset, key, wsSupport) {
2644
+ const wsACSURL = `${wsSupport.baseUrl}/v2/state/active-contracts`;
2645
+ const format = _ACSContainer.createEventFormat(key);
2646
+ const request = {
2647
+ activeAtOffset: offset,
2648
+ verbose: false,
2649
+ eventFormat: format
2650
+ };
2651
+ return new Promise((resolve, reject) => {
2652
+ const ws = new WebSocket(wsACSURL, wsSupport.extractProtocols());
2653
+ const results = [];
2654
+ let finished = false;
2655
+ let error = null;
2656
+ setTimeout(() => {
2657
+ if (!finished && !error && results.length === 0) {
2658
+ error = Error(
2659
+ `No data received from WebSocket ${wsACSURL} within ${ACS_UPDATE_CONFIG.wsTimeoutBeforeFirstElement}ms`
2660
+ );
2661
+ wsSupport.reportError(error);
2662
+ reject(error);
2663
+ ws.close();
2664
+ }
2665
+ }, ACS_UPDATE_CONFIG.wsTimeoutBeforeFirstElement);
2666
+ ws.onopen = () => {
2667
+ ws.send(JSON.stringify(request));
2668
+ };
2669
+ ws.onmessage = (event) => {
2670
+ try {
2671
+ const data = JSON.parse(
2672
+ event.data
2673
+ );
2674
+ results.push(data);
2675
+ } catch (err) {
2676
+ console.error("Invalid JSON:", err);
2677
+ }
2678
+ };
2679
+ ws.onerror = () => {
2680
+ error = new Error("WebSocket error");
2681
+ wsSupport.reportError(error);
2682
+ reject(error);
2683
+ };
2684
+ ws.onclose = () => {
2685
+ finished = true;
2686
+ if (!error) {
2687
+ wsSupport.reportSuccess();
2688
+ resolve({
2689
+ acsOffset: offset,
2690
+ initialAcs: results,
2691
+ lastUpdateOffset: offset,
2692
+ updates: []
2693
+ });
2694
+ }
2695
+ };
2696
+ });
2697
+ }
2698
+ static createInterfaceFilter(interfaceId) {
2699
+ return {
2700
+ cumulative: [
2701
+ {
2702
+ identifierFilter: {
2703
+ InterfaceFilter: {
2704
+ value: {
2705
+ interfaceId,
2706
+ includeInterfaceView: true,
2707
+ includeCreatedEventBlob: false
2708
+ }
2709
+ }
2710
+ }
2711
+ }
2712
+ ]
2713
+ };
2714
+ }
2715
+ static createTemplateFilter(templateId) {
2716
+ return {
2717
+ cumulative: [
2718
+ {
2719
+ identifierFilter: {
2720
+ TemplateFilter: {
2721
+ value: {
2722
+ templateId,
2723
+ includeCreatedEventBlob: false
2724
+ }
2725
+ }
2726
+ }
2727
+ }
2728
+ ]
2729
+ };
2730
+ }
2731
+ static createEventFormat(key) {
2732
+ const cumulativeFilter = key.templateId ? _ACSContainer.createTemplateFilter(key.templateId) : _ACSContainer.createInterfaceFilter(key.interfaceId ?? "");
2733
+ const baseFormat = {
2734
+ filtersByParty: {},
2735
+ verbose: false
2736
+ };
2737
+ if (key.party) {
2738
+ if (!key.interfaceId && !key.templateId) {
2739
+ baseFormat.filtersByParty[key.party] = {};
2740
+ return baseFormat;
2741
+ }
2742
+ baseFormat.filtersByParty[key.party] = cumulativeFilter;
2743
+ return baseFormat;
2744
+ }
2745
+ return {
2746
+ ...baseFormat,
2747
+ filtersForAnyParty: cumulativeFilter
2748
+ };
2749
+ }
2750
+ };
2751
+
2752
+ // src/acs/acs-helper.ts
2753
+ var DEFAULT_MAX_CACHE_SIZE = 50;
2754
+ var DEFAULT_ENTRY_EXPIRATION_TIME = 10 * 60 * 1e3;
2755
+ var ACSHelper = class _ACSHelper {
2756
+ constructor(apiInstance, _logger, options) {
2757
+ __publicField(this, "contractsSet");
2758
+ __publicField(this, "apiInstance");
2759
+ __publicField(this, "wsSupport");
2760
+ __publicField(this, "logger");
2761
+ __publicField(this, "hits", 0);
2762
+ __publicField(this, "misses", 0);
2763
+ __publicField(this, "evictions", 0);
2764
+ __publicField(this, "totalLookuptime", 0);
2765
+ __publicField(this, "totalCacheServeTime", 0);
2766
+ this.contractsSet = new typescriptLruCache.LRUCache({
2767
+ maxSize: options?.maxCacheSize ?? DEFAULT_MAX_CACHE_SIZE,
2768
+ entryExpirationTimeInMS: options?.entryExpirationTime ?? DEFAULT_ENTRY_EXPIRATION_TIME,
2769
+ // 10 minutes
2770
+ onEntryEvicted: (entry) => {
2771
+ this.logger.debug(
2772
+ `entry ${entry.key} isExpired = ${entry.isExpired}. evicting entry.`
2773
+ );
2774
+ this.evictions++;
2775
+ }
2776
+ });
2777
+ this.apiInstance = apiInstance;
2778
+ this.wsSupport = options?.wsSupport;
2779
+ this.logger = _logger.child({ component: "ACSHelper" });
2780
+ }
2781
+ getCacheStats() {
2782
+ const totalCalls = this.hits + this.misses;
2783
+ const hitRate = totalCalls ? this.hits / totalCalls * 100 : 0;
2784
+ const avgLookupTime = totalCalls > 0 ? this.totalLookuptime / totalCalls : 0;
2785
+ return {
2786
+ totalCalls,
2787
+ hits: this.hits,
2788
+ misses: this.misses,
2789
+ evictions: this.evictions,
2790
+ cacheSize: this.contractsSet.size,
2791
+ hitRate: hitRate.toFixed(2) + "%",
2792
+ averageLookupTime: avgLookupTime.toFixed(3) + " ms",
2793
+ cacheServeTime: this.totalCacheServeTime.toFixed(3)
2794
+ };
2795
+ }
2796
+ static createKey(party, templateId, interfaceId) {
2797
+ return { party, templateId, interfaceId };
2798
+ }
2799
+ static keyToString(key) {
2800
+ return `${key.party ? key.party : "ANY"}_T:${key.templateId ?? "()"}_I:${key.interfaceId ?? "()"}`;
2801
+ }
2802
+ findACSContainer(key) {
2803
+ const keyStr = _ACSHelper.keyToString(key);
2804
+ const start = performance.now();
2805
+ const existing = this.contractsSet.get(keyStr);
2806
+ const end = performance.now();
2807
+ this.totalLookuptime += end - start;
2808
+ if (existing) {
2809
+ this.hits++;
2810
+ this.logger.debug("cache hit");
2811
+ return existing;
2812
+ }
2813
+ this.logger.debug("cache miss");
2814
+ this.misses++;
2815
+ const newContainer = new ACSContainer();
2816
+ this.contractsSet.set(keyStr, newContainer);
2817
+ return newContainer;
2818
+ }
2819
+ async activeContractsForTemplate(offset, partyFilter, templateId) {
2820
+ const key = _ACSHelper.createKey(partyFilter, templateId, void 0);
2821
+ const start = performance.now();
2822
+ const container = this.findACSContainer(key);
2823
+ const result = container.update(
2824
+ offset,
2825
+ key,
2826
+ this.apiInstance,
2827
+ this.wsSupport
2828
+ );
2829
+ const end = performance.now();
2830
+ if (this.contractsSet.has(_ACSHelper.keyToString(key))) {
2831
+ this.totalCacheServeTime += end - start;
2832
+ }
2833
+ return result;
2834
+ }
2835
+ async activeContractsForInterface(offset, partyFilter, interfaceId) {
2836
+ const key = _ACSHelper.createKey(partyFilter, void 0, interfaceId);
2837
+ const start = performance.now();
2838
+ const container = this.findACSContainer(key);
2839
+ const result = container.update(
2840
+ offset,
2841
+ key,
2842
+ this.apiInstance,
2843
+ this.wsSupport
2844
+ );
2845
+ const end = performance.now();
2846
+ if (this.contractsSet.has(_ACSHelper.keyToString(key))) {
2847
+ this.totalCacheServeTime += end - start;
2848
+ }
2849
+ return result;
2850
+ }
2851
+ };
2852
+
2853
+ // src/ledger-client.ts
2854
+ var supportedVersions = ["3.3", "3.4"];
2855
+ var LedgerClient = class {
2856
+ constructor(baseUrl, _logger, isAdmin = false, accessToken, accessTokenProvider, version, acsHelperOptions) {
2857
+ // privately manage the active connected version and associated client codegen
2858
+ __publicField(this, "clients");
2859
+ __publicField(this, "clientVersion", "3.3");
2860
+ // default to 3.3 if not provided
2861
+ __publicField(this, "currentClient");
2862
+ __publicField(this, "initialized", false);
2863
+ __publicField(this, "accessTokenProvider");
2864
+ __publicField(this, "acsHelper");
2865
+ __publicField(this, "logger");
2866
+ this.logger = _logger.child({ component: "LedgerClient" });
2867
+ this.accessTokenProvider = accessTokenProvider;
2868
+ this.clients = {
2869
+ "3.3": createClient__default.default({
2870
+ baseUrl: baseUrl.href,
2871
+ fetch: async (url, options = {}) => {
2872
+ if (this.accessTokenProvider) {
2873
+ accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
2874
+ }
2875
+ return fetch(url, {
2876
+ ...options,
2877
+ headers: {
2878
+ ...options.headers || {},
2879
+ Authorization: `Bearer ${accessToken}`
2880
+ }
2881
+ });
2882
+ }
2883
+ }),
2884
+ "3.4": createClient__default.default({
2885
+ baseUrl: baseUrl.href,
2886
+ fetch: async (url, options = {}) => {
2887
+ if (this.accessTokenProvider) {
2888
+ accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
2889
+ }
2890
+ return fetch(url, {
2891
+ ...options,
2892
+ headers: {
2893
+ ...options.headers || {},
2894
+ Authorization: `Bearer ${accessToken}`
2895
+ }
2896
+ });
2897
+ }
2898
+ })
2899
+ };
2900
+ this.clientVersion = version ?? this.clientVersion;
2901
+ this.currentClient = this.clients[this.clientVersion];
2902
+ this.acsHelper = new ACSHelper(this, _logger, acsHelperOptions);
2903
+ }
2904
+ async init() {
2905
+ if (!this.initialized) {
2906
+ const versionFromClient = await this.currentClient.GET("/v2/version");
2907
+ this.clientVersion = this.parseSupportedVersions(
2908
+ versionFromClient.data?.version
2909
+ );
2910
+ this.initialized = true;
2911
+ }
2912
+ }
2913
+ getCurrentClientVersion() {
2914
+ return this.clientVersion;
2915
+ }
2916
+ parseSupportedVersions(version) {
2917
+ if (!version) {
2918
+ throw new Error("Client version missing from response");
2919
+ }
2920
+ const match = supportedVersions.find((v) => version.startsWith(v));
2921
+ if (!match) {
2922
+ throw new Error(`Unsupported version - found ${version}`);
2923
+ }
2924
+ return match;
2925
+ }
2926
+ /**
2927
+ * Check if a party exists
2928
+ *
2929
+ * @param partyId The ID of the party to look for
2930
+ * @returns A promise to resolves to a boolean.
2931
+ */
2932
+ async checkIfPartyExists(partyId) {
2933
+ try {
2934
+ const party = await this.get("/v2/parties/{party}", {
2935
+ path: { party: partyId }
2936
+ });
2937
+ return party.partyDetails !== void 0 && party.partyDetails[0].party === partyId;
2938
+ } catch {
2939
+ return false;
2940
+ }
2941
+ }
2942
+ /**
2943
+ * grant "Master User" rights to a user.
2944
+ *
2945
+ * this require running with an admin token.
2946
+ *
2947
+ * @param userId The ID of the user to grant rights to.
2948
+ * @param canReadAsAnyParty define if the user can read as any party.
2949
+ * @param canExecuteAsAnyParty define if the user can execute as any party.
2950
+ */
2951
+ async grantMasterUserRights(userId, canReadAsAnyParty, canExecuteAsAnyParty) {
2952
+ const rights = [];
2953
+ if (canReadAsAnyParty) {
2954
+ rights.push({
2955
+ kind: {
2956
+ CanReadAsAnyParty: { value: {} }
2957
+ }
2958
+ });
2959
+ }
2960
+ if (canExecuteAsAnyParty) {
2961
+ rights.push({
2962
+ kind: {
2963
+ CanExecuteAsAnyParty: {
2964
+ value: {}
2965
+ }
2966
+ }
2967
+ });
2968
+ }
2969
+ const result = await this.post(
2970
+ "/v2/users/{user-id}/rights",
2971
+ {
2972
+ identityProviderId: "",
2973
+ userId,
2974
+ rights
2975
+ },
2976
+ {
2977
+ path: {
2978
+ "user-id": userId
2979
+ }
2980
+ }
2981
+ );
2982
+ if (!result.newlyGrantedRights) {
2983
+ throw new Error("Failed to grant user rights");
2984
+ }
2985
+ }
2986
+ /**
2987
+ * Create a new user.
2988
+ *
2989
+ * @param userId The ID of the user to create.
2990
+ * @param primaryParty The primary party of the user.
2991
+ */
2992
+ async createUser(userId, primaryParty) {
2993
+ try {
2994
+ const existing = await this.get("/v2/users/{user-id}", {
2995
+ path: { "user-id": userId }
2996
+ });
2997
+ if (existing && existing.user) {
2998
+ return existing.user;
2999
+ }
3000
+ } catch {
3001
+ }
3002
+ return (await this.post("/v2/users", {
3003
+ user: {
3004
+ identityProviderId: "",
3005
+ id: userId,
3006
+ isDeactivated: false,
3007
+ primaryParty
3008
+ },
3009
+ rights: [
3010
+ {
3011
+ kind: {
3012
+ ParticipantAdmin: {
3013
+ value: {}
3014
+ }
3015
+ }
3016
+ }
3017
+ ]
3018
+ })).user;
3019
+ }
3020
+ /**
3021
+ * Grants a user the right to act as a party, while ensuring the party exists.
3022
+ *
3023
+ * @param userId The ID of the user to grant rights to.
3024
+ * @param partyId The ID of the party to grant rights for.
3025
+ * @returns A promise that resolves when the rights have been granted.
3026
+ */
3027
+ async waitForPartyAndGrantUserRights(userId, partyId) {
3028
+ await this.init();
3029
+ let partyFound = false;
3030
+ let tries = 0;
3031
+ const maxTries = 30;
3032
+ while (!partyFound && tries < maxTries) {
3033
+ partyFound = await this.checkIfPartyExists(partyId);
3034
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
3035
+ tries++;
3036
+ }
3037
+ if (tries >= maxTries) {
3038
+ throw new Error("timed out waiting for new party to appear");
3039
+ }
3040
+ const result = await this.grantRights(userId, {
3041
+ actAs: [partyId]
3042
+ });
3043
+ if (!result.newlyGrantedRights) {
3044
+ throw new Error("Failed to grant user rights");
3045
+ }
3046
+ return;
3047
+ }
3048
+ async grantRights(userId, userRightsOptions) {
3049
+ await this.init();
3050
+ const rights = [];
3051
+ for (const partyId of userRightsOptions.readAs ?? []) {
3052
+ rights.push({
3053
+ kind: {
3054
+ CanReadAs: {
3055
+ value: {
3056
+ party: partyId
3057
+ }
3058
+ }
3059
+ }
3060
+ });
3061
+ }
3062
+ for (const partyId of userRightsOptions.actAs ?? []) {
3063
+ rights.push({
3064
+ kind: {
3065
+ CanActAs: {
3066
+ value: {
3067
+ party: partyId
3068
+ }
3069
+ }
3070
+ }
3071
+ });
3072
+ }
3073
+ if (userRightsOptions.canReadAsAnyParty) {
3074
+ rights.push({
3075
+ kind: {
3076
+ CanReadAsAnyParty: { value: {} }
3077
+ }
3078
+ });
3079
+ }
3080
+ if (userRightsOptions.canExecuteAsAnyParty) {
3081
+ rights.push({
3082
+ kind: {
3083
+ CanExecuteAsAnyParty: {
3084
+ value: {}
3085
+ }
3086
+ }
3087
+ });
3088
+ }
3089
+ const result = await this.post(
3090
+ "/v2/users/{user-id}/rights",
3091
+ {
3092
+ identityProviderId: "",
3093
+ userId,
3094
+ rights
3095
+ },
3096
+ {
3097
+ path: {
3098
+ "user-id": userId
3099
+ }
3100
+ }
3101
+ );
3102
+ if (!result.newlyGrantedRights) {
3103
+ throw new Error("Failed to grant user rights");
3104
+ }
3105
+ return result;
3106
+ }
3107
+ /** TODO: simplify once 3.4 snapshot contains this endpoint */
3108
+ async allocateExternalParty(synchronizerId, onboardingTransactions, multiHashSignatures) {
3109
+ await this.init();
3110
+ if (this.clientVersion !== "3.3") {
3111
+ throw new Error(
3112
+ "allocateExternalParty is only supported on 3.3 clients"
3113
+ );
3114
+ }
3115
+ const client = this.clients["3.3"];
3116
+ const resp = await client.POST("/v2/parties/external/allocate", {
3117
+ body: {
3118
+ synchronizer: synchronizerId,
3119
+ identityProviderId: "",
3120
+ onboardingTransactions,
3121
+ multiHashSignatures
3122
+ }
3123
+ });
3124
+ return this.valueOrError(resp);
3125
+ }
3126
+ /** TODO: simplify once 3.4 snapshot contains this endpoint */
3127
+ async generateTopology(synchronizerId, publicKey, partyHint, localParticipantObservationOnly = false, confirmationThreshold = 1, otherConfirmingParticipantUids = []) {
3128
+ await this.init();
3129
+ if (this.clientVersion !== "3.3") {
3130
+ throw new Error(
3131
+ "allocateExternalParty is only supported on 3.3 clients"
3132
+ );
3133
+ }
3134
+ const client = this.clients["3.3"];
3135
+ const body = {
3136
+ synchronizer: synchronizerId,
3137
+ partyHint,
3138
+ publicKey: {
3139
+ format: "CRYPTO_KEY_FORMAT_RAW",
3140
+ keyData: publicKey,
3141
+ keySpec: "SIGNING_KEY_SPEC_EC_CURVE25519"
3142
+ },
3143
+ localParticipantObservationOnly,
3144
+ confirmationThreshold,
3145
+ otherConfirmingParticipantUids
3146
+ };
3147
+ this.logger.debug(body, "generateTopology request body");
3148
+ const resp = await client.POST(
3149
+ "/v2/parties/external/generate-topology",
3150
+ { body }
3151
+ );
3152
+ return this.valueOrError(resp);
3153
+ }
3154
+ async activeContracts(options) {
3155
+ const { offset, templateIds, parties, filterByParty } = options;
3156
+ this.logger.debug(options, "options for active contracts");
3157
+ if (templateIds?.length === 1 && parties?.length === 1) {
3158
+ const party = parties[0];
3159
+ const templateId = templateIds[0];
3160
+ return this.acsHelper.activeContractsForTemplate(
3161
+ offset,
3162
+ party,
3163
+ templateId
3164
+ );
3165
+ }
3166
+ if (filterByParty && !templateIds?.length && parties?.length === 1) {
3167
+ const party = parties[0];
3168
+ const r = this.acsHelper.activeContractsForInterface(
3169
+ offset,
3170
+ party,
3171
+ ""
3172
+ );
3173
+ this.logger.info(r);
3174
+ return r;
3175
+ }
3176
+ const filter = this.buildActiveContractsFilter(options);
3177
+ this.logger.debug("falling back to post request");
3178
+ return await this.postWithRetry("/v2/state/active-contracts", filter);
3179
+ }
3180
+ buildActiveContractsFilter(options) {
3181
+ const filter = {
3182
+ filter: {
3183
+ filtersByParty: {}
3184
+ },
3185
+ verbose: false,
3186
+ activeAtOffset: options?.offset
3187
+ };
3188
+ const buildTemplateFilter = (templateIds) => {
3189
+ if (!templateIds) return [];
3190
+ return [
3191
+ {
3192
+ identifierFilter: {
3193
+ TemplateFilter: {
3194
+ value: {
3195
+ templateId: templateIds[0],
3196
+ includeCreatedEventBlob: true
3197
+ //TODO: figure out if this should be configurable
3198
+ }
3199
+ }
3200
+ }
3201
+ }
3202
+ ];
3203
+ };
3204
+ if (options?.filterByParty && options.parties && options.parties.length > 0) {
3205
+ for (const party of options.parties) {
3206
+ filter.filter.filtersByParty[party] = {
3207
+ cumulative: options.templateIds ? buildTemplateFilter(options.templateIds) : []
3208
+ };
3209
+ }
3210
+ } else if (options?.templateIds) {
3211
+ filter.filter.filtersForAnyParty = {
3212
+ cumulative: buildTemplateFilter(options.templateIds)
3213
+ };
3214
+ }
3215
+ return filter;
3216
+ }
3217
+ async postWithRetry(path, body, retryOptions = defaultRetryableOptions, params, additionalOptions) {
3218
+ return await retryable(
3219
+ () => this.post(path, body, params, additionalOptions),
3220
+ retryOptions,
3221
+ this.logger
3222
+ ).catch((e) => {
3223
+ throw asJsCantonError(e);
3224
+ });
3225
+ }
3226
+ async getWithRetry(path, retryOptions = defaultRetryableOptions, params) {
3227
+ return await retryable(
3228
+ () => this.get(path, params),
3229
+ retryOptions,
3230
+ this.logger
3231
+ ).catch((e) => {
3232
+ throw asJsCantonError(e);
3233
+ });
3234
+ }
3235
+ getCacheStats() {
3236
+ return this.acsHelper.getCacheStats();
3237
+ }
3238
+ /**
3239
+ * @deprecated use postWithRetry instead, should be made private
3240
+ */
3241
+ async post(path, body, params, additionalOptions) {
3242
+ const options = { body, params, ...additionalOptions };
3243
+ const resp = await this.currentClient.POST(path, options);
3244
+ return this.valueOrError(resp);
3245
+ }
3246
+ /**
3247
+ * @deprecated use getWithRetry instead, should be made private
3248
+ */
3249
+ async get(path, params) {
3250
+ await this.init();
3251
+ const options = { params };
3252
+ const resp = await this.currentClient.GET(path, options);
3253
+ return this.valueOrError(resp);
3254
+ }
3255
+ async valueOrError(response) {
3256
+ if (response.data === void 0) {
3257
+ return Promise.reject(response.error);
3258
+ } else {
3259
+ return Promise.resolve(response.data);
3260
+ }
3261
+ }
3262
+ };
3263
+
3264
+ // src/acs/ws-support.ts
3265
+ var INITIAL_BACKOFF_MS = 1e3;
3266
+ var MAX_BACKOFF_MS = 10 * 60 * 1e3;
3267
+ var WSSupportWithBackOffSwitch = class {
3268
+ constructor(extractProtocols, baseUrl) {
3269
+ this.extractProtocols = extractProtocols;
3270
+ this.baseUrl = baseUrl;
3271
+ __publicField(this, "backOffUntil", null);
3272
+ __publicField(this, "backOffDurationMs", INITIAL_BACKOFF_MS);
3273
+ }
3274
+ enabled() {
3275
+ if (this.backOffUntil === null) {
3276
+ return true;
3277
+ }
3278
+ const now = Date.now();
3279
+ if (now >= this.backOffUntil) {
3280
+ this.backOffUntil = null;
3281
+ return true;
3282
+ }
3283
+ return false;
3284
+ }
3285
+ reportError(error) {
3286
+ console.error("WebSocket error reported:", error);
3287
+ const now = Date.now();
3288
+ if (this.backOffUntil !== null && now - this.backOffUntil < 500) {
3289
+ return;
3290
+ }
3291
+ this.backOffUntil = Date.now() + this.backOffDurationMs;
3292
+ this.backOffDurationMs = Math.min(
3293
+ this.backOffDurationMs * 1.6,
3294
+ MAX_BACKOFF_MS
3295
+ );
3296
+ }
3297
+ reportSuccess() {
3298
+ this.backOffUntil = null;
3299
+ this.backOffDurationMs = INITIAL_BACKOFF_MS;
3300
+ }
3301
+ };
3302
+
3303
+ exports.ACSContainer = ACSContainer;
3304
+ exports.ACS_UPDATE_CONFIG = ACS_UPDATE_CONFIG;
3305
+ exports.CoreService = CoreService;
3306
+ exports.LedgerClient = LedgerClient;
3307
+ exports.TokenStandardService = TokenStandardService;
3308
+ exports.TopologyWriteService = TopologyWriteService;
3309
+ exports.WSSupportWithBackOffSwitch = WSSupportWithBackOffSwitch;
3310
+ exports.asJsCantonError = asJsCantonError;
3311
+ exports.awaitCompletion = awaitCompletion;
3312
+ exports.defaultRetryableOptions = defaultRetryableOptions;
3313
+ exports.isJsCantonError = isJsCantonError;
3314
+ exports.promiseWithTimeout = promiseWithTimeout;
3315
+ exports.supportedVersions = supportedVersions;
3316
+ //# sourceMappingURL=index.cjs.map
3317
+ //# sourceMappingURL=index.cjs.map