@canton-network/core-ledger-client 0.14.0 → 0.16.0

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