@canton-network/core-ledger-client 0.19.0 → 0.20.1

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.
package/dist/index.cjs CHANGED
@@ -1,309 +1,19 @@
1
1
  'use strict';
2
2
 
3
- var crypto = require('crypto');
4
- var coreLedgerProto = require('@canton-network/core-ledger-proto');
5
- var grpcTransport = require('@protobuf-ts/grpc-transport');
6
- var grpcJs = require('@grpc/grpc-js');
7
- var fs = require('fs');
8
3
  var coreTokenStandard = require('@canton-network/core-token-standard');
4
+ var coreLedgerProto = require('@canton-network/core-ledger-proto');
9
5
  var BigNumber = require('bignumber.js');
10
6
  var createClient = require('openapi-fetch');
11
7
  var typescriptLruCache = require('typescript-lru-cache');
12
8
 
13
9
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
14
10
 
15
- var fs__default = /*#__PURE__*/_interopDefault(fs);
16
11
  var BigNumber__default = /*#__PURE__*/_interopDefault(BigNumber);
17
12
  var createClient__default = /*#__PURE__*/_interopDefault(createClient);
18
13
 
19
14
  var __defProp = Object.defineProperty;
20
15
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
21
16
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
- function prefixedInt(value, bytes) {
23
- const buffer = Buffer.alloc(4 + bytes.length);
24
- buffer.writeUInt32BE(value, 0);
25
- Buffer.from(bytes).copy(buffer, 4);
26
- return buffer;
27
- }
28
- function signingPublicKeyFromEd25519(publicKey) {
29
- return {
30
- format: coreLedgerProto.CryptoKeyFormat.RAW,
31
- publicKey: Buffer.from(publicKey, "base64"),
32
- scheme: coreLedgerProto.SigningKeyScheme.ED25519,
33
- keySpec: coreLedgerProto.SigningKeySpec.EC_CURVE25519,
34
- usage: []
35
- };
36
- }
37
- function computeSha256CantonHash(purpose, bytes) {
38
- const hashInput = prefixedInt(purpose, bytes);
39
- const hash = crypto.createHash("sha256").update(hashInput).digest();
40
- const multiprefix = Buffer.from([18, 32]);
41
- return Buffer.concat([multiprefix, hash]).toString("hex");
42
- }
43
- function createGrpcTransport(options) {
44
- const { useTls = false, tls } = options;
45
- if (useTls) {
46
- const readMaybeFile = (value) => typeof value === "string" ? fs__default.default.readFileSync(value) : value;
47
- const rootCert = readMaybeFile(tls?.rootCert);
48
- const clientCert = readMaybeFile(tls?.clientCert);
49
- const clientKey = readMaybeFile(tls?.clientKey);
50
- if (tls?.mutual) {
51
- if (!clientCert || !clientKey) {
52
- throw new Error(
53
- "mTLS enabled but clientCert or clientKey are missing"
54
- );
55
- }
56
- return grpcJs.ChannelCredentials.createSsl(rootCert, clientKey, clientCert);
57
- } else {
58
- return grpcJs.ChannelCredentials.createSsl(rootCert);
59
- }
60
- } else {
61
- return grpcJs.ChannelCredentials.createInsecure();
62
- }
63
- }
64
- var TopologyWriteService = class _TopologyWriteService {
65
- constructor(synchronizerId, userAdminUrl, ledgerClient, accessToken = "", accessTokenProvider, grpcClientOptions) {
66
- this.synchronizerId = synchronizerId;
67
- __publicField(this, "topologyClient");
68
- __publicField(this, "topologyReadService");
69
- __publicField(this, "ledgerClient");
70
- __publicField(this, "accessTokenProvider");
71
- __publicField(this, "accessToken");
72
- __publicField(this, "storeId", () => coreLedgerProto.StoreId.create({
73
- store: {
74
- oneofKind: "synchronizer",
75
- synchronizer: coreLedgerProto.StoreId_Synchronizer.create({
76
- id: this.synchronizerId
77
- })
78
- }
79
- }));
80
- let transport;
81
- if (grpcClientOptions) {
82
- transport = new grpcTransport.GrpcTransport({
83
- host: userAdminUrl,
84
- channelCredentials: createGrpcTransport(grpcClientOptions)
85
- });
86
- } else {
87
- transport = new grpcTransport.GrpcTransport({
88
- host: userAdminUrl,
89
- channelCredentials: grpcJs.ChannelCredentials.createInsecure()
90
- });
91
- }
92
- this.topologyClient = new coreLedgerProto.TopologyManagerWriteServiceClient(transport);
93
- this.topologyReadService = new coreLedgerProto.TopologyManagerReadServiceClient(
94
- transport
95
- );
96
- this.ledgerClient = ledgerClient;
97
- this.accessTokenProvider = accessTokenProvider;
98
- this.accessToken = accessToken;
99
- }
100
- static combineHashes(hashes) {
101
- const sortedHashes = hashes.sort(
102
- (a, b) => a.toString("hex").localeCompare(b.toString("hex"))
103
- );
104
- const combinedHashes = Buffer.alloc(4);
105
- combinedHashes.writeUInt32BE(sortedHashes.length, 0);
106
- let concatenatedHashes = combinedHashes;
107
- for (const h of sortedHashes) {
108
- const lengthBuffer = Buffer.alloc(4);
109
- lengthBuffer.writeUInt32BE(h.length, 0);
110
- concatenatedHashes = Buffer.concat([
111
- concatenatedHashes,
112
- lengthBuffer,
113
- h
114
- ]);
115
- }
116
- const predefineHashPurpose = computeSha256CantonHash(
117
- 55,
118
- concatenatedHashes
119
- );
120
- return Buffer.from(predefineHashPurpose, "hex").toString("base64");
121
- }
122
- static createFingerprintFromKey(publicKey) {
123
- let key;
124
- if (typeof publicKey === "string") {
125
- key = signingPublicKeyFromEd25519(publicKey);
126
- } else {
127
- key = publicKey;
128
- }
129
- const hashPurpose = 12;
130
- return computeSha256CantonHash(hashPurpose, key.publicKey);
131
- }
132
- /** @deprecated only for grpc/protobuf implementation */
133
- static toSignedTopologyTransaction(txHashes, serializedTransaction, signature, namespace) {
134
- return coreLedgerProto.SignedTopologyTransaction.create({
135
- transaction: serializedTransaction,
136
- proposal: true,
137
- signatures: [],
138
- multiTransactionSignatures: [
139
- coreLedgerProto.MultiTransactionSignatures.create({
140
- transactionHashes: txHashes,
141
- signatures: [
142
- coreLedgerProto.Signature.create({
143
- format: coreLedgerProto.SignatureFormat.RAW,
144
- signature: Buffer.from(signature, "base64"),
145
- signedBy: namespace,
146
- signingAlgorithmSpec: coreLedgerProto.SigningAlgorithmSpec.ED25519
147
- })
148
- ]
149
- })
150
- ]
151
- });
152
- }
153
- /** @deprecated */
154
- generateTransactionsRequest(namespace, partyId, publicKey, confirmingThreshold = 1, hostingParticipantRights) {
155
- const namespaceDelegation = coreLedgerProto.TopologyMapping.create({
156
- mapping: {
157
- oneofKind: "namespaceDelegation",
158
- namespaceDelegation: coreLedgerProto.NamespaceDelegation.create({
159
- namespace,
160
- targetKey: publicKey,
161
- isRootDelegation: true,
162
- restriction: {
163
- oneofKind: void 0
164
- }
165
- })
166
- }
167
- });
168
- const hostingParticipants = [...hostingParticipantRights].map(
169
- ([participantUid, permission]) => coreLedgerProto.PartyToParticipant_HostingParticipant.create({
170
- participantUid,
171
- permission
172
- })
173
- );
174
- const partyToParticipant = coreLedgerProto.TopologyMapping.create({
175
- mapping: {
176
- oneofKind: "partyToParticipant",
177
- partyToParticipant: coreLedgerProto.PartyToParticipant.create({
178
- party: partyId,
179
- threshold: confirmingThreshold,
180
- participants: hostingParticipants
181
- })
182
- }
183
- });
184
- const partyToKeyMapping = coreLedgerProto.TopologyMapping.create({
185
- mapping: {
186
- oneofKind: "partyToKeyMapping",
187
- partyToKeyMapping: coreLedgerProto.PartyToKeyMapping.create({
188
- party: partyId,
189
- threshold: 1,
190
- signingKeys: [publicKey]
191
- })
192
- }
193
- });
194
- return coreLedgerProto.GenerateTransactionsRequest.create({
195
- proposals: [
196
- namespaceDelegation,
197
- partyToParticipant,
198
- partyToKeyMapping
199
- ].map(
200
- (mapping) => coreLedgerProto.GenerateTransactionsRequest_Proposal.create({
201
- mapping,
202
- serial: 1,
203
- store: this.storeId(),
204
- operation: coreLedgerProto.Enums_TopologyChangeOp.ADD_REPLACE
205
- })
206
- )
207
- });
208
- }
209
- /** @deprecated use allocateExternalParty() instead */
210
- async submitExternalPartyTopology(signedTopologyTxs, partyId) {
211
- await this.addTransactions(signedTopologyTxs);
212
- await this.authorizePartyToParticipant(partyId);
213
- }
214
- /** @deprecated use generateTopology() */
215
- async generateTransactions(publicKey, partyId, confirmingThreshold = 1, hostingParticipantRights) {
216
- const signingPublicKey = signingPublicKeyFromEd25519(publicKey);
217
- const namespace = _TopologyWriteService.createFingerprintFromKey(signingPublicKey);
218
- let participantRights = hostingParticipantRights;
219
- if (!participantRights || participantRights.size === 0) {
220
- const { participantId } = await this.ledgerClient.getWithRetry(
221
- "/v2/parties/participant-id"
222
- );
223
- participantRights = /* @__PURE__ */ new Map([
224
- [participantId, coreLedgerProto.Enums_ParticipantPermission.CONFIRMATION]
225
- ]);
226
- }
227
- const req = this.generateTransactionsRequest(
228
- namespace,
229
- partyId,
230
- signingPublicKey,
231
- confirmingThreshold,
232
- participantRights
233
- );
234
- const adminAccessToken = this.accessTokenProvider ? await this.accessTokenProvider.getAdminAccessToken() : this.accessToken;
235
- return this.topologyClient.generateTransactions(req, {
236
- meta: {
237
- Authorization: `Bearer ${adminAccessToken}`
238
- }
239
- }).response;
240
- }
241
- /** @deprecated */
242
- async addTransactions(signedTopologyTxs) {
243
- const request = coreLedgerProto.AddTransactionsRequest.create({
244
- transactions: signedTopologyTxs,
245
- forceChanges: [],
246
- store: this.storeId()
247
- });
248
- const adminAccessToken = this.accessTokenProvider ? await this.accessTokenProvider.getAdminAccessToken() : this.accessToken;
249
- return this.topologyClient.addTransactions(request, {
250
- meta: {
251
- Authorization: `Bearer ${adminAccessToken}`
252
- }
253
- }).response;
254
- }
255
- /** @deprecated */
256
- async waitForPartyToParticipantProposal(partyId) {
257
- let counter = 0;
258
- return new Promise((resolve, reject) => {
259
- const interval = setInterval(async () => {
260
- const result = await this.topologyReadService.listPartyToParticipant(
261
- coreLedgerProto.ListPartyToParticipantRequest.create({
262
- baseQuery: coreLedgerProto.BaseQuery.create({
263
- store: this.storeId(),
264
- proposals: true,
265
- timeQuery: {
266
- oneofKind: "headState",
267
- headState: coreLedgerProto.Empty.create()
268
- }
269
- }),
270
- filterParty: partyId
271
- })
272
- );
273
- if (result.response.results.length > 0) {
274
- clearInterval(interval);
275
- resolve(result.response.results[0].context?.transactionHash);
276
- }
277
- counter += 1;
278
- if (counter > 10) {
279
- clearInterval(interval);
280
- reject("Timeout waiting for party to participant proposal");
281
- }
282
- }, 1e3);
283
- });
284
- }
285
- /** @deprecated */
286
- async authorizePartyToParticipant(partyId) {
287
- const hash = await this.waitForPartyToParticipantProposal(partyId);
288
- if (!hash) {
289
- throw new Error("No topology transaction found for authorization");
290
- }
291
- const request = coreLedgerProto.AuthorizeRequest.create({
292
- type: {
293
- oneofKind: "transactionHash",
294
- transactionHash: Buffer.from(hash).toString("hex")
295
- },
296
- mustFullyAuthorize: false,
297
- store: this.storeId()
298
- });
299
- const adminAccessToken = this.accessTokenProvider ? await this.accessTokenProvider.getAdminAccessToken() : this.accessToken;
300
- return this.topologyClient.authorize(request, {
301
- meta: {
302
- Authorization: `Bearer ${adminAccessToken}`
303
- }
304
- }).response;
305
- }
306
- };
307
17
  function splitInterfaceId(interfaceId) {
308
18
  const regExp = /^#?([^:]+):([^:]+):([^:]+)$/;
309
19
  const match = regExp.exec(interfaceId);
@@ -1582,6 +1292,10 @@ var CoreService = class _CoreService {
1582
1292
  fetchedAtOffset: offset
1583
1293
  };
1584
1294
  }
