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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/dist/acs/acs-container.d.ts +36 -0
  2. package/dist/acs/acs-container.d.ts.map +1 -0
  3. package/dist/acs/acs-helper.d.ts +39 -0
  4. package/dist/acs/acs-helper.d.ts.map +1 -0
  5. package/dist/acs/types.d.ts +10 -0
  6. package/dist/acs/types.d.ts.map +1 -0
  7. package/dist/acs/ws-support.d.ts +18 -0
  8. package/dist/acs/ws-support.d.ts.map +1 -0
  9. package/dist/index.cjs +3306 -0
  10. package/dist/index.cjs.map +1 -0
  11. package/dist/index.d.ts +3 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +3286 -7
  14. package/dist/index.js.map +1 -0
  15. package/dist/ledger-api-utils.d.ts +3 -1
  16. package/dist/ledger-api-utils.d.ts.map +1 -1
  17. package/dist/ledger-client.d.ts +32 -4
  18. package/dist/ledger-client.d.ts.map +1 -1
  19. package/dist/token-standard-service.d.ts +11 -9
  20. package/dist/token-standard-service.d.ts.map +1 -1
  21. package/dist/topology-write-service.d.ts +4 -2
  22. package/dist/topology-write-service.d.ts.map +1 -1
  23. package/dist/txparse/parser.d.ts.map +1 -1
  24. package/dist/txparse/test-data/mock/eventsByContractIdResponses.d.ts +153 -0
  25. package/dist/txparse/test-data/mock/eventsByContractIdResponses.d.ts.map +1 -1
  26. package/dist/txparse/types.d.ts +5 -2
  27. package/dist/txparse/types.d.ts.map +1 -1
  28. package/package.json +23 -11
  29. package/dist/constants.js +0 -47
  30. package/dist/generated-clients/openapi-3.3.0-SNAPSHOT.js +0 -5
  31. package/dist/generated-clients/openapi-3.4.0-SNAPSHOT.js +0 -5
  32. package/dist/ledger-api-utils.js +0 -432
  33. package/dist/ledger-client.js +0 -321
  34. package/dist/token-standard-service.js +0 -871
  35. package/dist/topology-write-service.js +0 -283
  36. package/dist/txparse/parser.js +0 -581
  37. package/dist/txparse/parser.test.d.ts +0 -2
  38. package/dist/txparse/parser.test.d.ts.map +0 -1
  39. package/dist/txparse/parser.test.js +0 -97
  40. package/dist/txparse/strict.js +0 -19
  41. package/dist/txparse/test-data/expected/txs.js +0 -2303
  42. package/dist/txparse/test-data/mock/eventsByContractIdResponses.js +0 -2973
  43. package/dist/txparse/test-data/mock/txs.js +0 -6788
  44. package/dist/txparse/types.js +0 -58
