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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/acs/acs-container.d.ts +33 -0
  2. package/dist/acs/acs-container.d.ts.map +1 -0
  3. package/dist/acs/acs-helper.d.ts +37 -0
  4. package/dist/acs/acs-helper.d.ts.map +1 -0
  5. package/dist/acs/types.d.ts +10 -0
  6. package/dist/acs/types.d.ts.map +1 -0
  7. package/dist/acs/ws-support.d.ts +18 -0
  8. package/dist/acs/ws-support.d.ts.map +1 -0
  9. package/dist/index.cjs +3317 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.ts +3 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +3297 -7
  14. package/dist/index.js.map +1 -0
  15. package/dist/ledger-api-utils.d.ts +3 -1
  16. package/dist/ledger-api-utils.d.ts.map +1 -1
  17. package/dist/ledger-client.d.ts +31 -3
  18. package/dist/ledger-client.d.ts.map +1 -1
  19. package/dist/token-standard-service.d.ts +10 -7
  20. package/dist/token-standard-service.d.ts.map +1 -1
  21. package/dist/topology-write-service.d.ts +4 -2
  22. package/dist/topology-write-service.d.ts.map +1 -1
  23. package/dist/txparse/parser.d.ts.map +1 -1
  24. package/dist/txparse/test-data/mock/eventsByContractIdResponses.d.ts +153 -0
  25. package/dist/txparse/test-data/mock/eventsByContractIdResponses.d.ts.map +1 -1
  26. package/dist/txparse/types.d.ts +5 -2
  27. package/dist/txparse/types.d.ts.map +1 -1
  28. package/package.json +23 -11
  29. package/dist/constants.js +0 -47
  30. package/dist/generated-clients/openapi-3.3.0-SNAPSHOT.js +0 -5
  31. package/dist/generated-clients/openapi-3.4.0-SNAPSHOT.js +0 -5
  32. package/dist/ledger-api-utils.js +0 -432
  33. package/dist/ledger-client.js +0 -321
  34. package/dist/token-standard-service.js +0 -871
  35. package/dist/topology-write-service.js +0 -283
  36. package/dist/txparse/parser.js +0 -581
  37. package/dist/txparse/parser.test.d.ts +0 -2
  38. package/dist/txparse/parser.test.d.ts.map +0 -1
  39. package/dist/txparse/parser.test.js +0 -97
  40. package/dist/txparse/strict.js +0 -19
  41. package/dist/txparse/test-data/expected/txs.js +0 -2303
  42. package/dist/txparse/test-data/mock/eventsByContractIdResponses.js +0 -2973
  43. package/dist/txparse/test-data/mock/txs.js +0 -6788
  44. package/dist/txparse/types.js +0 -58
