@canton-network/core-ledger-client 0.20.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.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- export * from './topology-write-service.js';
2
1
  export * from './token-standard-service.js';
3
2
  export * from './ledger-client.js';
4
3
  export * from './generated-clients/openapi-3.3.0-SNAPSHOT.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,6BAA6B,CAAA;AAC3C,cAAc,6BAA6B,CAAA;AAC3C,cAAc,oBAAoB,CAAA;AAClC,cAAc,+CAA+C,CAAA;AAC7D,cAAc,wBAAwB,CAAA;AACtC,cAAc,qBAAqB,CAAA;AACnC,YAAY,EACR,WAAW,EACX,kBAAkB,EAClB,OAAO,EACP,WAAW,EACX,cAAc,EACd,qBAAqB,EACrB,uBAAuB,EACvB,mBAAmB,EACnB,kBAAkB,EAClB,cAAc,EACd,SAAS,EACT,KAAK,EACL,UAAU,EACV,WAAW,EACX,UAAU,EACV,IAAI,EACJ,IAAI,EACJ,MAAM,EACN,UAAU,EACV,UAAU,EACV,SAAS,GACZ,MAAM,oBAAoB,CAAA;AAE3B,OAAO,EACH,eAAe,EACf,kBAAkB,EAClB,eAAe,EACf,eAAe,EACf,aAAa,EACb,uBAAuB,GAC1B,MAAM,uBAAuB,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAGA,cAAc,6BAA6B,CAAA;AAC3C,cAAc,oBAAoB,CAAA;AAClC,cAAc,+CAA+C,CAAA;AAC7D,cAAc,wBAAwB,CAAA;AACtC,cAAc,qBAAqB,CAAA;AACnC,YAAY,EACR,WAAW,EACX,kBAAkB,EAClB,OAAO,EACP,WAAW,EACX,cAAc,EACd,qBAAqB,EACrB,uBAAuB,EACvB,mBAAmB,EACnB,kBAAkB,EAClB,cAAc,EACd,SAAS,EACT,KAAK,EACL,UAAU,EACV,WAAW,EACX,UAAU,EACV,IAAI,EACJ,IAAI,EACJ,MAAM,EACN,UAAU,EACV,UAAU,EACV,SAAS,GACZ,MAAM,oBAAoB,CAAA;AAE3B,OAAO,EACH,eAAe,EACf,kBAAkB,EAClB,eAAe,EACf,eAAe,EACf,aAAa,EACb,uBAAuB,GAC1B,MAAM,uBAAuB,CAAA"}
package/dist/index.js CHANGED
@@ -1,9 +1,5 @@
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
1
  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';
2
+ import { ErrorInfo, RetryInfo } from '@canton-network/core-ledger-proto';
7
3
  import BigNumber from 'bignumber.js';
8
4
  import createClient from 'openapi-fetch';
9
5
  import { LRUCache } from 'typescript-lru-cache';
@@ -11,291 +7,6 @@ import { LRUCache } from 'typescript-lru-cache';
11
7
  var __defProp = Object.defineProperty;
12
8
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
13
9
  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