@@ -1,871 +0,0 @@
1
- // Copyright (c) 2025 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
2
- // SPDX-License-Identifier: Apache-2.0
3
- import { TokenStandardClient, TRANSFER_FACTORY_INTERFACE_ID, HOLDING_INTERFACE_ID, ALLOCATION_FACTORY_INTERFACE_ID, ALLOCATION_INTERFACE_ID, ALLOCATION_REQUEST_INTERFACE_ID, ALLOCATION_INSTRUCTION_INTERFACE_ID, TRANSFER_INSTRUCTION_INTERFACE_ID, FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID, } from '@canton-network/core-token-standard';
4
- import { TokenStandardTransactionInterfaces } from './constants.js';
5
- import { ensureInterfaceViewIsPresent, TransactionFilterBySetup, EventFilterBySetup, defaultRetryableOptions, } from './ledger-api-utils.js';
6
- import { TransactionParser } from './txparse/parser.js';
7
- import { renderTransaction, } from './txparse/types.js';
8
- const MEMO_KEY = 'splice.lfdecentralizedtrust.org/reason';
9
- const REQUESTED_AT_SKEW_MS = 60_000;
10
- const EMPTY_META = { values: {} };
11
- class CoreService {
12
- ledgerClient;
13
- scanProxyClient;
14
- logger;
15
- accessToken;
16
- isMasterUser;
17
- constructor(ledgerClient, scanProxyClient, logger, accessToken, isMasterUser) {
18
- this.ledgerClient = ledgerClient;
19
- this.scanProxyClient = scanProxyClient;
20
- this.logger = logger;
21
- this.accessToken = accessToken;
22
- this.isMasterUser = isMasterUser;
23
- }
24
- getTokenStandardClient(registryUrl) {
25
- return new TokenStandardClient(registryUrl, this.logger, this.accessToken);
26
- }
27
- async getInputHoldingsCids(sender, inputUtxos) {
28
- const now = new Date();
29
- if (inputUtxos && inputUtxos.length > 0) {
30
- return inputUtxos;
31
- }
32
- const senderHoldings = await this.listContractsByInterface(HOLDING_INTERFACE_ID, sender);
33
- if (senderHoldings.length === 0) {
34
- throw new Error("Sender has no holdings, so transfer can't be executed.");
35
- }
36
- return senderHoldings
37
- .filter((utxo) => {
38
- //filter out locked holdings
39
- const lock = utxo.interfaceViewValue.lock;
40
- if (!lock)
41
- return true;
42
- const expiresAt = lock.expiresAt;
43
- if (!expiresAt)
44
- return false;
45
- const expiresAtDate = new Date(expiresAt);
46
- return expiresAtDate <= now;
47
- })
48
- .map((h) => h.contractId);
49
- /* TODO: optimize input holding selection, currently if you transfer 10 CC and have 10 inputs of 1000 CC,
50
- then all 10 of those are chose as input.
51
- */
52
- }
53
- async listContractsByInterface(interfaceId, partyId, limit) {
54
- try {
55
- const ledgerEnd = await this.ledgerClient.getWithRetry('/v2/state/ledger-end');
56
- const acsResponses = await this.ledgerClient.postWithRetry('/v2/state/active-contracts', {
57
- filter: TransactionFilterBySetup(interfaceId, {
58
- isMasterUser: this.isMasterUser,
59
- partyId: partyId,
60
- }),
61
- verbose: false,
62
- activeAtOffset: ledgerEnd.offset,
63
- }, defaultRetryableOptions, {
64
- query: limit ? { limit: limit.toString() } : {},
65
- });
66
- /* This filters out responses with entries of:
67
- - JsEmpty
68
- - JsIncompleteAssigned
69
- - JsIncompleteUnassigned
70
- while leaving JsActiveContract.
71
- It works fine only with single synchronizer
72
- TODO (#353) add support for multiple synchronizers
73
- */
74
- const isActiveContractEntry = (acsResponse) => !!acsResponse.contractEntry.JsActiveContract?.createdEvent;
75
- const activeContractEntries = acsResponses.filter(isActiveContractEntry);
76
- return activeContractEntries.map((response) => this.toPrettyContract(interfaceId, response));
77
- }
78
- catch (err) {
79
- this.logger.error(`Failed to list contracts of interface ${interfaceId}`, err);
80
- throw err;
81
- }
82
- }
83
- async toPrettyTransactions(updates, partyId, ledgerClient) {
84
- // Runtime filters that also let TS know which of OneOfs types to check against
85
- const isOffsetCheckpointUpdate = (updateResponse) => !!updateResponse?.update?.OffsetCheckpoint;
86
- const isTransactionUpdate = (updateResponse) => !!updateResponse.update?.Transaction?.value;
87
- const offsetCheckpoints = updates
88
- .filter(isOffsetCheckpointUpdate)
89
- .map((update) => update.update.OffsetCheckpoint.value.offset);
90
- const latestCheckpointOffset = Math.max(...offsetCheckpoints);
91
- const transactions = await Promise.all(updates
92
- // exclude OffsetCheckpoint, Reassignment, TopologyTransaction
93
- .filter(isTransactionUpdate)
94
- .map(async (update) => {
95
- const tx = update.update.Transaction.value;
96
- const parser = new TransactionParser(tx, ledgerClient, partyId, this.isMasterUser);
97
- return await parser.parseTransaction();
98
- }));
99
- return {
100
- // OffsetCheckpoint can be anywhere... or not at all, maybe
101
- nextOffset: Math.max(latestCheckpointOffset, ...transactions.map((tx) => tx.offset)),
102
- transactions: transactions
103
- .filter((tx) => tx.events.length > 0)
104
- .map(renderTransaction),
105
- };
106
- }
107
- async toPrettyTransaction(getTransactionResponse, partyId, ledgerClient) {
108
- const tx = getTransactionResponse.transaction;
109
- const parser = new TransactionParser(tx, ledgerClient, partyId, this.isMasterUser);
110
- const parsedTx = await parser.parseTransaction();
111
- return renderTransaction(parsedTx);
112
- }
113
- async toPrettyTransactionsPerParty(updates, parties, ledgerClient) {
114
- const all = await Promise.all(parties.map(async (partyId) => [
115
- partyId,
116
- await this.toPrettyTransactions(updates, partyId, ledgerClient),
117
- ]));
118
- return new Map(all);
119
- }
120
- // returns object with JsActiveContract content
121
- // and contractId and interface view value extracted from it as separate fields for convenience
122
- toPrettyContract(interfaceId, response) {
123
- const activeContract = response.contractEntry.JsActiveContract;
124
- const { createdEvent } = activeContract;
125
- return {
126
- contractId: createdEvent.contractId,
127
- activeContract,
128
- interfaceViewValue: ensureInterfaceViewIsPresent(createdEvent, interfaceId).viewValue,
129
- };
130
- }
131
- async getActiveOpenMiningRound() {
132
- const openMiningRounds = await this.scanProxyClient.getOpenMiningRounds();
133
- if (!(Array.isArray(openMiningRounds) && openMiningRounds.length)) {
134
- throw new Error('OpenMiningRound contract not found');
135
- }
136
- const nowForOpenMiningRounds = Date.now();
137
- const latestOpenMiningRound = openMiningRounds.findLast((openMiningRound) => {
138
- const { opensAt, targetClosesAt } = openMiningRound.payload;
139
- const opensAtMs = Number(new Date(opensAt));
140
- const targetClosesAtMs = Number(new Date(targetClosesAt));
141
- return (opensAtMs <= nowForOpenMiningRounds &&
142
- targetClosesAtMs > nowForOpenMiningRounds);
143
- });
144
- return latestOpenMiningRound ?? null;
145
- }
146
- }
147
- class AllocationService {
148
- core;
149
- logger;
150
- constructor(core, logger) {
151
- this.core = core;
152
- this.logger = logger;
153
- }
154
- async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
155
- const allocationSpecificationNormalized = {
156
- ...allocationSpecification,
157
- settlement: {
158
- ...allocationSpecification.settlement,
159
- meta: allocationSpecification.settlement.meta ?? { values: {} },
160
- },
161
- transferLeg: {
162
- ...allocationSpecification.transferLeg,
163
- meta: allocationSpecification.transferLeg.meta ?? {
164
- values: {},
165
- },
166
- },
167
- };
168
- const inputHoldingCids = await this.core.getInputHoldingsCids(allocationSpecificationNormalized.transferLeg.sender, inputUtxos);
169
- return {
170
- expectedAdmin,
171
- allocation: allocationSpecificationNormalized,
172
- requestedAt: requestedAt ??
173
- new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
174
- inputHoldingCids,
175
- extraArgs: {
176
- context: { values: {} },
177
- meta: { values: {} },
178
- },
179
- };
180
- }
181
- async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs) {
182
- return this.core
183
- .getTokenStandardClient(registryUrl)
184
- .post('/registry/allocation-instruction/v1/allocation-factory', {
185
- choiceArguments: choiceArgs,
186
- });
187
- }
188
- async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
189
- choiceArgs.extraArgs.context = {
190
- ...choiceContext.choiceContextData,
191
- values: choiceContext.choiceContextData?.values ?? {},
192
- };
193
- const exercise = {
194
- templateId: ALLOCATION_FACTORY_INTERFACE_ID,
195
- contractId: factoryId,
196
- choice: 'AllocationFactory_Allocate',
197
- choiceArgument: choiceArgs,
198
- };
199
- return [exercise, choiceContext.disclosedContracts];
200
- }
201
- async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
202
- const choiceArgs = await this.buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt);
203
- if (prefetchedRegistryChoiceContext) {
204
- return this.createAllocationInstructionFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
205
- }
206
- const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs);
207
- return this.createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext);
208
- }
209
- buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
210
- const exercise = {
211
- templateId,
212
- contractId,
213
- choice,
214
- choiceArgument: {
215
- extraArgs: {
216
- context: choiceContext.choiceContextData,
217
- meta: EMPTY_META,
218
- },
219
- },
220
- };
221
- return [exercise, choiceContext.disclosedContracts ?? []];
222
- }
223
- async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
224
- return this.core.getTokenStandardClient(registryUrl).post('/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer', {}, {
225
- path: {
226
- allocationId,
227
- },
228
- });
229
- }
230
- createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
231
- return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, 'Allocation_ExecuteTransfer', choiceContext);
232
- }
233
- async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
234
- if (prefetchedRegistryChoiceContext) {
235
- return this.createExecuteTransferAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
236
- }
237
- const choiceContext = await this.fetchExecuteTransferChoiceContext(allocationCid, registryUrl);
238
- return this.createExecuteTransferAllocationFromContext(allocationCid, choiceContext);
239
- }
240
- async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
241
- return this.core
242
- .getTokenStandardClient(registryUrl)
243
- .post('/registry/allocations/v1/{allocationId}/choice-contexts/withdraw', {}, { path: { allocationId: allocationCid } });
244
- }
245
- createWithdrawAllocationFromContext(allocationCid, choiceContext) {
246
- return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, 'Allocation_Withdraw', choiceContext);
247
- }
248
- async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
249
- if (prefetchedRegistryChoiceContext) {
250
- return this.createWithdrawAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
251
- }
252
- const choiceContext = await this.fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl);
253
- return this.createWithdrawAllocationFromContext(allocationCid, choiceContext);
254
- }
255
- async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
256
- return this.core
257
- .getTokenStandardClient(registryUrl)
258
- .post('/registry/allocations/v1/{allocationId}/choice-contexts/cancel', {}, { path: { allocationId: allocationCid } });
259
- }
260
- createCancelAllocationFromContext(allocationCid, choiceContext) {
261
- return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, 'Allocation_Cancel', choiceContext);
262
- }
263
- async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
264
- if (prefetchedRegistryChoiceContext) {
265
- return this.createCancelAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
266
- }
267
- const choiceContext = await this.fetchCancelAllocationChoiceContext(allocationCid, registryUrl);
268
- return this.createCancelAllocationFromContext(allocationCid, choiceContext);
269
- }
270
- async createWithdrawAllocationInstruction(allocationInstructionCid) {
271
- const exercise = {
272
- templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
273
- contractId: allocationInstructionCid,
274
- choice: 'AllocationInstruction_Withdraw',
275
- choiceArgument: {
276
- extraArgs: {
277
- context: { values: {} },
278
- meta: { values: {} },
279
- },
280
- },
281
- };
282
- return [exercise, []];
283
- }
284
- async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
285
- const exercise = {
286
- templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
287
- contractId: allocationInstructionCid,
288
- choice: 'AllocationInstruction_Update',
289
- choiceArgument: {
290
- extraActors,
291
- extraArgs: {
292
- context: { values: extraArgsContext },
293
- meta: { values: extraArgsMeta },
294
- },
295
- },
296
- };
297
- return [exercise, []];
298
- }
299
- async createRejectAllocationRequest(allocationRequestCid, actor) {
300
- const exercise = {
301
- templateId: ALLOCATION_REQUEST_INTERFACE_ID,
302
- contractId: allocationRequestCid,
303
- choice: 'AllocationRequest_Reject',
304
- choiceArgument: {
305
- actor,
306
- extraArgs: {
307
- context: { values: {} },
308
- meta: { values: {} },
309
- },
310
- },
311
- };
312
- return [exercise, []];
313
- }
314
- async createWithdrawAllocationRequest(allocationRequestCid) {
315
- const exercise = {
316
- templateId: ALLOCATION_REQUEST_INTERFACE_ID,
317
- contractId: allocationRequestCid,
318
- choice: 'AllocationRequest_Withdraw',
319
- choiceArgument: {
320
- extraArgs: {
321
- context: { values: {} },
322
- meta: { values: {} },
323
- },
324
- },
325
- };
326
- return [exercise, []];
327
- }
328
- }
329
- class TransferService {
330
- core;
331
- logger;
332
- constructor(core, logger) {
333
- this.core = core;
334
- this.logger = logger;
335
- }
336
- async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta) {
337
- const inputHoldingCids = await this.core.getInputHoldingsCids(sender, inputUtxos);
338
- return {
339
- expectedAdmin: instrumentAdmin,
340
- transfer: {
341
- sender,
342
- receiver,
343
- amount,
344
- instrumentId: { admin: instrumentAdmin, id: instrumentId },
345
- requestedAt: new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
346
- executeBefore: (expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1000)).toISOString(),
347
- inputHoldingCids,
348
- meta: { values: { [MEMO_KEY]: memo || '', ...meta?.values } },
349
- },
350
- extraArgs: {
351
- context: { values: {} },
352
- meta: { values: {} },
353
- },
354
- };
355
- }
356
- async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs) {
357
- return await this.core
358
- .getTokenStandardClient(registryUrl)
359
- .post('/registry/transfer-instruction/v1/transfer-factory', {
360
- choiceArguments: choiceArgs,
361
- });
362
- }
363
- async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
364
- this.logger.debug('Creating transfer from pre-fetched context...');
365
- choiceArgs.extraArgs.context = {
366
- ...choiceContext.choiceContextData,
367
- values: choiceContext.choiceContextData?.values ?? {},
368
- };
369
- const exercise = {
370
- templateId: TRANSFER_FACTORY_INTERFACE_ID,
371
- contractId: factoryId,
372
- choice: 'TransferFactory_Transfer',
373
- choiceArgument: choiceArgs,
374
- };
375
- return [exercise, choiceContext.disclosedContracts];
376
- }
377
- async createTransfer(sender, receiver, amount, instrumentAdmin, // TODO (#907): replace with registry call
378
- instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext) {
379
- try {
380
- const choiceArgs = await this.buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta);
381
- if (prefetchedRegistryChoiceContext) {
382
- return this.createTransferFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
383
- }
384
- const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(registryUrl, choiceArgs);
385
- return this.createTransferFromContext(factoryId, choiceArgs, choiceContext);
386
- }
387
- catch (e) {
388
- this.logger.error('Failed to execute transfer:', e);
389
- throw e;
390
- }
391
- }
392
- async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
393
- const client = this.core.getTokenStandardClient(registryUrl);
394
- const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept', {}, {
395
- path: {
396
- transferInstructionId: transferInstructionCid,
397
- },
398
- });
399
- return {
400
- choiceContextData: choiceContext.choiceContextData,
401
- disclosedContracts: choiceContext.disclosedContracts,
402
- };
403
- }
404
- async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
405
- try {
406
- const exercise = {
407
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
408
- contractId: transferInstructionCid,
409
- choice: 'TransferInstruction_Accept',
410
- choiceArgument: {
411
- extraArgs: {
412
- context: choiceContext.choiceContextData,
413
- meta: { values: {} },
414
- },
415
- },
416
- };
417
- return [exercise, choiceContext.disclosedContracts];
418
- }
419
- catch (e) {
420
- this.logger.error('Failed to create accept transfer instruction:', e);
421
- throw e;
422
- }
423
- }
424
- async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
425
- const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(transferInstructionCid, registryUrl.href);
426
- const choiceArgs = {
427
- cid: acceptTransferInstructionContext.contractId,
428
- proxyArg: {
429
- featuredAppRightCid: featuredAppRightCid,
430
- beneficiaries: beneficiaries,
431
- choiceArg: acceptTransferInstructionContext.choiceArgument,
432
- },
433
- };
434
- return [
435
- {
436
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
437
- contractId: proxyCid,
438
- choice: 'DelegateProxy_TransferInstruction_Accept',
439
- choiceArgument: choiceArgs,
440
- },
441
- disclosedContracts,
442
- ];
443
- }
444
- async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
445
- const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(transferInstructionCid, registryUrl.href);
446
- const choiceArgs = {
447
- cid: rejectTransferInstructionContext.contractId,
448
- proxyArg: {
449
- featuredAppRightCid: featuredAppRightCid,
450
- beneficiaries,
451
- choiceArg: rejectTransferInstructionContext.choiceArgument,
452
- },
453
- };
454
- return [
455
- {
456
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
457
- contractId: proxyCid,
458
- choice: 'DelegateProxy_TransferInstruction_Reject',
459
- choiceArgument: choiceArgs,
460
- },
461
- disclosedContracts,
462
- ];
463
- }
464
- async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
465
- const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl.href);
466
- const sumOfWeights = beneficiaries.reduce((totalWeight, beneficiary) => totalWeight + beneficiary.weight, 0);
467
- if (sumOfWeights > 1.0) {
468
- throw new Error('Sum of beneficiary weights is larger than 1.');
469
- }
470
- const choiceArgs = {
471
- cid: withdrawTransferInstructionContext.contractId,
472
- proxyArg: {
473
- featuredAppRightCid: featuredAppRightCid,
474
- beneficiaries,
475
- choiceArg: withdrawTransferInstructionContext.choiceArgument,
476
- },
477
- };
478
- return [
479
- {
480
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
481
- contractId: proxyCid,
482
- choice: 'DelegateProxy_TransferInstruction_Withdraw',
483
- choiceArgument: choiceArgs,
484
- },
485
- disclosedContracts,
486
- ];
487
- }
488
- async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
489
- if (prefetchedRegistryChoiceContext) {
490
- return this.createAcceptTransferInstructionFromContext(transferInstructionCid, {
491
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
492
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts,
493
- });
494
- }
495
- const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
496
- return this.createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext);
497
- }
498
- async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
499
- const client = this.core.getTokenStandardClient(registryUrl);
500
- const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject', {}, {
501
- path: {
502
- transferInstructionId: transferInstructionCid,
503
- },
504
- });
505
- return {
506
- choiceContextData: choiceContext.choiceContextData,
507
- disclosedContracts: choiceContext.disclosedContracts,
508
- };
509
- }
510
- async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
511
- try {
512
- const exercise = {
513
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
514
- contractId: transferInstructionCid,
515
- choice: 'TransferInstruction_Reject',
516
- choiceArgument: {
517
- extraArgs: {
518
- context: choiceContext.choiceContextData,
519
- meta: { values: {} },
520
- },
521
- },
522
- };
523
- return [exercise, choiceContext.disclosedContracts];
524
- }
525
- catch (e) {
526
- this.logger.error('Failed to create reject transfer instruction:', e);
527
- throw e;
528
- }
529
- }
530
- async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
531
- if (prefetchedRegistryChoiceContext) {
532
- return this.createRejectTransferInstructionFromContext(transferInstructionCid, {
533
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
534
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts,
535
- });
536
- }
537
- const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
538
- return this.createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext);
539
- }
540
- async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
541
- const client = this.core.getTokenStandardClient(registryUrl);
542
- const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw', {}, {
543
- path: {
544
- transferInstructionId: transferInstructionCid,
545
- },
546
- });
547
- return {
548
- choiceContextData: choiceContext.choiceContextData,
549
- disclosedContracts: choiceContext.disclosedContracts,
550
- };
551
- }
552
- async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
553
- try {
554
- const exercise = {
555
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
556
- contractId: transferInstructionCid,
557
- choice: 'TransferInstruction_Withdraw',
558
- choiceArgument: {
559
- extraArgs: {
560
- context: choiceContext.choiceContextData,
561
- meta: { values: {} },
562
- },
563
- },
564
- };
565
- return [exercise, choiceContext.disclosedContracts];
566
- }
567
- catch (e) {
568
- this.logger.error('Failed to create withdraw transfer instruction:', e);
569
- throw e;
570
- }
571
- }
572
- async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
573
- if (prefetchedRegistryChoiceContext) {
574
- return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, {
575
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
576
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts,
577
- });
578
- }
579
- const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
580
- return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext);
581
- }
582
- }
583
- export class TokenStandardService {
584
- ledgerClient;
585
- scanProxyClient;
586
- logger;
587
- accessToken;
588
- isMasterUser;
589
- core;
590
- allocation;
591
- transfer;
592
- constructor(ledgerClient, scanProxyClient, logger, accessToken, isMasterUser) {
593
- this.ledgerClient = ledgerClient;
594
- this.scanProxyClient = scanProxyClient;
595
- this.logger = logger;
596
- this.accessToken = accessToken;
597
- this.isMasterUser = isMasterUser;
598
- this.core = new CoreService(ledgerClient, scanProxyClient, logger, accessToken, isMasterUser);
599
- this.allocation = new AllocationService(this.core, this.logger);
600
- this.transfer = new TransferService(this.core, this.logger);
601
- }
602
- async getTransferPreApprovalByParty(partyId) {
603
- const { transfer_preapproval } = await this.scanProxyClient.get('/v0/scan-proxy/transfer-preapprovals/by-party/{party}', {
604
- path: {
605
- party: partyId,
606
- },
607
- });
608
- return transfer_preapproval;
609
- }
610
- async getFeaturedAppsByParty(partyId) {
611
- const { featured_app_right } = await this.scanProxyClient.get('/v0/scan-proxy/featured-apps/{provider_party_id}', {
612
- path: {
613
- provider_party_id: partyId,
614
- },
615
- });
616
- return featured_app_right;
617
- }
618
- async getInstrumentById(registryUrl, instrumentId) {
619
- try {
620
- const params = {
621
- path: {
622
- instrumentId,
623
- },
624
- };
625
- const client = this.core.getTokenStandardClient(registryUrl);
626
- return client.get('/registry/metadata/v1/instruments/{instrumentId}', params);
627
- }
628
- catch (e) {
629
- this.logger.error(e);
630
- throw new Error(`Instrument id ${instrumentId} does not exist for this instrument admin.`);
631
- }
632
- }
633
- async getInstrumentAdmin(registryUrl) {
634
- const client = this.core.getTokenStandardClient(registryUrl);
635
- const info = await client.get('/registry/metadata/v1/info');
636
- return info.adminId;
637
- }
638
- // <T> is shape of viewValue related to queried interface.
639
- // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
640
- async listContractsByInterface(interfaceId, partyId, limit) {
641
- return this.core.listContractsByInterface(interfaceId, partyId, limit);
642
- }
643
- async listHoldingTransactions(partyId, afterOffset, beforeOffset) {
644
- try {
645
- this.logger.debug('Set or query offset');
646
- const afterOffsetOrLatest = Number(afterOffset) ||
647
- (await this.ledgerClient.getWithRetry('/v2/state/latest-pruned-offsets')).participantPrunedUpToInclusive;
648
- const beforeOffsetOrLatest = Number(beforeOffset) ||
649
- (await this.ledgerClient.getWithRetry('/v2/state/ledger-end'))
650
- .offset;
651
- this.logger.debug(afterOffsetOrLatest, 'Using offset');
652
- const updatesResponse = await this.ledgerClient.postWithRetry('/v2/updates/flats', {
653
- updateFormat: {
654
- includeTransactions: {
655
- eventFormat: EventFilterBySetup(TokenStandardTransactionInterfaces, {
656
- includeWildcard: true,
657
- isMasterUser: this.isMasterUser,
658
- partyId: partyId,
659
- }),
660
- transactionShape: 'TRANSACTION_SHAPE_LEDGER_EFFECTS',
661
- },
662
- },
663
- beginExclusive: afterOffsetOrLatest,
664
- endInclusive: beforeOffsetOrLatest,
665
- verbose: false,
666
- });
667
- return this.core.toPrettyTransactions(updatesResponse, partyId, this.ledgerClient);
668
- }
669
- catch (err) {
670
- this.logger.error('Failed to list holding transactions.', err);
671
- throw err;
672
- }
673
- }
674
- async getTransactionById(updateId, partyId) {
675
- const transactionFormat = {
676
- eventFormat: EventFilterBySetup(TokenStandardTransactionInterfaces, {
677
- includeWildcard: true,
678
- isMasterUser: this.isMasterUser,
679
- partyId: partyId,
680
- }),
681
- transactionShape: 'TRANSACTION_SHAPE_LEDGER_EFFECTS',
682
- };
683
- const getTransactionResponse = await this.ledgerClient.postWithRetry('/v2/updates/transaction-by-id', {
684
- updateId,
685
- transactionFormat,
686
- });
687
- return this.core.toPrettyTransaction(getTransactionResponse, partyId, this.ledgerClient);
688
- }
689
- async getInputHoldingsCids(sender, inputUtxos) {
690
- return this.core.getInputHoldingsCids(sender, inputUtxos);
691
- }
692
- async createDelegateProxyTranfser(sender, receiver, amount, instrumentAdmin, // TODO (#907): replace with registry call
693
- instrumentId, registryUrl, featuredAppRightCid, proxyCid, beneficiaries, inputUtxos, memo, expiryDate, meta) {
694
- const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta);
695
- const sumOfWeights = beneficiaries.reduce((totalWeight, beneficiary) => totalWeight + beneficiary.weight, 0);
696
- if (sumOfWeights > 1.0) {
697
- throw new Error('Sum of beneficiary weights is larger than 1.');
698
- }
699
- const choiceArgs = {
700
- cid: transferCommand.contractId,
701
- proxyArg: {
702
- featuredAppRightCid: featuredAppRightCid,
703
- beneficiaries,
704
- choiceArg: transferCommand.choiceArgument,
705
- },
706
- };
707
- const exercise = {
708
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
709
- contractId: proxyCid,
710
- choice: 'DelegateProxy_TransferFactory_Transfer',
711
- choiceArgument: choiceArgs,
712
- };
713
- return [exercise, disclosedContracts];
714
- }
715
- // TODO(#583) as it's not a part of token standard, should be moved somewhere else
716
- async createTap(receiver, amount, instrumentAdmin, // TODO (#907): replace with registry call
717
- instrumentId, registryUrl) {
718
- const now = new Date();
719
- const tomorrow = new Date(now);
720
- tomorrow.setDate(tomorrow.getDate() + 1);
721
- const choiceArgs = {
722
- expectedAdmin: instrumentAdmin,
723
- transfer: {
724
- sender: instrumentAdmin,
725
- receiver,
726
- amount,
727
- instrumentId: { admin: instrumentAdmin, id: instrumentId },
728
- lock: null,
729
- requestedAt: new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
730
- executeBefore: tomorrow.toISOString(),
731
- inputHoldingCids: [],
732
- meta: { values: {} },
733
- },
734
- extraArgs: {
735
- context: { values: {} },
736
- meta: { values: {} },
737
- },
738
- };
739
- const transferFactory = await this.core
740
- .getTokenStandardClient(registryUrl)
741
- .post('/registry/transfer-instruction/v1/transfer-factory', {
742
- choiceArguments: choiceArgs,
743
- });
744
- const disclosedContracts = transferFactory.choiceContext.disclosedContracts;
745
- const amuletRules = await this.scanProxyClient.getAmuletRules();
746
- if (!amuletRules) {
747
- throw new Error('AmuletRules contract not found');
748
- }
749
- const latestOpenMiningRound = await this.core.getActiveOpenMiningRound();
750
- if (!latestOpenMiningRound) {
751
- throw new Error('OpenMiningRound active at current moment not found');
752
- }
753
- return [
754
- {
755
- templateId: amuletRules.template_id,
756
- contractId: amuletRules.contract_id,
757
- choice: 'AmuletRules_DevNet_Tap',
758
- choiceArgument: {
759
- receiver,
760
- amount,
761
- openRound: latestOpenMiningRound.contract_id,
762
- },
763
- },
764
- disclosedContracts,
765
- ];
766
- }
767
- async selfGrantFeatureAppRight(providerPartyId, synchronizerId) {
768
- const amuletRules = await this.scanProxyClient.getAmuletRules();
769
- const disclosedContracts = {
770
- templateId: amuletRules.template_id,
771
- contractId: amuletRules.contract_id,
772
- createdEventBlob: amuletRules.created_event_blob,
773
- synchronizerId,
774
- };
775
- return [
776
- {
777
- templateId: amuletRules.template_id,
778
- contractId: amuletRules.contract_id,
779
- choice: 'AmuletRules_DevNet_FeatureApp',
780
- choiceArgument: {
781
- provider: providerPartyId,
782
- },
783
- },
784
- [disclosedContracts],
785
- ];
786
- }
787
- async cancelTransferPreapproval(contractId, templateId, actor) {
788
- const exercise = {
789
- templateId,
790
- contractId,
791
- choice: 'TransferPreapproval_Cancel',
792
- choiceArgument: { p: actor },
793
- };
794
- return [exercise, []];
795
- }
796
- async renewTransferPreapproval(contractId, templateId, provider, synchronizerId, newExpiresAt, inputUtxos) {
797
- const amuletRules = await this.scanProxyClient.getAmuletRules();
798
- const activeRound = await this.core.getActiveOpenMiningRound();
799
- if (!amuletRules) {
800
- throw new Error('AmuletRules contract not found');
801
- }
802
- if (!activeRound) {
803
- throw new Error('OpenMiningRound active at current moment not found');
804
- }
805
- const disclosed = [
806
- {
807
- templateId: amuletRules.template_id,
808
- contractId: amuletRules.contract_id,
809
- createdEventBlob: amuletRules.created_event_blob,
810
- synchronizerId,
811
- },
812
- {
813
- templateId: activeRound.template_id,
814
- contractId: activeRound.contract_id,
815
- createdEventBlob: activeRound.created_event_blob,
816
- synchronizerId,
817
- },
818
- ];
819
- const inputHoldings = await this.core.getInputHoldingsCids(provider, inputUtxos);
820
- const context = {
821
- context: {
822
- openMiningRound: activeRound.contract_id,
823
- issuingMiningRounds: [],
824
- validatorRights: [],
825
- featuredAppRight: null,
826
- },
827
- amuletRules: amuletRules.contract_id,
828
- };
829
- // Defaults to 90 days
830
- const effectiveNewExpiresAt = newExpiresAt ?? new Date(Date.now() + 90 * 24 * 3600 * 1000);
831
- const exercise = {
832
- templateId,
833
- contractId,
834
- choice: 'TransferPreapproval_Renew',
835
- choiceArgument: {
836
- context,
837
- inputs: inputHoldings.map((cid) => ({
838
- tag: 'InputAmulet',
839
- value: cid,
840
- })),
841
- newExpiresAt: effectiveNewExpiresAt.toISOString(),
842
- },
843
- };
844
- return [exercise, disclosed];
845
- }
846
- async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
847
- const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(transferInstructionCid, registryUrl);
848
- const choiceArgs = {
849
- cid: acceptTransferInstructionContext.contractId,
850
- proxyArg: {
851
- featuredAppRightCid: featuredAppRightCid,
852
- beneficiaries: [
853
- {
854
- beneficiary: exchangeParty,
855
- weight: 1.0,
856
- },
857
- ],
858
- choiceArg: acceptTransferInstructionContext.choiceArgument,
859
- },
860
- };
861
- return [
862
- {
863
- templateId: '#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy',
864
- contractId: proxyCid,
865
- choice: 'DelegateProxy_TransferInstruction_Accept',
866
- choiceArgument: choiceArgs,
867
- },
868
- disclosedContracts,
869
- ];
870
- }
871
- }