@canton-network/core-ledger-client 0.15.0 → 0.17.0

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