@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.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);
@@ -1391,9 +1102,8 @@ var MEMO_KEY = "splice.lfdecentralizedtrust.org/reason";
1391
1102
  var REQUESTED_AT_SKEW_MS = 6e4;
1392
1103
  var EMPTY_META = { values: {} };
1393
1104
  var CoreService = class _CoreService {
1394
- constructor(ledgerClient, scanProxyClient, logger, accessTokenProvider, isMasterUser, isAdmin = false, accessToken = "") {
1105
+ constructor(ledgerClient, logger, accessTokenProvider, isMasterUser, isAdmin = false, accessToken = "") {
1395
1106
  this.ledgerClient = ledgerClient;
1396
- this.scanProxyClient = scanProxyClient;
1397
1107
  this.logger = logger;
1398
1108
  this.accessTokenProvider = accessTokenProvider;
1399
1109
  this.isMasterUser = isMasterUser;
@@ -1409,6 +1119,7 @@ var CoreService = class _CoreService {
1409
1119
  this.accessTokenProvider
1410
1120
  );
1411
1121
  }
1122
+ // TODO: probably needs a filter by instrument ID as well?
1412
1123
  async getInputHoldingsCids(sender, inputUtxos, amount) {
1413
1124
  const now = /* @__PURE__ */ new Date();
1414
1125
  if (inputUtxos && inputUtxos.length > 0) {
@@ -2158,19 +1869,16 @@ var TransferService = class {
2158
1869
  }
2159
1870
  };
2160
1871
  var TokenStandardService = class {
2161
- constructor(ledgerClient, scanProxyClient, logger, accessTokenProvider, isMasterUser, scanClient) {
1872
+ constructor(ledgerClient, logger, accessTokenProvider, isMasterUser) {
2162
1873
  this.ledgerClient = ledgerClient;
2163
- this.scanProxyClient = scanProxyClient;
2164
1874
  this.logger = logger;
2165
1875
  this.accessTokenProvider = accessTokenProvider;
2166
1876
  this.isMasterUser = isMasterUser;
2167
- this.scanClient = scanClient;
2168
1877
  __publicField(this, "core");
2169
1878
  __publicField(this, "allocation");
2170
1879
  __publicField(this, "transfer");
2171
1880
  this.core = new CoreService(
2172
1881
  ledgerClient,
2173
- scanProxyClient,
2174
1882
  logger,
2175
1883
  accessTokenProvider,
2176
1884
  isMasterUser,
@@ -2180,28 +1888,6 @@ var TokenStandardService = class {
2180
1888
  this.allocation = new AllocationService(this.core, this.logger);
2181
1889
  this.transfer = new TransferService(this.core, this.logger);
2182
1890
  }
2183
- async getTransferPreApprovalByParty(partyId) {
2184
- const { transfer_preapproval } = await this.scanProxyClient.get(
2185
- "/v0/scan-proxy/transfer-preapprovals/by-party/{party}",
2186
- {
2187
- path: {
2188
- party: partyId
2189
- }
2190
- }
2191
- );
2192
- return transfer_preapproval;
2193
- }
2194
- async getFeaturedAppsByParty(partyId) {
2195
- const { featured_app_right } = await this.scanProxyClient.get(
2196
- "/v0/scan-proxy/featured-apps/{provider_party_id}",
2197
- {
2198
- path: {
2199
- provider_party_id: partyId
2200
- }
2201
- }
2202
- );
2203
- return featured_app_right;
2204
- }
2205
1891
  async getInstrumentById(registryUrl, instrumentId) {
2206
1892
  try {
2207
1893
  const params = {
@@ -2221,77 +1907,6 @@ var TokenStandardService = class {
2221
1907
  );
2222
1908
  }
2223
1909
  }
2224
- async buyMemberTraffic(dso, provider, trafficAmount, synchronizerId, memberId, migrationId, inputUtxos) {
2225
- const amuletRules = await this.scanProxyClient.getAmuletRules();
2226
- const activeRound = await this.scanProxyClient.getActiveOpenMiningRound();
2227
- const inputHoldings = await this.core.getInputHoldingsCids(
2228
- provider,
2229
- inputUtxos,
2230
- trafficAmount
2231
- );
2232
- if (!amuletRules) {
2233
- throw new Error("AmuletRules contract not found");
2234
- }
2235
- if (!activeRound) {
2236
- throw new Error(
2237
- "OpenMiningRound active at current moment not found"
2238
- );
2239
- }
2240
- const disclosed = [
2241
- {
2242
- templateId: amuletRules.template_id,
2243
- contractId: amuletRules.contract_id,
2244
- createdEventBlob: amuletRules.created_event_blob,
2245
- synchronizerId
2246
- },
2247
- {
2248
- templateId: activeRound.template_id,
2249
- contractId: activeRound.contract_id,
2250
- createdEventBlob: activeRound.created_event_blob,
2251
- synchronizerId
2252
- }
2253
- ];
2254
- const context = {
2255
- openMiningRound: activeRound.contract_id,
2256
- issuingMiningRounds: [],
2257
- validatorRights: [],
2258
- featuredAppRight: null
2259
- };
2260
- const choiceArgs = {
2261
- context,
2262
- inputs: inputHoldings.map((cid) => ({
2263
- tag: "InputAmulet",
2264
- value: cid
2265
- })),
2266
- provider,
2267
- memberId: this.core.toQualifiedMemberId(memberId),
2268
- synchronizerId,
2269
- migrationId,
2270
- trafficAmount,
2271
- expectedDso: dso
2272
- };
2273
- const exercise = {
2274
- templateId: "#splice-amulet:Splice.AmuletRules:AmuletRules",
2275
- contractId: amuletRules.contract_id,
2276
- choice: "AmuletRules_BuyMemberTraffic",
2277
- choiceArgument: choiceArgs
2278
- };
2279
- return [exercise, disclosed];
2280
- }
2281
- async getMemberTrafficStatus(domainId, memberId) {
2282
- if (!this.scanClient) {
2283
- throw new Error("Scan API URL was not provided");
2284
- }
2285
- return this.scanClient.get(
2286
- "/v0/domains/{domain_id}/members/{member_id}/traffic-status",
2287
- {
2288
- path: {
2289
- domain_id: domainId,
2290
- member_id: this.core.toQualifiedMemberId(memberId)
2291
- }
2292
- }
2293
- );
2294
- }
2295
1910
  async getInstrumentAdmin(registryUrl) {
2296
1911
  const client = this.core.getTokenStandardClient(registryUrl);
2297
1912
  const info = await client.get("/registry/metadata/v1/info");
@@ -2377,8 +1992,8 @@ var TokenStandardService = class {
2377
1992
  this.ledgerClient
2378
1993
  );
2379
1994
  }
2380
- async getInputHoldingsCids(sender, inputUtxos) {
2381
- return this.core.getInputHoldingsCids(sender, inputUtxos);
1995
+ async getInputHoldingsCids(sender, inputUtxos, amount) {
1996
+ return this.core.getInputHoldingsCids(sender, inputUtxos, amount);
2382
1997
  }
2383
1998
  async createDelegateProxyTranfser(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, featuredAppRightCid, proxyCid, beneficiaries, inputUtxos, memo, expiryDate, meta) {
2384
1999
  const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(
@@ -2416,58 +2031,136 @@ var TokenStandardService = class {
2416
2031
  };
2417
2032
  return [exercise, disclosedContracts];
2418
2033
  }
2419
- // TODO(#583) as it's not a part of token standard, should be moved somewhere else
2420
- async createTap(receiver, amount, instrumentAdmin, instrumentId, registryUrl) {
2421
- const now = /* @__PURE__ */ new Date();
2422
- const tomorrow = new Date(now);
2423
- tomorrow.setDate(tomorrow.getDate() + 1);
2034
+ async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
2035
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(
2036
+ transferInstructionCid,
2037
+ registryUrl
2038
+ );
2424
2039
  const choiceArgs = {
2425
- expectedAdmin: instrumentAdmin,
2426
- transfer: {
2427
- sender: instrumentAdmin,
2428
- receiver,
2429
- amount,
2430
- instrumentId: { admin: instrumentAdmin, id: instrumentId },
2431
- lock: null,
2432
- requestedAt: new Date(
2433
- Date.now() - REQUESTED_AT_SKEW_MS
2434
- ).toISOString(),
2435
- executeBefore: tomorrow.toISOString(),
2436
- inputHoldingCids: [],
2437
- meta: { values: {} }
2438
- },
2439
- extraArgs: {
2440
- context: { values: {} },
2441
- meta: { values: {} }
2040
+ cid: acceptTransferInstructionContext.contractId,
2041
+ proxyArg: {
2042
+ featuredAppRightCid,
2043
+ beneficiaries: [
2044
+ {
2045
+ beneficiary: exchangeParty,
2046
+ weight: 1
2047
+ }
2048
+ ],
2049
+ choiceArg: acceptTransferInstructionContext.choiceArgument
2442
2050
  }
2443
2051
  };
2444
- const transferFactory = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
2445
- choiceArguments: choiceArgs
2446
- });
2447
- const disclosedContracts = transferFactory.choiceContext.disclosedContracts;
2052
+ return [
2053
+ {
2054
+ templateId: "#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy",
2055
+ contractId: proxyCid,
2056
+ choice: "DelegateProxy_TransferInstruction_Accept",
2057
+ choiceArgument: choiceArgs
2058
+ },
2059
+ disclosedContracts
2060
+ ];
2061
+ }
2062
+ };
2063
+
2064
+ // src/amulet-service.ts
2065
+ var REQUESTED_AT_SKEW_MS2 = 6e4;
2066
+ var AmuletService = class {
2067
+ constructor(tokenStandard, scanProxyClient, scanClient) {
2068
+ this.tokenStandard = tokenStandard;
2069
+ this.scanProxyClient = scanProxyClient;
2070
+ this.scanClient = scanClient;
2071
+ }
2072
+ async getTransferPreApprovalByParty(partyId) {
2073
+ const { transfer_preapproval } = await this.scanProxyClient.get(
2074
+ "/v0/scan-proxy/transfer-preapprovals/by-party/{party}",
2075
+ {
2076
+ path: {
2077
+ party: partyId
2078
+ }
2079
+ }
2080
+ );
2081
+ return transfer_preapproval;
2082
+ }
2083
+ async getFeaturedAppsByParty(partyId) {
2084
+ const { featured_app_right } = await this.scanProxyClient.get(
2085
+ "/v0/scan-proxy/featured-apps/{provider_party_id}",
2086
+ {
2087
+ path: {
2088
+ provider_party_id: partyId
2089
+ }
2090
+ }
2091
+ );
2092
+ return featured_app_right;
2093
+ }
2094
+ async buyMemberTraffic(dso, provider, trafficAmount, synchronizerId, memberId, migrationId, inputUtxos) {
2448
2095
  const amuletRules = await this.scanProxyClient.getAmuletRules();
2096
+ const activeRound = await this.scanProxyClient.getActiveOpenMiningRound();
2097
+ const inputHoldings = await this.tokenStandard.getInputHoldingsCids(
2098
+ provider,
2099
+ inputUtxos,
2100
+ trafficAmount
2101
+ );
2449
2102
  if (!amuletRules) {
2450
2103
  throw new Error("AmuletRules contract not found");
2451
2104
  }
2452
- const latestOpenMiningRound = await this.scanProxyClient.getActiveOpenMiningRound();
2453
- if (!latestOpenMiningRound) {
2105
+ if (!activeRound) {
2454
2106
  throw new Error(
2455
2107
  "OpenMiningRound active at current moment not found"
2456
2108
  );
2457
2109
  }
2458
- return [
2110
+ const disclosed = [
2459
2111
  {
2460
2112
  templateId: amuletRules.template_id,
2461
2113
  contractId: amuletRules.contract_id,
2462
- choice: "AmuletRules_DevNet_Tap",
2463
- choiceArgument: {
2464
- receiver,
2465
- amount,
2466
- openRound: latestOpenMiningRound.contract_id
2467
- }
2114
+ createdEventBlob: amuletRules.created_event_blob,
2115
+ synchronizerId
2468
2116
  },
2469
- disclosedContracts
2117
+ {
2118
+ templateId: activeRound.template_id,
2119
+ contractId: activeRound.contract_id,
2120
+ createdEventBlob: activeRound.created_event_blob,
2121
+ synchronizerId
2122
+ }
2470
2123
  ];
2124
+ const context = {
2125
+ openMiningRound: activeRound.contract_id,
2126
+ issuingMiningRounds: [],
2127
+ validatorRights: [],
2128
+ featuredAppRight: null
2129
+ };
2130
+ const choiceArgs = {
2131
+ context,
2132
+ inputs: inputHoldings.map((cid) => ({
2133
+ tag: "InputAmulet",
2134
+ value: cid
2135
+ })),
2136
+ provider,
2137
+ memberId: this.tokenStandard.core.toQualifiedMemberId(memberId),
2138
+ synchronizerId,
2139
+ migrationId,
2140
+ trafficAmount,
2141
+ expectedDso: dso
2142
+ };
2143
+ const exercise = {
2144
+ templateId: "#splice-amulet:Splice.AmuletRules:AmuletRules",
2145
+ contractId: amuletRules.contract_id,
2146
+ choice: "AmuletRules_BuyMemberTraffic",
2147
+ choiceArgument: choiceArgs
2148
+ };
2149
+ return [exercise, disclosed];
2150
+ }
2151
+ async getMemberTrafficStatus(domainId, memberId) {
2152
+ if (!this.scanClient) {
2153
+ throw new Error("Scan API URL was not provided");
2154
+ }
2155
+ return this.scanClient.get(
2156
+ "/v0/domains/{domain_id}/members/{member_id}/traffic-status",
2157
+ {
2158
+ path: {
2159
+ domain_id: domainId,
2160
+ member_id: this.tokenStandard.core.toQualifiedMemberId(memberId)
2161
+ }
2162
+ }
2163
+ );
2471
2164
  }
2472
2165
  async selfGrantFeatureAppRight(providerPartyId, synchronizerId) {
2473
2166
  const amuletRules = await this.scanProxyClient.getAmuletRules();
@@ -2523,7 +2216,7 @@ var TokenStandardService = class {
2523
2216
  synchronizerId
2524
2217
  }
2525
2218
  ];
2526
- const inputHoldings = await this.core.getInputHoldingsCids(
2219
+ const inputHoldings = await this.tokenStandard.getInputHoldingsCids(
2527
2220
  provider,
2528
2221
  inputUtxos
2529
2222
  );
@@ -2552,30 +2245,54 @@ var TokenStandardService = class {
2552
2245
  };
2553
2246
  return [exercise, disclosed];
2554
2247
  }
2555
- async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
2556
- const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(
2557
- transferInstructionCid,
2558
- registryUrl
2559
- );
2248
+ async createTap(receiver, amount, instrumentAdmin, instrumentId, registryUrl) {
2249
+ const now = /* @__PURE__ */ new Date();
2250
+ const tomorrow = new Date(now);
2251
+ tomorrow.setDate(tomorrow.getDate() + 1);
2560
2252
  const choiceArgs = {
2561
- cid: acceptTransferInstructionContext.contractId,
2562
- proxyArg: {
2563
- featuredAppRightCid,
2564
- beneficiaries: [
2565
- {
2566
- beneficiary: exchangeParty,
2567
- weight: 1
2568
- }
2569
- ],
2570
- choiceArg: acceptTransferInstructionContext.choiceArgument
2253
+ expectedAdmin: instrumentAdmin,
2254
+ transfer: {
2255
+ sender: instrumentAdmin,
2256
+ receiver,
2257
+ amount,
2258
+ instrumentId: { admin: instrumentAdmin, id: instrumentId },
2259
+ lock: null,
2260
+ requestedAt: new Date(
2261
+ Date.now() - REQUESTED_AT_SKEW_MS2
2262
+ ).toISOString(),
2263
+ executeBefore: tomorrow.toISOString(),
2264
+ inputHoldingCids: [],
2265
+ meta: { values: {} }
2266
+ },
2267
+ extraArgs: {
2268
+ context: { values: {} },
2269
+ meta: { values: {} }
2571
2270
  }
2572
2271
  };
2272
+ const disclosedContracts = (await this.tokenStandard.transfer.fetchTransferFactoryChoiceContext(
2273
+ registryUrl,
2274
+ choiceArgs
2275
+ )).choiceContext.disclosedContracts;
2276
+ const amuletRules = await this.scanProxyClient.getAmuletRules();
2277
+ if (!amuletRules) {
2278
+ throw new Error("AmuletRules contract not found");
2279
+ }
2280
+ const latestOpenMiningRound = await this.scanProxyClient.getActiveOpenMiningRound();
2281
+ if (!latestOpenMiningRound) {
2282
+ throw new Error(
2283
+ "OpenMiningRound active at current moment not found"
2284
+ );
2285
+ }
2573
2286
  return [
2574
2287
  {
2575
- templateId: "#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy",
2576
- contractId: proxyCid,
2577
- choice: "DelegateProxy_TransferInstruction_Accept",
2578
- choiceArgument: choiceArgs
2288
+ templateId: amuletRules.template_id,
2289
+ contractId: amuletRules.contract_id,
2290
+ choice: "AmuletRules_DevNet_Tap",
2291
+ choiceArgument: {
2292
+ receiver,
2293
+ amount,
2294
+ openRound: latestOpenMiningRound.contract_id
2295
+ }
2579
2296
  },
2580
2297
  disclosedContracts
2581
2298
  ];
@@ -3026,7 +2743,16 @@ var ACSHelper = class _ACSHelper {
3026
2743
  // src/ledger-client.ts
3027
2744
  var supportedVersions = ["3.3", "3.4"];
3028
2745
  var LedgerClient = class {
3029
- constructor(baseUrl, _logger, isAdmin = false, accessToken, accessTokenProvider, version, acsHelperOptions) {
2746
+ constructor({
2747
+ baseUrl,
2748
+ logger,
2749
+ isAdmin,
2750
+ accessToken,
2751
+ accessTokenProvider,
2752
+ version,
2753
+ acsHelperOptions,
2754
+ ...options
2755
+ }) {
3030
2756
  // privately manage the active connected version and associated client codegen
3031
2757
  __publicField(this, "clients");
3032
2758
  __publicField(this, "clientVersion", "3.4");
@@ -3038,38 +2764,30 @@ var LedgerClient = class {
3038
2764
  __publicField(this, "logger");
3039
2765
  __publicField(this, "synchronizerId");
3040
2766
  __publicField(this, "baseUrl");
3041
- this.logger = _logger.child({ component: "LedgerClient" });
2767
+ this.logger = logger.child({ component: "LedgerClient" });
3042
2768
  this.accessTokenProvider = accessTokenProvider;
2769
+ const baseFetch = options.fetch ?? fetch;
2770
+ const authenticatedFetch = async (url, options2 = {}) => {
2771
+ let token = accessToken;
2772
+ if (this.accessTokenProvider) {
2773
+ token = isAdmin ?? false ? await this.accessTokenProvider.getAdminAccessToken() : await this.accessTokenProvider.getUserAccessToken();
2774
+ }
2775
+ return baseFetch(url, {
2776
+ ...options2,
2777
+ headers: {
2778
+ ...options2.headers || {},
2779
+ ...token && { Authorization: `Bearer ${token}` }
2780
+ }
2781
+ });
2782
+ };
3043
2783
  this.clients = {
3044
2784
  "3.3": createClient({
3045
2785
  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
- }
2786
+ fetch: authenticatedFetch
3058
2787
  }),
3059
2788
  "3.4": createClient({
3060
2789
  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
- }
2790
+ fetch: authenticatedFetch
3073
2791
  })
3074
2792
  };
3075
2793
  this.clientVersion = version ?? this.clientVersion;
@@ -3077,7 +2795,7 @@ var LedgerClient = class {
3077
2795
  this.baseUrl = baseUrl;
3078
2796
  this.acsHelper = new ACSHelper(
3079
2797
  this,
3080
- _logger,
2798
+ logger,
3081
2799
  acsHelperOptions,
3082
2800
  SharedACSCache
3083
2801
  );
@@ -3204,20 +2922,23 @@ var LedgerClient = class {
3204
2922
  *
3205
2923
  * @param userId The ID of the user to grant rights to.
3206
2924
  * @param partyId The ID of the party to grant rights for.
2925
+ * @param maxTries Optional max number of retries with default 30. May be increased if expecting heavy load.
2926
+ * @param retryIntervalMs Optional interval between retries to verify that party exists with default 2000ms. May be increased if expecting heavy load.
3207
2927
  * @returns A promise that resolves when the rights have been granted.
3208
2928
  */
3209
- async waitForPartyAndGrantUserRights(userId, partyId) {
2929
+ async waitForPartyAndGrantUserRights(userId, partyId, maxTries = 30, retryIntervalMs = 2e3) {
3210
2930
  await this.init();
3211
2931
  let partyFound = false;
3212
2932
  let tries = 0;
3213
- const maxTries = 30;
3214
2933
  while (!partyFound && tries < maxTries) {
3215
2934
  partyFound = await this.checkIfPartyExists(partyId);
3216
- await new Promise((resolve) => setTimeout(resolve, 2e3));
2935
+ await new Promise((resolve) => setTimeout(resolve, retryIntervalMs));
3217
2936
  tries++;
3218
2937
  }
3219
2938
  if (tries >= maxTries) {
3220
- throw new Error("timed out waiting for new party to appear");
2939
+ throw new Error(
2940
+ `timed out waiting for new party to appear after ${maxTries} tries`
2941
+ );
3221
2942
  }
3222
2943
  const result = await this.grantRights(userId, {
3223
2944
  actAs: [partyId]
@@ -3574,6 +3295,6 @@ var WSSupportWithBackOffSwitch = class {
3574
3295
  }
3575
3296
  };
3576
3297
 
3577
- export { ACSContainer, ACS_UPDATE_CONFIG, CoreService, LedgerClient, TokenStandardService, TopologyWriteService, WSSupportWithBackOffSwitch, asJsCantonError, awaitCompletion, defaultRetryableOptions, isJsCantonError, promiseWithTimeout, supportedVersions };
3298
+ export { ACSContainer, ACS_UPDATE_CONFIG, AmuletService, CoreService, LedgerClient, TokenStandardService, WSSupportWithBackOffSwitch, asJsCantonError, awaitCompletion, defaultRetryableOptions, isJsCantonError, promiseWithTimeout, supportedVersions };
3578
3299
  //# sourceMappingURL=index.js.map
3579
3300
  //# sourceMappingURL=index.js.map