10
  function splitInterfaceId(interfaceId) {
300
11
  const regExp = /^#?([^:]+):([^:]+):([^:]+)$/;
301
12
  const match = regExp.exec(interfaceId);
@@ -3026,7 +2737,16 @@ var ACSHelper = class _ACSHelper {
3026
2737
  // src/ledger-client.ts
3027
2738
  var supportedVersions = ["3.3", "3.4"];
3028
2739
  var LedgerClient = class {
3029
- constructor(baseUrl, _logger, isAdmin = false, accessToken, accessTokenProvider, version, acsHelperOptions) {
2740
+ constructor({
2741
+ baseUrl,
2742
+ logger,
2743
+ isAdmin,
2744
+ accessToken,
2745
+ accessTokenProvider,
2746
+ version,
2747
+ acsHelperOptions,
2748
+ ...options
2749
+ }) {
3030
2750
  // privately manage the active connected version and associated client codegen
3031
2751
  __publicField(this, "clients");
3032
2752
  __publicField(this, "clientVersion", "3.4");
@@ -3038,38 +2758,30 @@ var LedgerClient = class {
3038
2758
  __publicField(this, "logger");
3039
2759
  __publicField(this, "synchronizerId");
3040
2760
  __publicField(this, "baseUrl");
3041
- this.logger = _logger.child({ component: "LedgerClient" });
2761
+ this.logger = logger.child({ component: "LedgerClient" });
3042
2762
  this.accessTokenProvider = accessTokenProvider;
2763
+ const baseFetch = options.fetch ?? fetch;
2764
+ const authenticatedFetch = async (url, options2 = {}) => {
2765
+ let token = accessToken;
2766
+ if (this.accessTokenProvider) {
2767
+ token = isAdmin ?? false ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
2768
+ }
2769
+ return baseFetch(url, {
2770
+ ...options2,
2771
+ headers: {
2772
+ ...options2.headers || {},
2773
+ ...token && { Authorization: `Bearer ${token}` }
2774
+ }
2775
+ });
2776
+ };
3043
2777
  this.clients = {
3044
2778
  "3.3": createClient({
3045
2779
  baseUrl: baseUrl.href,
3046
- fetch: async (url, options = {}) => {
3047
- if (this.accessTokenProvider) {
3048
- accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
3049
- }
3050
- return fetch(url, {
3051
- ...options,
3052
- headers: {
3053
- ...options.headers || {},
3054
- Authorization: `Bearer ${accessToken}`
3055
- }
3056
- });
3057
- }
2780
+ fetch: authenticatedFetch
3058
2781
  }),
3059
2782
  "3.4": createClient({
3060
2783
  baseUrl: baseUrl.href,
3061
- fetch: async (url, options = {}) => {
3062
- if (this.accessTokenProvider) {
3063
- accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
3064
- }
3065
- return fetch(url, {
3066
- ...options,
3067
- headers: {
3068
- ...options.headers || {},
3069
- Authorization: `Bearer ${accessToken}`
3070
- }
3071
- });
3072
- }
2784
+ fetch: authenticatedFetch
3073
2785
  })
3074
2786
  };
3075
2787
  this.clientVersion = version ?? this.clientVersion;
@@ -3077,7 +2789,7 @@ var LedgerClient = class {
3077
2789
  this.baseUrl = baseUrl;
3078
2790
  this.acsHelper = new ACSHelper(
3079
2791
  this,
3080
- _logger,
2792
+ logger,
3081
2793
  acsHelperOptions,
3082
2794
  SharedACSCache
3083
2795
  );
@@ -3204,20 +2916,23 @@ var LedgerClient = class {
3204
2916
  *
3205
2917
  * @param userId The ID of the user to grant rights to.
3206
2918
  * @param partyId The ID of the party to grant rights for.
2919
+ * @param maxTries Optional max number of retries with default 30. May be increased if expecting heavy load.
2920
+ * @param retryIntervalMs Optional interval between retries to verify that party exists with default 2000ms. May be increased if expecting heavy load.
3207
2921
  * @returns A promise that resolves when the rights have been granted.
3208
2922
  */
3209
- async waitForPartyAndGrantUserRights(userId, partyId) {
2923
+ async waitForPartyAndGrantUserRights(userId, partyId, maxTries = 30, retryIntervalMs = 2e3) {
3210
2924
  await this.init();
3211
2925
  let partyFound = false;
3212
2926
  let tries = 0;
3213
- const maxTries = 30;
3214
2927
  while (!partyFound && tries < maxTries) {
3215
2928
  partyFound = await this.checkIfPartyExists(partyId);
3216
- await new Promise((resolve) => setTimeout(resolve, 2e3));
2929
+ await new Promise((resolve) => setTimeout(resolve, retryIntervalMs));
3217
2930
  tries++;
3218
2931
  }
3219
2932
  if (tries >= maxTries) {
3220
- throw new Error("timed out waiting for new party to appear");
2933
+ throw new Error(
2934
+ `timed out waiting for new party to appear after ${maxTries} tries`
2935
+ );
3221
2936
  }
3222
2937
  const result = await this.grantRights(userId, {
3223
2938
  actAs: [partyId]
@@ -3574,6 +3289,6 @@ var WSSupportWithBackOffSwitch = class {
3574
3289
  }
3575
3290
  };
3576
3291
 
3577
- export { ACSContainer, ACS_UPDATE_CONFIG, CoreService, LedgerClient, TokenStandardService, TopologyWriteService, WSSupportWithBackOffSwitch, asJsCantonError, awaitCompletion, defaultRetryableOptions, isJsCantonError, promiseWithTimeout, supportedVersions };
3292
+ export { ACSContainer, ACS_UPDATE_CONFIG, CoreService, LedgerClient, TokenStandardService, WSSupportWithBackOffSwitch, asJsCantonError, awaitCompletion, defaultRetryableOptions, isJsCantonError, promiseWithTimeout, supportedVersions };
3578
3293
  //# sourceMappingURL=index.js.map
3579
3294
  //# sourceMappingURL=index.js.map