package/dist/constants.js DELETED
@@ -1,47 +0,0 @@
1
- // Copyright (c) 2025 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
2
- // SPDX-License-Identifier: Apache-2.0
3
- import { TRANSFER_INSTRUCTION_INTERFACE_ID, TRANSFER_FACTORY_INTERFACE_ID, ALLOCATION_FACTORY_INTERFACE_ID, ALLOCATION_INSTRUCTION_INTERFACE_ID, HOLDING_INTERFACE_ID, ALLOCATION_INTERFACE_ID, ALLOCATION_REQUEST_INTERFACE_ID, } from '@canton-network/core-token-standard';
4
- export function splitInterfaceId(interfaceId) {
5
- // Captures 3 groups: pkg, module and entity
6
- // Note that prefix # is optional in regexp below,
7
- // format without # is deprecated, but supported in canton 3.3 and will be removed in canton 3.4
8
- // https://docs.digitalasset.com/build/3.3/reference/lapi-migration-guide.html#identifier-addressing-by-package-name
9
- const regExp = /^#?([^:]+):([^:]+):([^:]+)$/;
10
- const match = regExp.exec(interfaceId);
11
- if (!match)
12
- return null;
13
- const [, packageName, moduleName, entityName] = match; // [0]=full, [1]=pkg, [2]=module, [3]=entity
14
- return {
15
- packageName,
16
- moduleName,
17
- entityName,
18
- };
19
- }
20
- export function matchInterfaceIds(a, b) {
21
- const aParts = splitInterfaceId(a);
22
- const bParts = splitInterfaceId(b);
23
- return (aParts !== null &&
24
- bParts !== null &&
25
- aParts.moduleName === bParts.moduleName &&
26
- aParts.entityName === bParts.entityName);
27
- }
28
- export const TokenStandardTransactionInterfaces = [
29
- HOLDING_INTERFACE_ID,
30
- TRANSFER_FACTORY_INTERFACE_ID,
31
- TRANSFER_INSTRUCTION_INTERFACE_ID,
32
- ALLOCATION_FACTORY_INTERFACE_ID,
33
- ALLOCATION_INSTRUCTION_INTERFACE_ID,
34
- ALLOCATION_INTERFACE_ID,
35
- ALLOCATION_REQUEST_INTERFACE_ID,
36
- ];
37
- const SpliceMetaKeyPrefix = 'splice.lfdecentralizedtrust.org/';
38
- export const TxKindMetaKey = `${SpliceMetaKeyPrefix}tx-kind`;
39
- export const SenderMetaKey = `${SpliceMetaKeyPrefix}sender`;
40
- export const ReasonMetaKey = `${SpliceMetaKeyPrefix}reason`;
41
- export const BurnedMetaKey = `${SpliceMetaKeyPrefix}burned`;
42
- export const AllKnownMetaKeys = [
43
- TxKindMetaKey,
44
- SenderMetaKey,
45
- ReasonMetaKey,
46
- BurnedMetaKey,
47
- ];
@@ -1,5 +0,0 @@
1
- /**
2
- * This file was auto-generated by openapi-typescript.
3
- * Do not make direct changes to the file.
4
- */
5
- export {};
@@ -1,5 +0,0 @@
1
- /**
2
- * This file was auto-generated by openapi-typescript.
3
- * Do not make direct changes to the file.
4
- */
5
- export {};
@@ -1,432 +0,0 @@
1
- // Copyright (c) 2025 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
2
- // SPDX-License-Identifier: Apache-2.0
3
- import crypto from 'crypto';
4
- import { randomUUID } from 'node:crypto';
5
- import { readFileSync } from 'node:fs';
6
- import { AllKnownMetaKeys, matchInterfaceIds } from './constants.js';
7
- import { HOLDING_INTERFACE_ID, TRANSFER_INSTRUCTION_INTERFACE_ID, } from '@canton-network/core-token-standard';
8
- import { ErrorInfo, RetryInfo } from '@canton-network/core-ledger-proto';
9
- export function TransactionFilterBySetup(interfaceNames, options = { includeWildcard: false, isMasterUser: false }) {
10
- const interfaceArrayed = Array.isArray(interfaceNames)
11
- ? interfaceNames
12
- : [interfaceNames];
13
- if (options.isMasterUser)
14
- return {
15
- filtersByParty: {},
16
- filtersForAnyParty: filtersForAnyParty(interfaceArrayed, options.includeWildcard ?? false) ?? {},
17
- };
18
- else if (!options.partyId || options.partyId === undefined)
19
- throw new Error('Party must be provided for non-master users');
20
- else
21
- return {
22
- filtersByParty: filtersByParty(options.partyId, interfaceArrayed, options.includeWildcard ?? false) ?? {},
23
- };
24
- }
25
- export function EventFilterBySetup(interfaceNames, options = { includeWildcard: false, isMasterUser: false }) {
26
- const interfaceArrayed = Array.isArray(interfaceNames)
27
- ? interfaceNames
28
- : [interfaceNames];
29
- if (options.isMasterUser)
30
- return {
31
- filtersByParty: {},
32
- filtersForAnyParty: filtersForAnyParty(interfaceArrayed, options.includeWildcard ?? false) ?? {},
33
- verbose: options.verbose ?? false,
34
- };
35
- else if (!options.partyId || options.partyId === undefined)
36
- throw new Error('Party must be provided for non-master users');
37
- else
38
- return {
39
- filtersByParty: filtersByParty(options.partyId, interfaceArrayed, options.includeWildcard ?? false) ?? {},
40
- verbose: options.verbose ?? false,
41
- };
42
- }
43
- function filtersByParty(party, interfaceNames, includeWildcard) {
44
- const wildcardFilter = includeWildcard
45
- ? [
46
- {
47
- identifierFilter: {
48
- WildcardFilter: {
49
- value: {
50
- includeCreatedEventBlob: true,
51
- },
52
- },
53
- },
54
- },
55
- ]
56
- : [];
57
- return {
58
- [party]: {
59
- cumulative: [
60
- ...interfaceNames.map((interfaceName) => {
61
- return {
62
- identifierFilter: {
63
- InterfaceFilter: {
64
- value: {
65
- interfaceId: interfaceName,
66
- includeInterfaceView: true,
67
- includeCreatedEventBlob: true,
68
- },
69
- },
70
- },
71
- };
72
- }),
73
- ...wildcardFilter,
74
- ],
75
- },
76
- };
77
- }
78
- function filtersForAnyParty(interfaceNames, includeWildcard) {
79
- const wildcardFilter = includeWildcard
80
- ? [
81
- {
82
- identifierFilter: {
83
- WildcardFilter: {
84
- value: {
85
- includeCreatedEventBlob: true,
86
- },
87
- },
88
- },
89
- },
90
- ]
91
- : [];
92
- return {
93
- cumulative: [
94
- ...interfaceNames.map((interfaceName) => {
95
- return {
96
- identifierFilter: {
97
- InterfaceFilter: {
98
- value: {
99
- interfaceId: interfaceName,
100
- includeInterfaceView: true,
101
- includeCreatedEventBlob: true,
102
- },
103
- },
104
- },
105
- };
106
- }),
107
- ...wildcardFilter,
108
- ],
109
- };
110
- }
111
- export function hasInterface(interfaceId, event) {
112
- return (event.implementedInterfaces || []).some((id) => matchInterfaceIds(id, interfaceId));
113
- }
114
- export function getInterfaceView(createdEvent) {
115
- const interfaceViews = createdEvent.interfaceViews || null;
116
- return (interfaceViews && interfaceViews[0]) || null;
117
- }
118
- export function getKnownInterfaceView(createdEvent) {
119
- const interfaceView = getInterfaceView(createdEvent);
120
- if (!interfaceView) {
121
- return null;
122
- }
123
- else if (matchInterfaceIds(HOLDING_INTERFACE_ID, interfaceView.interfaceId)) {
124
- return {
125
- type: 'Holding',
126
- viewValue: interfaceView.viewValue,
127
- };
128
- }
129
- else if (matchInterfaceIds(TRANSFER_INSTRUCTION_INTERFACE_ID, interfaceView.interfaceId)) {
130
- return {
131
- type: 'TransferInstruction',
132
- viewValue: interfaceView.viewValue,
133
- };
134
- }
135
- else {
136
- return null;
137
- }
138
- }
139
- // TODO (#563): handle allocations in such a way that any callers have to handle them too
140
- /**
141
- * Use this when `createdEvent` is guaranteed to have an interface view because the ledger api filters
142
- * include it, and thus is guaranteed to be returned by the API.
143
- */
144
- export function ensureInterfaceViewIsPresent(createdEvent, interfaceId) {
145
- const interfaceView = getInterfaceView(createdEvent);
146
- if (!interfaceView) {
147
- throw new Error(`Expected to have interface views, but didn't: ${JSON.stringify(createdEvent)}`);
148
- }
149
- if (!matchInterfaceIds(interfaceId, interfaceView.interfaceId)) {
150
- throw new Error(`Not a ${interfaceId} but a ${interfaceView.interfaceId}: ${JSON.stringify(createdEvent)}`);
151
- }
152
- return interfaceView;
153
- }
154
- export function mergeMetas(event, extra) {
155
- // Add a type assertion to help TypeScript understand the shape of choiceArgument
156
- const choiceArgument = event.choiceArgument;
157
- const lastWriteWins = [
158
- choiceArgument?.transfer?.meta,
159
- choiceArgument?.extraArgs?.meta,
160
- choiceArgument?.meta,
161
- extra,
162
- event.exerciseResult?.meta,
163
- ];
164
- const result = {};
165
- lastWriteWins.forEach((meta) => {
166
- const values = meta?.values || {};
167
- Object.entries(values).forEach(([k, v]) => {
168
- result[k] = v;
169
- });
170
- });
171
- if (Object.keys(result).length === 0) {
172
- return undefined;
173
- }
174
- // order of keys doesn't matter, but we return it consistent for test purposes (and it's nicer)
175
- else {
176
- return { values: result };
177
- }
178
- }
179
- export function getMetaKeyValue(key, meta) {
180
- return (meta?.values || {})[key] || null;
181
- }
182
- /**
183
- * From the view of making it easy to build the display for the wallet,
184
- * we remove all metadata fields that were fully parsed, and whose content is reflected in the TypeScript structure.
185
- * Otherwise, the display code has to do so, overloading the user with superfluous metadata entries.
186
- */
187
- export function removeParsedMetaKeys(meta) {
188
- return {
189
- values: Object.fromEntries(Object.entries(meta?.values || {}).filter(([k]) => !AllKnownMetaKeys.includes(k))),
190
- };
191
- }
192
- //TODO: Investigate, this method is not used anywhere ?
193
- export async function submitExerciseCommand(ledgerClient, exerciseCommand, disclosedContracts, partyId, userId, publicKeyPath, privateKeyPath) {
194
- const submissionId = randomUUID();
195
- const commandId = `tscli-${randomUUID()}`;
196
- const command = {
197
- ExerciseCommand: exerciseCommand,
198
- };
199
- const synchronizerId = getSynchronizerIdFromDisclosedContracts(disclosedContracts);
200
- const prepared = await ledgerClient.postWithRetry('/v2/interactive-submission/prepare', {
201
- actAs: [partyId],
202
- readAs: [partyId],
203
- userId: userId,
204
- commandId,
205
- synchronizerId,
206
- commands: [command],
207
- disclosedContracts,
208
- verboseHashing: true,
209
- packageIdSelectionPreference: [],
210
- });
211
- const signed = signTransaction(publicKeyPath, privateKeyPath, prepared.preparedTransactionHash);
212
- const partySignatures = {
213
- signatures: [
214
- {
215
- party: partyId,
216
- signatures: [
217
- {
218
- signature: signed.signedHash,
219
- signedBy: signed.signedBy,
220
- format: 'SIGNATURE_FORMAT_CONCAT',
221
- signingAlgorithmSpec: 'SIGNING_ALGORITHM_SPEC_ED25519',
222
- },
223
- ],
224
- },
225
- ],
226
- };
227
- const deduplicationPeriod = {
228
- Empty: {},
229
- };
230
- const ledgerEnd = await ledgerClient.getWithRetry('/v2/state/ledger-end');
231
- await ledgerClient.postWithRetry('/v2/interactive-submission/execute', {
232
- userId,
233
- submissionId,
234
- preparedTransaction: prepared.preparedTransaction,
235
- hashingSchemeVersion: prepared.hashingSchemeVersion,
236
- partySignatures,
237
- deduplicationPeriod,
238
- });
239
- const completionPromise = awaitCompletion(ledgerClient, ledgerEnd.offset, partyId, userId, commandId);
240
- return promiseWithTimeout(completionPromise, 45_000 * 2, // 45s
241
- `Timed out getting completion for submission with userId=${userId}, commandId=${commandId}, submissionId=${submissionId}.
242
- The submission might have succeeded or failed, but it couldn't be determined in time.`);
243
- }
244
- // The synchronizer id is mandatory, so we derive it from the disclosed contracts,
245
- // expecting that they'll all be in the same synchronizer
246
- function getSynchronizerIdFromDisclosedContracts(disclosedContracts) {
247
- const synchronizerId = disclosedContracts[0].synchronizerId;
248
- const differentSynchronizerId = disclosedContracts.find((dc) => dc.synchronizerId !== synchronizerId);
249
- if (differentSynchronizerId) {
250
- throw new Error(`Contract is in a different domain so can't submit to the correct synchronizer: ${JSON.stringify(differentSynchronizerId)}`);
251
- }
252
- return synchronizerId;
253
- }
254
- function signTransaction(publicKeyPath, privateKeyPath, preparedTransactionHash) {
255
- const publicKey = readFileSync(publicKeyPath);
256
- const nodePublicKey = crypto.createPublicKey({
257
- key: publicKey,
258
- format: 'der',
259
- type: 'spki', // pycryptodome exports public keys as SPKI
260
- });
261
- const privateKey = readFileSync(privateKeyPath);
262
- const nodePrivateKey = crypto.createPrivateKey({
263
- key: privateKey,
264
- format: 'der',
265
- type: 'pkcs8',
266
- });
267
- const keyFingerprint = crypto
268
- .createHash('sha256')
269
- .update(Buffer.from(`0000000C${nodePublicKey
270
- .export({ format: 'der', type: 'spki' })
271
- // Ed25519 public key is the last 32 bytes of the SPKI DER key
272
- .subarray(-32)
273
- .toString('hex')}`, 'hex'))
274
- .digest('hex');
275
- const fingerprintPreFix = '1220'; // 12 PublicKeyFingerprint, 20 is a special length encoding
276
- const signedBy = `${fingerprintPreFix}${keyFingerprint}`;
277
- const hashBuffer = Buffer.from(preparedTransactionHash, 'base64');
278
- const signedHash = crypto
279
- .sign(null, hashBuffer, {
280
- key: nodePrivateKey,
281
- dsaEncoding: 'ieee-p1363',
282
- })
283
- .toString('base64');
284
- return {
285
- signedBy,
286
- signedHash,
287
- };
288
- }
289
- const COMPLETIONS_LIMIT = '100';
290
- const COMPLETIONS_STREAM_IDLE_TIMEOUT_MS = '1000';
291
- /**
292
- * Polls the completions endpoint until
293
- * the completion with the given (userId, commandId, submissionId) is returned.
294
- * Then returns the updateId, synchronizerId and recordTime of that completion.
295
- */
296
- export async function awaitCompletion(ledgerClient, ledgerEnd, partyId, userId, commandIdOrSubmissionId) {
297
- const responses = await ledgerClient.postWithRetry('/v2/commands/completions', {
298
- userId,
299
- parties: [partyId],
300
- beginExclusive: ledgerEnd,
301
- }, defaultRetryableOptions, {
302
- query: {
303
- limit: COMPLETIONS_LIMIT,
304
- stream_idle_timeout_ms: COMPLETIONS_STREAM_IDLE_TIMEOUT_MS,
305
- },
306
- });
307
- const completions = responses.filter((response) => !!response.completionResponse.Completion);
308
- const wantedCompletion = completions.find((response) => {
309
- const completion = response.completionResponse.Completion;
310
- if (!completion)
311
- return false;
312
- if (completion.value.userId !== userId)
313
- return false;
314
- if (completion.value.commandId === commandIdOrSubmissionId)
315
- return true;
316
- if (completion.value.submissionId === commandIdOrSubmissionId)
317
- return true;
318
- return false;
319
- });
320
- if (wantedCompletion) {
321
- const completion = wantedCompletion.completionResponse.Completion;
322
- const status = completion.value.status;
323
- if (status && status.code !== 0) {
324
- // status.code is 0 for success
325
- throw asGrpcError(status);
326
- }
327
- return completion.value;
328
- }
329
- else {
330
- const lastCompletion = completions[completions.length - 1];
331
- const newLedgerEnd = lastCompletion?.completionResponse.Completion.value.offset;
332
- return awaitCompletion(ledgerClient, newLedgerEnd || ledgerEnd, // !newLedgerEnd implies response was empty
333
- partyId, userId, commandIdOrSubmissionId);
334
- }
335
- }
336
- export async function promiseWithTimeout(promise, timeoutMs, errorMessage) {
337
- let timeoutPid = null;
338
- const timeoutPromise = new Promise((_resolve, reject) => {
339
- timeoutPid = setTimeout(() => reject(errorMessage), timeoutMs);
340
- });
341
- try {
342
- return await Promise.race([promise, timeoutPromise]);
343
- }
344
- finally {
345
- if (timeoutPid) {
346
- clearTimeout(timeoutPid);
347
- }
348
- }
349
- }
350
- export const defaultRetryableOptions = {
351
- retries: 5,
352
- delayMs: 3000,
353
- cantonErrorKeys: [
354
- 'SEQUENCER_REQUEST_FAILED',
355
- 'SEQUENCER_BACKPRESSURE',
356
- 'SUBMISSION_ALREADY_IN_FLIGHT',
357
- 'LOCAL_VERDICT_TIMEOUT',
358
- 'NOT_SEQUENCED_TIMEOUT',
359
- 'NO_VIEW_WITH_VALID_RECIPIENTS',
360
- ],
361
- };
362
- export async function retryable(fn, retryableOptions, logger) {
363
- for (let attempts = 1; attempts <= retryableOptions.retries; attempts++) {
364
- try {
365
- return await fn();
366
- }
367
- catch (err) {
368
- const grpcError = asGrpcError(err);
369
- const message = grpcError.message;
370
- const shouldRetry = retryableOptions.cantonErrorKeys.length === 0 ||
371
- retryableOptions.cantonErrorKeys.some((key) => message.includes(key));
372
- if (attempts < retryableOptions.retries && shouldRetry) {
373
- logger?.warn(`Caught retryiable error: ${message}. Retrying attempt ${attempts} of ${retryableOptions.retries}...`);
374
- await new Promise((res) => setTimeout(res, retryableOptions.delayMs));
375
- // continue to next attempt
376
- }
377
- else {
378
- throw grpcError;
379
- }
380
- }
381
- }
382
- throw new Error('retryable: Exceeded maximum retries without throwing.');
383
- }
384
- // Helper for differentiating ledger errors from others and satisfying TS when checking error properties
385
- export const isJsCantonError = (e) => typeof e === 'object' && e !== null && 'status' in e && 'errorCategory' in e;
386
- export const asGrpcError = (e) => {
387
- let errorInfo = undefined;
388
- let retryInfo = undefined;
389
- let code = 500;
390
- let message = e?.message || '';
391
- if (typeof e === 'object' && e !== null && 'cause' in e) {
392
- message = e.cause;
393
- }
394
- else if (typeof e === 'object' && e !== null && 'message' in e) {
395
- message = e.message;
396
- }
397
- if (typeof e === 'object' &&
398
- e !== null &&
399
- 'code' in e &&
400
- 'message' in e &&
401
- 'details' in e &&
402
- Array.isArray(e.details)) {
403
- code = e.code;
404
- message = e.message;
405
- for (const detail of e.details) {
406
- if (detail.typeUrl === 'type.googleapis.com/google.rpc.ErrorInfo' &&
407
- typeof detail.value === 'string') {
408
- try {
409
- errorInfo = ErrorInfo.fromBinary(Buffer.from(detail.value, 'base64'));
410
- }
411
- catch {
412
- //if parsing fails, we skip adding ErrorInfo
413
- }
414
- }
415
- else if (detail.typeUrl === 'type.googleapis.com/google.rpc.RetryInfo' &&
416
- typeof detail.value === 'string') {
417
- try {
418
- retryInfo = RetryInfo.fromBinary(Buffer.from(detail.value, 'base64'));
419
- }
420
- catch {
421
- //if parsing fails, we skip adding RetryInfo
422
- }
423
- }
424
- }
425
- }
426
- else {
427
- // Not a gRPC error, rethrow
428
- throw e;
429
- }
430
- // Fallback: just return the error message
431
- return { code: code, message: message, errorInfo, retryInfo };
432
- };