1295
+ toQualifiedMemberId(memberId) {
1296
+ if (!memberId) throw new Error("memberId is required");
1297
+ return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
1298
+ }
1585
1299
  };
1586
1300
  var AllocationService = class {
1587
1301
  constructor(core, logger) {
@@ -2162,12 +1876,13 @@ var TransferService = class {
2162
1876
  }
2163
1877
  };
2164
1878
  var TokenStandardService = class {
2165
- constructor(ledgerClient, scanProxyClient, logger, accessTokenProvider, isMasterUser) {
1879
+ constructor(ledgerClient, scanProxyClient, logger, accessTokenProvider, isMasterUser, scanClient) {
2166
1880
  this.ledgerClient = ledgerClient;
2167
1881
  this.scanProxyClient = scanProxyClient;
2168
1882
  this.logger = logger;
2169
1883
  this.accessTokenProvider = accessTokenProvider;
2170
1884
  this.isMasterUser = isMasterUser;
1885
+ this.scanClient = scanClient;
2171
1886
  __publicField(this, "core");
2172
1887
  __publicField(this, "allocation");
2173
1888
  __publicField(this, "transfer");
@@ -2176,7 +1891,9 @@ var TokenStandardService = class {
2176
1891
  scanProxyClient,
2177
1892
  logger,
2178
1893
  accessTokenProvider,
2179
- isMasterUser
1894
+ isMasterUser,
1895
+ void 0,
1896
+ void 0
2180
1897
  );
2181
1898
  this.allocation = new AllocationService(this.core, this.logger);
2182
1899
  this.transfer = new TransferService(this.core, this.logger);
@@ -2265,7 +1982,7 @@ var TokenStandardService = class {
2265
1982
  value: cid
2266
1983
  })),
2267
1984
  provider,
2268
- memberId,
1985
+ memberId: this.core.toQualifiedMemberId(memberId),
2269
1986
  synchronizerId,
2270
1987
  migrationId,
2271
1988
  trafficAmount,
@@ -2279,6 +1996,20 @@ var TokenStandardService = class {
2279
1996
  };
2280
1997
  return [exercise, disclosed];
2281
1998
  }
1999
+ async getMemberTrafficStatus(domainId, memberId) {
2000
+ if (!this.scanClient) {
2001
+ throw new Error("Scan API URL was not provided");
2002
+ }
2003
+ return this.scanClient.get(
2004
+ "/v0/domains/{domain_id}/members/{member_id}/traffic-status",
2005
+ {
2006
+ path: {
2007
+ domain_id: domainId,
2008
+ member_id: this.core.toQualifiedMemberId(memberId)
2009
+ }
2010
+ }
2011
+ );
2012
+ }
2282
2013
  async getInstrumentAdmin(registryUrl) {
2283
2014
  const client = this.core.getTokenStandardClient(registryUrl);
2284
2015
  const info = await client.get("/registry/metadata/v1/info");
@@ -3013,7 +2744,16 @@ var ACSHelper = class _ACSHelper {
3013
2744
  // src/ledger-client.ts
3014
2745
  var supportedVersions = ["3.3", "3.4"];
3015
2746
  var LedgerClient = class {
3016
- constructor(baseUrl, _logger, isAdmin = false, accessToken, accessTokenProvider, version, acsHelperOptions) {
2747
+ constructor({
2748
+ baseUrl,
2749
+ logger,
2750
+ isAdmin,
2751
+ accessToken,
2752
+ accessTokenProvider,
2753
+ version,
2754
+ acsHelperOptions,
2755
+ ...options
2756
+ }) {
3017
2757
  // privately manage the active connected version and associated client codegen
3018
2758
  __publicField(this, "clients");
3019
2759
  __publicField(this, "clientVersion", "3.4");
@@ -3023,39 +2763,32 @@ var LedgerClient = class {
3023
2763
  __publicField(this, "accessTokenProvider");
3024
2764
  __publicField(this, "acsHelper");
3025
2765
  __publicField(this, "logger");
2766
+ __publicField(this, "synchronizerId");
3026
2767
  __publicField(this, "baseUrl");
3027
- this.logger = _logger.child({ component: "LedgerClient" });
2768
+ this.logger = logger.child({ component: "LedgerClient" });
3028
2769
  this.accessTokenProvider = accessTokenProvider;
2770
+ const baseFetch = options.fetch ?? fetch;
2771
+ const authenticatedFetch = async (url, options2 = {}) => {
2772
+ let token = accessToken;
2773
+ if (this.accessTokenProvider) {
2774
+ token = isAdmin ?? false ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
2775
+ }
2776
+ return baseFetch(url, {
2777
+ ...options2,
2778
+ headers: {
2779
+ ...options2.headers || {},
2780
+ ...token && { Authorization: `Bearer ${token}` }
2781
+ }
2782
+ });
2783
+ };
3029
2784
  this.clients = {
3030
2785
  "3.3": createClient__default.default({
3031
2786
  baseUrl: baseUrl.href,
3032
- fetch: async (url, options = {}) => {
3033
- if (this.accessTokenProvider) {
3034
- accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
3035
- }
3036
- return fetch(url, {
3037
- ...options,
3038
- headers: {
3039
- ...options.headers || {},
3040
- Authorization: `Bearer ${accessToken}`
3041
- }
3042
- });
3043
- }
2787
+ fetch: authenticatedFetch
3044
2788
  }),
3045
2789
  "3.4": createClient__default.default({
3046
2790
  baseUrl: baseUrl.href,
3047
- fetch: async (url, options = {}) => {
3048
- if (this.accessTokenProvider) {
3049
- accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
3050
- }
3051
- return fetch(url, {
3052
- ...options,
3053
- headers: {
3054
- ...options.headers || {},
3055
- Authorization: `Bearer ${accessToken}`
3056
- }
3057
- });
3058
- }
2791
+ fetch: authenticatedFetch
3059
2792
  })
3060
2793
  };
3061
2794
  this.clientVersion = version ?? this.clientVersion;
@@ -3063,7 +2796,7 @@ var LedgerClient = class {
3063
2796
  this.baseUrl = baseUrl;
3064
2797
  this.acsHelper = new ACSHelper(
3065
2798
  this,
3066
- _logger,
2799
+ logger,
3067
2800
  acsHelperOptions,
3068
2801
  SharedACSCache
3069
2802
  );
@@ -3190,20 +2923,23 @@ var LedgerClient = class {
3190
2923
  *
3191
2924
  * @param userId The ID of the user to grant rights to.
3192
2925
  * @param partyId The ID of the party to grant rights for.
2926
+ * @param maxTries Optional max number of retries with default 30. May be increased if expecting heavy load.
2927
+ * @param retryIntervalMs Optional interval between retries to verify that party exists with default 2000ms. May be increased if expecting heavy load.
3193
2928
  * @returns A promise that resolves when the rights have been granted.
3194
2929
  */
3195
- async waitForPartyAndGrantUserRights(userId, partyId) {
2930
+ async waitForPartyAndGrantUserRights(userId, partyId, maxTries = 30, retryIntervalMs = 2e3) {
3196
2931
  await this.init();
3197
2932
  let partyFound = false;
3198
2933
  let tries = 0;
3199
- const maxTries = 30;
3200
2934
  while (!partyFound && tries < maxTries) {
3201
2935
  partyFound = await this.checkIfPartyExists(partyId);
3202
- await new Promise((resolve) => setTimeout(resolve, 2e3));
2936
+ await new Promise((resolve) => setTimeout(resolve, retryIntervalMs));
3203
2937
  tries++;
3204
2938
  }
3205
2939
  if (tries >= maxTries) {
3206
- throw new Error("timed out waiting for new party to appear");
2940
+ throw new Error(
2941
+ `timed out waiting for new party to appear after ${maxTries} tries`
2942
+ );
3207
2943
  }
3208
2944
  const result = await this.grantRights(userId, {
3209
2945
  actAs: [partyId]
@@ -3461,6 +3197,25 @@ var LedgerClient = class {
3461
3197
  }
3462
3198
  return filter;
3463
3199
  }
3200
+ // Retrieve an (arbitrary) synchronizer id from the validator.
3201
+ // This synchronizer id is cached for the remainder of this object's life.
3202
+ async getSynchronizerId() {
3203
+ if (this.synchronizerId) return this.synchronizerId;
3204
+ const response = await this.getWithRetry(
3205
+ "/v2/state/connected-synchronizers"
3206
+ );
3207
+ if (!response.connectedSynchronizers?.[0]) {
3208
+ throw new Error("No connected synchronizers found");
3209
+ }
3210
+ const synchronizerId = response.connectedSynchronizers[0].synchronizerId;
3211
+ if (response.connectedSynchronizers.length > 1) {
3212
+ this.logger.warn(
3213
+ `Found ${response.connectedSynchronizers.length} synchronizers, defaulting to ${synchronizerId}`
3214
+ );
3215
+ }
3216
+ this.synchronizerId = synchronizerId;
3217
+ return synchronizerId;
3218
+ }
3464
3219
  async postWithRetry(path, body, retryOptions = defaultRetryableOptions, params, additionalOptions) {
3465
3220
  return await retryable(
3466
3221
  () => this.post(path, body, params, additionalOptions),
@@ -3546,7 +3301,6 @@ exports.ACS_UPDATE_CONFIG = ACS_UPDATE_CONFIG;
3546
3301
  exports.CoreService = CoreService;
3547
3302
  exports.LedgerClient = LedgerClient;
3548
3303
  exports.TokenStandardService = TokenStandardService;
3549
- exports.TopologyWriteService = TopologyWriteService;
3550
3304
  exports.WSSupportWithBackOffSwitch = WSSupportWithBackOffSwitch;
3551
3305
  exports.asJsCantonError = asJsCantonError;
3552
3306
  exports.awaitCompletion = awaitCompletion;