@canton-network/core-ledger-client 0.20.0 → 0.20.2

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);
@@ -1399,9 +1109,8 @@ var MEMO_KEY = "splice.lfdecentralizedtrust.org/reason";
1399
1109
  var REQUESTED_AT_SKEW_MS = 6e4;
1400
1110
  var EMPTY_META = { values: {} };
1401
1111
  var CoreService = class _CoreService {
1402
- constructor(ledgerClient, scanProxyClient, logger, accessTokenProvider, isMasterUser, isAdmin = false, accessToken = "") {
1112
+ constructor(ledgerClient, logger, accessTokenProvider, isMasterUser, isAdmin = false, accessToken = "") {
1403
1113
  this.ledgerClient = ledgerClient;
1404
- this.scanProxyClient = scanProxyClient;
1405
1114
  this.logger = logger;
1406
1115
  this.accessTokenProvider = accessTokenProvider;
1407
1116
  this.isMasterUser = isMasterUser;
@@ -1417,6 +1126,7 @@ var CoreService = class _CoreService {
1417
1126
  this.accessTokenProvider
1418
1127
  );
1419
1128
  }
1129
+ // TODO: probably needs a filter by instrument ID as well?
1420
1130
  async getInputHoldingsCids(sender, inputUtxos, amount) {
1421
1131
  const now = /* @__PURE__ */ new Date();
1422
1132
  if (inputUtxos && inputUtxos.length > 0) {
@@ -2166,19 +1876,16 @@ var TransferService = class {
2166
1876
  }
2167
1877
  };
2168
1878
  var TokenStandardService = class {
2169
- constructor(ledgerClient, scanProxyClient, logger, accessTokenProvider, isMasterUser, scanClient) {
1879
+ constructor(ledgerClient, logger, accessTokenProvider, isMasterUser) {
2170
1880
  this.ledgerClient = ledgerClient;
2171
- this.scanProxyClient = scanProxyClient;
2172
1881
  this.logger = logger;
2173
1882
  this.accessTokenProvider = accessTokenProvider;
2174
1883
  this.isMasterUser = isMasterUser;
2175
- this.scanClient = scanClient;
2176
1884
  __publicField(this, "core");
2177
1885
  __publicField(this, "allocation");
2178
1886
  __publicField(this, "transfer");
2179
1887
  this.core = new CoreService(
2180
1888
  ledgerClient,
2181
- scanProxyClient,
2182
1889
  logger,
2183
1890
  accessTokenProvider,
2184
1891
  isMasterUser,
@@ -2188,28 +1895,6 @@ var TokenStandardService = class {
2188
1895
  this.allocation = new AllocationService(this.core, this.logger);
2189
1896
  this.transfer = new TransferService(this.core, this.logger);
2190
1897
  }
2191
- async getTransferPreApprovalByParty(partyId) {
2192
- const { transfer_preapproval } = await this.scanProxyClient.get(
2193
- "/v0/scan-proxy/transfer-preapprovals/by-party/{party}",
2194
- {
2195
- path: {
2196
- party: partyId
2197
- }
2198
- }
2199
- );
2200
- return transfer_preapproval;
2201
- }
2202
- async getFeaturedAppsByParty(partyId) {
2203
- const { featured_app_right } = await this.scanProxyClient.get(
2204
- "/v0/scan-proxy/featured-apps/{provider_party_id}",
2205
- {
2206
- path: {
2207
- provider_party_id: partyId
2208
- }
2209
- }
2210
- );
2211
- return featured_app_right;
2212
- }
2213
1898
  async getInstrumentById(registryUrl, instrumentId) {
2214
1899
  try {
2215
1900
  const params = {
@@ -2229,77 +1914,6 @@ var TokenStandardService = class {
2229
1914
  );
2230
1915
  }
2231
1916
  }
2232
- async buyMemberTraffic(dso, provider, trafficAmount, synchronizerId, memberId, migrationId, inputUtxos) {
2233
- const amuletRules = await this.scanProxyClient.getAmuletRules();
2234
- const activeRound = await this.scanProxyClient.getActiveOpenMiningRound();
2235
- const inputHoldings = await this.core.getInputHoldingsCids(
2236
- provider,
2237
- inputUtxos,
2238
- trafficAmount
2239
- );
2240
- if (!amuletRules) {
2241
- throw new Error("AmuletRules contract not found");
2242
- }
2243
- if (!activeRound) {
2244
- throw new Error(
2245
- "OpenMiningRound active at current moment not found"
2246
- );
2247
- }
2248
- const disclosed = [
2249
- {
2250
- templateId: amuletRules.template_id,
2251
- contractId: amuletRules.contract_id,
2252
- createdEventBlob: amuletRules.created_event_blob,
2253
- synchronizerId
2254
- },
2255
- {
2256
- templateId: activeRound.template_id,
2257
- contractId: activeRound.contract_id,
2258
- createdEventBlob: activeRound.created_event_blob,
2259
- synchronizerId
2260
- }
2261
- ];
2262
- const context = {
2263
- openMiningRound: activeRound.contract_id,
2264
- issuingMiningRounds: [],
2265
- validatorRights: [],
2266
- featuredAppRight: null
2267
- };
2268
- const choiceArgs = {
2269
- context,
2270
- inputs: inputHoldings.map((cid) => ({
2271
- tag: "InputAmulet",
2272
- value: cid
2273
- })),
2274
- provider,
2275
- memberId: this.core.toQualifiedMemberId(memberId),
2276
- synchronizerId,
2277
- migrationId,
2278
- trafficAmount,
2279
- expectedDso: dso
2280
- };
2281
- const exercise = {
2282
- templateId: "#splice-amulet:Splice.AmuletRules:AmuletRules",
2283
- contractId: amuletRules.contract_id,
2284
- choice: "AmuletRules_BuyMemberTraffic",
2285
- choiceArgument: choiceArgs
2286
- };
2287
- return [exercise, disclosed];
2288
- }
2289
- async getMemberTrafficStatus(domainId, memberId) {
2290
- if (!this.scanClient) {
2291
- throw new Error("Scan API URL was not provided");
2292
- }
2293
- return this.scanClient.get(
2294
- "/v0/domains/{domain_id}/members/{member_id}/traffic-status",
2295
- {
2296
- path: {
2297
- domain_id: domainId,
2298
- member_id: this.core.toQualifiedMemberId(memberId)
2299
- }
2300
- }
2301
- );
2302
- }
2303
1917
  async getInstrumentAdmin(registryUrl) {
2304
1918
  const client = this.core.getTokenStandardClient(registryUrl);
2305
1919
  const info = await client.get("/registry/metadata/v1/info");
@@ -2385,8 +1999,8 @@ var TokenStandardService = class {
2385
1999
  this.ledgerClient
2386
2000
  );
2387
2001
  }
2388
- async getInputHoldingsCids(sender, inputUtxos) {
2389
- return this.core.getInputHoldingsCids(sender, inputUtxos);
2002
+ async getInputHoldingsCids(sender, inputUtxos, amount) {
2003
+ return this.core.getInputHoldingsCids(sender, inputUtxos, amount);
2390
2004
  }
2391
2005
  async createDelegateProxyTranfser(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, featuredAppRightCid, proxyCid, beneficiaries, inputUtxos, memo, expiryDate, meta) {
2392
2006
  const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(
@@ -2424,58 +2038,136 @@ var TokenStandardService = class {
2424
2038
  };
2425
2039
  return [exercise, disclosedContracts];
2426
2040
  }
2427
- // TODO(#583) as it's not a part of token standard, should be moved somewhere else
2428
- async createTap(receiver, amount, instrumentAdmin, instrumentId, registryUrl) {
2429
- const now = /* @__PURE__ */ new Date();
2430
- const tomorrow = new Date(now);
2431
- tomorrow.setDate(tomorrow.getDate() + 1);
2041
+ async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
2042
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(
2043
+ transferInstructionCid,
2044
+ registryUrl
2045
+ );
2432
2046
  const choiceArgs = {
2433
- expectedAdmin: instrumentAdmin,
2434
- transfer: {
2435
- sender: instrumentAdmin,
2436
- receiver,
2437
- amount,
2438
- instrumentId: { admin: instrumentAdmin, id: instrumentId },
2439
- lock: null,
2440
- requestedAt: new Date(
2441
- Date.now() - REQUESTED_AT_SKEW_MS
2442
- ).toISOString(),
2443
- executeBefore: tomorrow.toISOString(),
2444
- inputHoldingCids: [],
2445
- meta: { values: {} }
2446
- },
2447
- extraArgs: {
2448
- context: { values: {} },
2449
- meta: { values: {} }
2047
+ cid: acceptTransferInstructionContext.contractId,
2048
+ proxyArg: {
2049
+ featuredAppRightCid,
2050
+ beneficiaries: [
2051
+ {
2052
+ beneficiary: exchangeParty,
2053
+ weight: 1
2054
+ }
2055
+ ],
2056
+ choiceArg: acceptTransferInstructionContext.choiceArgument
2450
2057
  }
2451
2058
  };
2452
- const transferFactory = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
2453
- choiceArguments: choiceArgs
2454
- });
2455
- const disclosedContracts = transferFactory.choiceContext.disclosedContracts;
2059
+ return [
2060
+ {
2061
+ templateId: "#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy",
2062
+ contractId: proxyCid,
2063
+ choice: "DelegateProxy_TransferInstruction_Accept",
2064
+ choiceArgument: choiceArgs
2065
+ },
2066
+ disclosedContracts
2067
+ ];
2068
+ }
2069
+ };
2070
+
2071
+ // src/amulet-service.ts
2072
+ var REQUESTED_AT_SKEW_MS2 = 6e4;
2073
+ var AmuletService = class {
2074
+ constructor(tokenStandard, scanProxyClient, scanClient) {
2075
+ this.tokenStandard = tokenStandard;
2076
+ this.scanProxyClient = scanProxyClient;
2077
+ this.scanClient = scanClient;
2078
+ }
2079
+ async getTransferPreApprovalByParty(partyId) {
2080
+ const { transfer_preapproval } = await this.scanProxyClient.get(
2081
+ "/v0/scan-proxy/transfer-preapprovals/by-party/{party}",
2082
+ {
2083
+ path: {
2084
+ party: partyId
2085
+ }
2086
+ }
2087
+ );
2088
+ return transfer_preapproval;
2089
+ }
2090
+ async getFeaturedAppsByParty(partyId) {
2091
+ const { featured_app_right } = await this.scanProxyClient.get(
2092
+ "/v0/scan-proxy/featured-apps/{provider_party_id}",
2093
+ {
2094
+ path: {
2095
+ provider_party_id: partyId
2096
+ }
2097
+ }
2098
+ );
2099
+ return featured_app_right;
2100
+ }
2101
+ async buyMemberTraffic(dso, provider, trafficAmount, synchronizerId, memberId, migrationId, inputUtxos) {
2456
2102
  const amuletRules = await this.scanProxyClient.getAmuletRules();
2103
+ const activeRound = await this.scanProxyClient.getActiveOpenMiningRound();
2104
+ const inputHoldings = await this.tokenStandard.getInputHoldingsCids(
2105
+ provider,
2106
+ inputUtxos,
2107
+ trafficAmount
2108
+ );
2457
2109
  if (!amuletRules) {
2458
2110
  throw new Error("AmuletRules contract not found");
2459
2111
  }
2460
- const latestOpenMiningRound = await this.scanProxyClient.getActiveOpenMiningRound();
2461
- if (!latestOpenMiningRound) {
2112
+ if (!activeRound) {
2462
2113
  throw new Error(
2463
2114
  "OpenMiningRound active at current moment not found"
2464
2115
  );
2465
2116
  }
2466
- return [
2117
+ const disclosed = [
2467
2118
  {
2468
2119
  templateId: amuletRules.template_id,
2469
2120
  contractId: amuletRules.contract_id,
2470
- choice: "AmuletRules_DevNet_Tap",
2471
- choiceArgument: {
2472
- receiver,
2473
- amount,
2474
- openRound: latestOpenMiningRound.contract_id
2475
- }
2121
+ createdEventBlob: amuletRules.created_event_blob,
2122
+ synchronizerId
2476
2123
  },
2477
- disclosedContracts
2124
+ {
2125
+ templateId: activeRound.template_id,
2126
+ contractId: activeRound.contract_id,
2127
+ createdEventBlob: activeRound.created_event_blob,
2128
+ synchronizerId
2129
+ }
2478
2130
  ];
2131
+ const context = {
2132
+ openMiningRound: activeRound.contract_id,
2133
+ issuingMiningRounds: [],
2134
+ validatorRights: [],
2135
+ featuredAppRight: null
2136
+ };
2137
+ const choiceArgs = {
2138
+ context,
2139
+ inputs: inputHoldings.map((cid) => ({
2140
+ tag: "InputAmulet",
2141
+ value: cid
2142
+ })),
2143
+ provider,
2144
+ memberId: this.tokenStandard.core.toQualifiedMemberId(memberId),
2145
+ synchronizerId,
2146
+ migrationId,
2147
+ trafficAmount,
2148
+ expectedDso: dso
2149
+ };
2150
+ const exercise = {
2151
+ templateId: "#splice-amulet:Splice.AmuletRules:AmuletRules",
2152
+ contractId: amuletRules.contract_id,
2153
+ choice: "AmuletRules_BuyMemberTraffic",
2154
+ choiceArgument: choiceArgs
2155
+ };
2156
+ return [exercise, disclosed];
2157
+ }
2158
+ async getMemberTrafficStatus(domainId, memberId) {
2159
+ if (!this.scanClient) {
2160
+ throw new Error("Scan API URL was not provided");
2161
+ }
2162
+ return this.scanClient.get(
2163
+ "/v0/domains/{domain_id}/members/{member_id}/traffic-status",
2164
+ {
2165
+ path: {
2166
+ domain_id: domainId,
2167
+ member_id: this.tokenStandard.core.toQualifiedMemberId(memberId)
2168
+ }
2169
+ }
2170
+ );
2479
2171
  }
2480
2172
  async selfGrantFeatureAppRight(providerPartyId, synchronizerId) {
2481
2173
  const amuletRules = await this.scanProxyClient.getAmuletRules();
@@ -2531,7 +2223,7 @@ var TokenStandardService = class {
2531
2223
  synchronizerId
2532
2224
  }
2533
2225
  ];
2534
- const inputHoldings = await this.core.getInputHoldingsCids(
2226
+ const inputHoldings = await this.tokenStandard.getInputHoldingsCids(
2535
2227
  provider,
2536
2228
  inputUtxos
2537
2229
  );
@@ -2560,30 +2252,54 @@ var TokenStandardService = class {
2560
2252
  };
2561
2253
  return [exercise, disclosed];
2562
2254
  }
2563
- async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
2564
- const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(
2565
- transferInstructionCid,
2566
- registryUrl
2567
- );
2255
+ async createTap(receiver, amount, instrumentAdmin, instrumentId, registryUrl) {
2256
+ const now = /* @__PURE__ */ new Date();
2257
+ const tomorrow = new Date(now);
2258
+ tomorrow.setDate(tomorrow.getDate() + 1);
2568
2259
  const choiceArgs = {
2569
- cid: acceptTransferInstructionContext.contractId,
2570
- proxyArg: {
2571
- featuredAppRightCid,
2572
- beneficiaries: [
2573
- {
2574
- beneficiary: exchangeParty,
2575
- weight: 1
2576
- }
2577
- ],
2578
- choiceArg: acceptTransferInstructionContext.choiceArgument
2260
+ expectedAdmin: instrumentAdmin,
2261
+ transfer: {
2262
+ sender: instrumentAdmin,
2263
+ receiver,
2264
+ amount,
2265
+ instrumentId: { admin: instrumentAdmin, id: instrumentId },
2266
+ lock: null,
2267
+ requestedAt: new Date(
2268
+ Date.now() - REQUESTED_AT_SKEW_MS2
2269
+ ).toISOString(),
2270
+ executeBefore: tomorrow.toISOString(),
2271
+ inputHoldingCids: [],
2272
+ meta: { values: {} }
2273
+ },
2274
+ extraArgs: {
2275
+ context: { values: {} },
2276
+ meta: { values: {} }
2579
2277
  }
2580
2278
  };
2279
+ const disclosedContracts = (await this.tokenStandard.transfer.fetchTransferFactoryChoiceContext(
2280
+ registryUrl,
2281
+ choiceArgs
2282
+ )).choiceContext.disclosedContracts;
2283
+ const amuletRules = await this.scanProxyClient.getAmuletRules();
2284
+ if (!amuletRules) {
2285
+ throw new Error("AmuletRules contract not found");
2286
+ }
2287
+ const latestOpenMiningRound = await this.scanProxyClient.getActiveOpenMiningRound();
2288
+ if (!latestOpenMiningRound) {
2289
+ throw new Error(
2290
+ "OpenMiningRound active at current moment not found"
2291
+ );
2292
+ }
2581
2293
  return [
2582
2294
  {
2583
- templateId: "#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy",
2584
- contractId: proxyCid,
2585
- choice: "DelegateProxy_TransferInstruction_Accept",
2586
- choiceArgument: choiceArgs
2295
+ templateId: amuletRules.template_id,
2296
+ contractId: amuletRules.contract_id,
2297
+ choice: "AmuletRules_DevNet_Tap",
2298
+ choiceArgument: {
2299
+ receiver,
2300
+ amount,
2301
+ openRound: latestOpenMiningRound.contract_id
2302
+ }
2587
2303
  },
2588
2304
  disclosedContracts
2589
2305
  ];
@@ -3034,7 +2750,16 @@ var ACSHelper = class _ACSHelper {
3034
2750
  // src/ledger-client.ts
3035
2751
  var supportedVersions = ["3.3", "3.4"];
3036
2752
  var LedgerClient = class {
3037
- constructor(baseUrl, _logger, isAdmin = false, accessToken, accessTokenProvider, version, acsHelperOptions) {
2753
+ constructor({
2754
+ baseUrl,
2755
+ logger,
2756
+ isAdmin,
2757
+ accessToken,
2758
+ accessTokenProvider,
2759
+ version,
2760
+ acsHelperOptions,
2761
+ ...options
2762
+ }) {
3038
2763
  // privately manage the active connected version and associated client codegen
3039
2764
  __publicField(this, "clients");
3040
2765
  __publicField(this, "clientVersion", "3.4");
@@ -3046,38 +2771,30 @@ var LedgerClient = class {
3046
2771
  __publicField(this, "logger");
3047
2772
  __publicField(this, "synchronizerId");
3048
2773
  __publicField(this, "baseUrl");
3049
- this.logger = _logger.child({ component: "LedgerClient" });
2774
+ this.logger = logger.child({ component: "LedgerClient" });
3050
2775
  this.accessTokenProvider = accessTokenProvider;
2776
+ const baseFetch = options.fetch ?? fetch;
2777
+ const authenticatedFetch = async (url, options2 = {}) => {
2778
+ let token = accessToken;
2779
+ if (this.accessTokenProvider) {
2780
+ token = isAdmin ?? false ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
2781
+ }
2782
+ return baseFetch(url, {
2783
+ ...options2,
2784
+ headers: {
2785
+ ...options2.headers || {},
2786
+ ...token && { Authorization: `Bearer ${token}` }
2787
+ }
2788
+ });
2789
+ };
3051
2790
  this.clients = {
3052
2791
  "3.3": createClient__default.default({
3053
2792
  baseUrl: baseUrl.href,
3054
- fetch: async (url, options = {}) => {
3055
- if (this.accessTokenProvider) {
3056
- accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
3057
- }
3058
- return fetch(url, {
3059
- ...options,
3060
- headers: {
3061
- ...options.headers || {},
3062
- Authorization: `Bearer ${accessToken}`
3063
- }
3064
- });
3065
- }
2793
+ fetch: authenticatedFetch
3066
2794
  }),
3067
2795
  "3.4": createClient__default.default({
3068
2796
  baseUrl: baseUrl.href,
3069
- fetch: async (url, options = {}) => {
3070
- if (this.accessTokenProvider) {
3071
- accessToken = isAdmin ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
3072
- }
3073
- return fetch(url, {
3074
- ...options,
3075
- headers: {
3076
- ...options.headers || {},
3077
- Authorization: `Bearer ${accessToken}`
3078
- }
3079
- });
3080
- }
2797
+ fetch: authenticatedFetch
3081
2798
  })
3082
2799
  };
3083
2800
  this.clientVersion = version ?? this.clientVersion;
@@ -3085,7 +2802,7 @@ var LedgerClient = class {
3085
2802
  this.baseUrl = baseUrl;
3086
2803
  this.acsHelper = new ACSHelper(
3087
2804
  this,
3088
- _logger,
2805
+ logger,
3089
2806
  acsHelperOptions,
3090
2807
  SharedACSCache
3091
2808
  );
@@ -3212,20 +2929,23 @@ var LedgerClient = class {
3212
2929
  *
3213
2930
  * @param userId The ID of the user to grant rights to.
3214
2931
  * @param partyId The ID of the party to grant rights for.
2932
+ * @param maxTries Optional max number of retries with default 30. May be increased if expecting heavy load.
2933
+ * @param retryIntervalMs Optional interval between retries to verify that party exists with default 2000ms. May be increased if expecting heavy load.
3215
2934
  * @returns A promise that resolves when the rights have been granted.
3216
2935
  */
3217
- async waitForPartyAndGrantUserRights(userId, partyId) {
2936
+ async waitForPartyAndGrantUserRights(userId, partyId, maxTries = 30, retryIntervalMs = 2e3) {
3218
2937
  await this.init();
3219
2938
  let partyFound = false;
3220
2939
  let tries = 0;
3221
- const maxTries = 30;
3222
2940
  while (!partyFound && tries < maxTries) {
3223
2941
  partyFound = await this.checkIfPartyExists(partyId);
3224
- await new Promise((resolve) => setTimeout(resolve, 2e3));
2942
+ await new Promise((resolve) => setTimeout(resolve, retryIntervalMs));
3225
2943
  tries++;
3226
2944
  }
3227
2945
  if (tries >= maxTries) {
3228
- throw new Error("timed out waiting for new party to appear");
2946
+ throw new Error(
2947
+ `timed out waiting for new party to appear after ${maxTries} tries`
2948
+ );
3229
2949
  }
3230
2950
  const result = await this.grantRights(userId, {
3231
2951
  actAs: [partyId]
@@ -3584,10 +3304,10 @@ var WSSupportWithBackOffSwitch = class {
3584
3304
 
3585
3305
  exports.ACSContainer = ACSContainer;
3586
3306
  exports.ACS_UPDATE_CONFIG = ACS_UPDATE_CONFIG;
3307
+ exports.AmuletService = AmuletService;
3587
3308
  exports.CoreService = CoreService;
3588
3309
  exports.LedgerClient = LedgerClient;
3589
3310
  exports.TokenStandardService = TokenStandardService;
3590
- exports.TopologyWriteService = TopologyWriteService;
3591
3311
  exports.WSSupportWithBackOffSwitch = WSSupportWithBackOffSwitch;
3592
3312
  exports.asJsCantonError = asJsCantonError;
3593
3313
  exports.awaitCompletion = awaitCompletion;