@canton-network/core-ledger-client 0.10.0 → 0.12.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.
@@ -1,66 +1,393 @@
1
1
  // Copyright (c) 2025 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
- import { TokenStandardClient, } from '@canton-network/core-token-standard';
4
- import { HoldingInterface, TokenStandardTransactionInterfaces, TransferFactoryInterface, TransferInstructionInterface, } from './constants.js';
5
- import { ensureInterfaceViewIsPresent, filtersByParty, } from './ledger-api-utils.js';
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, } from '@canton-network/core-token-standard';
4
+ import { TokenStandardTransactionInterfaces } from './constants.js';
5
+ import { ensureInterfaceViewIsPresent, TransactionFilterBySetup, EventFilterBySetup, } from './ledger-api-utils.js';
6
6
  import { TransactionParser } from './txparse/parser.js';
7
7
  import { renderTransaction, } from './txparse/types.js';
8
8
  const MEMO_KEY = 'splice.lfdecentralizedtrust.org/reason';
9
- export class TokenStandardService {
9
+ const REQUESTED_AT_SKEW_MS = 60_000;
10
+ const EMPTY_META = { values: {} };
11
+ class CoreService {
10
12
  ledgerClient;
11
13
  scanProxyClient;
12
14
  logger;
13
15
  accessToken;
14
- constructor(ledgerClient, scanProxyClient, logger, accessToken) {
16
+ isMasterUser;
17
+ constructor(ledgerClient, scanProxyClient, logger, accessToken, isMasterUser) {
15
18
  this.ledgerClient = ledgerClient;
16
19
  this.scanProxyClient = scanProxyClient;
17
20
  this.logger = logger;
18
21
  this.accessToken = accessToken;
22
+ this.isMasterUser = isMasterUser;
19
23
  }
20
24
  getTokenStandardClient(registryUrl) {
21
25
  return new TokenStandardClient(registryUrl, this.logger, this.accessToken);
22
26
  }
23
- async getTransferPreApprovalByParty(partyId) {
24
- const { transfer_preapproval } = await this.scanProxyClient.get('/v0/scan-proxy/transfer-preapprovals/by-party/{party}', {
25
- path: {
26
- party: partyId,
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) {
54
+ try {
55
+ const ledgerEnd = await this.ledgerClient.get('/v2/state/ledger-end');
56
+ const acsResponses = await this.ledgerClient.post('/v2/state/active-contracts', {
57
+ filter: TransactionFilterBySetup(interfaceId, {
58
+ isMasterUser: this.isMasterUser,
59
+ partyId: partyId,
60
+ }),
61
+ verbose: false,
62
+ activeAtOffset: ledgerEnd.offset,
63
+ });
64
+ /* This filters out responses with entries of:
65
+ - JsEmpty
66
+ - JsIncompleteAssigned
67
+ - JsIncompleteUnassigned
68
+ while leaving JsActiveContract.
69
+ It works fine only with single synchronizer
70
+ TODO (#353) add support for multiple synchronizers
71
+ */
72
+ const isActiveContractEntry = (acsResponse) => !!acsResponse.contractEntry.JsActiveContract?.createdEvent;
73
+ const activeContractEntries = acsResponses.filter(isActiveContractEntry);
74
+ return activeContractEntries.map((response) => this.toPrettyContract(interfaceId, response));
75
+ }
76
+ catch (err) {
77
+ this.logger.error(`Failed to list contracts of interface ${interfaceId}`, err);
78
+ throw err;
79
+ }
80
+ }
81
+ async toPrettyTransactions(updates, partyId, ledgerClient) {
82
+ // Runtime filters that also let TS know which of OneOfs types to check against
83
+ const isOffsetCheckpointUpdate = (updateResponse) => !!updateResponse?.update?.OffsetCheckpoint;
84
+ const isTransactionUpdate = (updateResponse) => !!updateResponse.update?.Transaction?.value;
85
+ const offsetCheckpoints = updates
86
+ .filter(isOffsetCheckpointUpdate)
87
+ .map((update) => update.update.OffsetCheckpoint.value.offset);
88
+ const latestCheckpointOffset = Math.max(...offsetCheckpoints);
89
+ const transactions = await Promise.all(updates
90
+ // exclude OffsetCheckpoint, Reassignment, TopologyTransaction
91
+ .filter(isTransactionUpdate)
92
+ .map(async (update) => {
93
+ const tx = update.update.Transaction.value;
94
+ const parser = new TransactionParser(tx, ledgerClient, partyId, this.isMasterUser);
95
+ return await parser.parseTransaction();
96
+ }));
97
+ return {
98
+ // OffsetCheckpoint can be anywhere... or not at all, maybe
99
+ nextOffset: Math.max(latestCheckpointOffset, ...transactions.map((tx) => tx.offset)),
100
+ transactions: transactions
101
+ .filter((tx) => tx.events.length > 0)
102
+ .map(renderTransaction),
103
+ };
104
+ }
105
+ async toPrettyTransaction(getTransactionResponse, partyId, ledgerClient) {
106
+ const tx = getTransactionResponse.transaction;
107
+ const parser = new TransactionParser(tx, ledgerClient, partyId, this.isMasterUser);
108
+ const parsedTx = await parser.parseTransaction();
109
+ return renderTransaction(parsedTx);
110
+ }
111
+ async toPrettyTransactionsPerParty(updates, parties, ledgerClient) {
112
+ const all = await Promise.all(parties.map(async (partyId) => [
113
+ partyId,
114
+ await this.toPrettyTransactions(updates, partyId, ledgerClient),
115
+ ]));
116
+ return new Map(all);
117
+ }
118
+ // returns object with JsActiveContract content
119
+ // and contractId and interface view value extracted from it as separate fields for convenience
120
+ toPrettyContract(interfaceId, response) {
121
+ const activeContract = response.contractEntry.JsActiveContract;
122
+ const { createdEvent } = activeContract;
123
+ return {
124
+ contractId: createdEvent.contractId,
125
+ activeContract,
126
+ interfaceViewValue: ensureInterfaceViewIsPresent(createdEvent, interfaceId).viewValue,
127
+ };
128
+ }
129
+ }
130
+ class AllocationService {
131
+ core;
132
+ logger;
133
+ constructor(core, logger) {
134
+ this.core = core;
135
+ this.logger = logger;
136
+ }
137
+ async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
138
+ const allocationSpecificationNormalized = {
139
+ ...allocationSpecification,
140
+ settlement: {
141
+ ...allocationSpecification.settlement,
142
+ meta: allocationSpecification.settlement.meta ?? { values: {} },
143
+ },
144
+ transferLeg: {
145
+ ...allocationSpecification.transferLeg,
146
+ meta: allocationSpecification.transferLeg.meta ?? {
147
+ values: {},
148
+ },
149
+ },
150
+ };
151
+ const inputHoldingCids = await this.core.getInputHoldingsCids(allocationSpecificationNormalized.transferLeg.sender, inputUtxos);
152
+ return {
153
+ expectedAdmin,
154
+ allocation: allocationSpecificationNormalized,
155
+ requestedAt: requestedAt ??
156
+ new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
157
+ inputHoldingCids,
158
+ extraArgs: {
159
+ context: { values: {} },
160
+ meta: { values: {} },
27
161
  },
162
+ };
163
+ }
164
+ async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs) {
165
+ return this.core
166
+ .getTokenStandardClient(registryUrl)
167
+ .post('/registry/allocation-instruction/v1/allocation-factory', {
168
+ choiceArguments: choiceArgs,
28
169
  });
29
- return transfer_preapproval;
30
170
  }
31
- async getFeaturedAppsByParty(partyId) {
32
- const { featured_app_right } = await this.scanProxyClient.get('/v0/scan-proxy/featured-apps/{provider_party_id}', {
171
+ async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
172
+ choiceArgs.extraArgs.context = {
173
+ ...choiceContext.choiceContextData,
174
+ values: choiceContext.choiceContextData?.values ?? {},
175
+ };
176
+ const exercise = {
177
+ templateId: ALLOCATION_FACTORY_INTERFACE_ID,
178
+ contractId: factoryId,
179
+ choice: 'AllocationFactory_Allocate',
180
+ choiceArgument: choiceArgs,
181
+ };
182
+ return [exercise, choiceContext.disclosedContracts];
183
+ }
184
+ async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
185
+ const choiceArgs = await this.buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt);
186
+ if (prefetchedRegistryChoiceContext) {
187
+ return this.createAllocationInstructionFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
188
+ }
189
+ const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs);
190
+ return this.createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext);
191
+ }
192
+ buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
193
+ const exercise = {
194
+ templateId,
195
+ contractId,
196
+ choice,
197
+ choiceArgument: {
198
+ extraArgs: {
199
+ context: choiceContext.choiceContextData,
200
+ meta: EMPTY_META,
201
+ },
202
+ },
203
+ };
204
+ return [exercise, choiceContext.disclosedContracts ?? []];
205
+ }
206
+ async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
207
+ return this.core.getTokenStandardClient(registryUrl).post('/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer', {}, {
33
208
  path: {
34
- provider_party_id: partyId,
209
+ allocationId,
35
210
  },
36
211
  });
37
- return featured_app_right;
38
212
  }
39
- async getInstrumentById(transferFactoryRegistryUrl, instrumentId) {
40
- try {
41
- const params = {
42
- path: {
43
- instrumentId,
213
+ createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
214
+ return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, 'Allocation_ExecuteTransfer', choiceContext);
215
+ }
216
+ async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
217
+ if (prefetchedRegistryChoiceContext) {
218
+ return this.createExecuteTransferAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
219
+ }
220
+ const choiceContext = await this.fetchExecuteTransferChoiceContext(allocationCid, registryUrl);
221
+ return this.createExecuteTransferAllocationFromContext(allocationCid, choiceContext);
222
+ }
223
+ async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
224
+ return this.core
225
+ .getTokenStandardClient(registryUrl)
226
+ .post('/registry/allocations/v1/{allocationId}/choice-contexts/withdraw', {}, { path: { allocationId: allocationCid } });
227
+ }
228
+ createWithdrawAllocationFromContext(allocationCid, choiceContext) {
229
+ return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, 'Allocation_Withdraw', choiceContext);
230
+ }
231
+ async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
232
+ if (prefetchedRegistryChoiceContext) {
233
+ return this.createWithdrawAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
234
+ }
235
+ const choiceContext = await this.fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl);
236
+ return this.createWithdrawAllocationFromContext(allocationCid, choiceContext);
237
+ }
238
+ async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
239
+ return this.core
240
+ .getTokenStandardClient(registryUrl)
241
+ .post('/registry/allocations/v1/{allocationId}/choice-contexts/cancel', {}, { path: { allocationId: allocationCid } });
242
+ }
243
+ createCancelAllocationFromContext(allocationCid, choiceContext) {
244
+ return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, 'Allocation_Cancel', choiceContext);
245
+ }
246
+ async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
247
+ if (prefetchedRegistryChoiceContext) {
248
+ return this.createCancelAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
249
+ }
250
+ const choiceContext = await this.fetchCancelAllocationChoiceContext(allocationCid, registryUrl);
251
+ return this.createCancelAllocationFromContext(allocationCid, choiceContext);
252
+ }
253
+ async createWithdrawAllocationInstruction(allocationInstructionCid) {
254
+ const exercise = {
255
+ templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
256
+ contractId: allocationInstructionCid,
257
+ choice: 'AllocationInstruction_Withdraw',
258
+ choiceArgument: {
259
+ extraArgs: {
260
+ context: { values: {} },
261
+ meta: { values: {} },
44
262
  },
45
- };
46
- const client = this.getTokenStandardClient(transferFactoryRegistryUrl);
47
- return client.get('/registry/metadata/v1/instruments/{instrumentId}', params);
263
+ },
264
+ };
265
+ return [exercise, []];
266
+ }
267
+ async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
268
+ const exercise = {
269
+ templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
270
+ contractId: allocationInstructionCid,
271
+ choice: 'AllocationInstruction_Update',
272
+ choiceArgument: {
273
+ extraActors,
274
+ extraArgs: {
275
+ context: { values: extraArgsContext },
276
+ meta: { values: extraArgsMeta },
277
+ },
278
+ },
279
+ };
280
+ return [exercise, []];
281
+ }
282
+ async createRejectAllocationRequest(allocationRequestCid, actor) {
283
+ const exercise = {
284
+ templateId: ALLOCATION_REQUEST_INTERFACE_ID,
285
+ contractId: allocationRequestCid,
286
+ choice: 'AllocationRequest_Reject',
287
+ choiceArgument: {
288
+ actor,
289
+ extraArgs: {
290
+ context: { values: {} },
291
+ meta: { values: {} },
292
+ },
293
+ },
294
+ };
295
+ return [exercise, []];
296
+ }
297
+ async createWithdrawAllocationRequest(allocationRequestCid) {
298
+ const exercise = {
299
+ templateId: ALLOCATION_REQUEST_INTERFACE_ID,
300
+ contractId: allocationRequestCid,
301
+ choice: 'AllocationRequest_Withdraw',
302
+ choiceArgument: {
303
+ extraArgs: {
304
+ context: { values: {} },
305
+ meta: { values: {} },
306
+ },
307
+ },
308
+ };
309
+ return [exercise, []];
310
+ }
311
+ }
312
+ class TransferService {
313
+ core;
314
+ logger;
315
+ constructor(core, logger) {
316
+ this.core = core;
317
+ this.logger = logger;
318
+ }
319
+ async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta) {
320
+ const inputHoldingCids = await this.core.getInputHoldingsCids(sender, inputUtxos);
321
+ return {
322
+ expectedAdmin: instrumentAdmin,
323
+ transfer: {
324
+ sender,
325
+ receiver,
326
+ amount,
327
+ instrumentId: { admin: instrumentAdmin, id: instrumentId },
328
+ requestedAt: new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
329
+ executeBefore: (expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1000)).toISOString(),
330
+ inputHoldingCids,
331
+ meta: { values: { [MEMO_KEY]: memo || '', ...meta?.values } },
332
+ },
333
+ extraArgs: {
334
+ context: { values: {} },
335
+ meta: { values: {} },
336
+ },
337
+ };
338
+ }
339
+ async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs) {
340
+ return await this.core
341
+ .getTokenStandardClient(registryUrl)
342
+ .post('/registry/transfer-instruction/v1/transfer-factory', {
343
+ choiceArguments: choiceArgs,
344
+ });
345
+ }
346
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
347
+ this.logger.debug('Creating transfer from pre-fetched context...');
348
+ choiceArgs.extraArgs.context = {
349
+ ...choiceContext.choiceContextData,
350
+ values: choiceContext.choiceContextData?.values ?? {},
351
+ };
352
+ const exercise = {
353
+ templateId: TRANSFER_FACTORY_INTERFACE_ID,
354
+ contractId: factoryId,
355
+ choice: 'TransferFactory_Transfer',
356
+ choiceArgument: choiceArgs,
357
+ };
358
+ return [exercise, choiceContext.disclosedContracts];
359
+ }
360
+ async createTransfer(sender, receiver, amount, instrumentAdmin, // TODO (#907): replace with registry call
361
+ instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext) {
362
+ try {
363
+ const choiceArgs = await this.buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta);
364
+ if (prefetchedRegistryChoiceContext) {
365
+ return this.createTransferFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
366
+ }
367
+ const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(registryUrl, choiceArgs);
368
+ return this.createTransferFromContext(factoryId, choiceArgs, choiceContext);
48
369
  }
49
370
  catch (e) {
50
- this.logger.error(e);
51
- throw new Error(`Instrument id ${instrumentId} does not exist for this instrument admin.`);
371
+ this.logger.error('Failed to execute transfer:', e);
372
+ throw e;
52
373
  }
53
374
  }
54
- async createAcceptTransferInstruction(transferInstructionCid, transferFactoryRegistryUrl) {
375
+ async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
376
+ const client = this.core.getTokenStandardClient(registryUrl);
377
+ const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept', {}, {
378
+ path: {
379
+ transferInstructionId: transferInstructionCid,
380
+ },
381
+ });
382
+ return {
383
+ choiceContextData: choiceContext.choiceContextData,
384
+ disclosedContracts: choiceContext.disclosedContracts,
385
+ };
386
+ }
387
+ async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
55
388
  try {
56
- const client = this.getTokenStandardClient(transferFactoryRegistryUrl);
57
- const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept', {}, {
58
- path: {
59
- transferInstructionId: transferInstructionCid,
60
- },
61
- });
62
389
  const exercise = {
63
- templateId: TransferInstructionInterface,
390
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
64
391
  contractId: transferInstructionCid,
65
392
  choice: 'TransferInstruction_Accept',
66
393
  choiceArgument: {
@@ -77,21 +404,32 @@ export class TokenStandardService {
77
404
  throw e;
78
405
  }
79
406
  }
80
- async getInstrumentAdmin(transferFactoryRegistryUrl) {
81
- const client = this.getTokenStandardClient(transferFactoryRegistryUrl);
82
- const info = await client.get('/registry/metadata/v1/info');
83
- return info.adminId;
407
+ async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
408
+ if (prefetchedRegistryChoiceContext) {
409
+ return this.createAcceptTransferInstructionFromContext(transferInstructionCid, {
410
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
411
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts,
412
+ });
413
+ }
414
+ const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
415
+ return this.createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext);
84
416
  }
85
- async createRejectTransferInstruction(transferInstructionCid, transferFactoryRegistryUrl) {
417
+ async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
418
+ const client = this.core.getTokenStandardClient(registryUrl);
419
+ const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject', {}, {
420
+ path: {
421
+ transferInstructionId: transferInstructionCid,
422
+ },
423
+ });
424
+ return {
425
+ choiceContextData: choiceContext.choiceContextData,
426
+ disclosedContracts: choiceContext.disclosedContracts,
427
+ };
428
+ }
429
+ async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
86
430
  try {
87
- const client = this.getTokenStandardClient(transferFactoryRegistryUrl);
88
- const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject', {}, {
89
- path: {
90
- transferInstructionId: transferInstructionCid,
91
- },
92
- });
93
431
  const exercise = {
94
- templateId: TransferInstructionInterface,
432
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
95
433
  contractId: transferInstructionCid,
96
434
  choice: 'TransferInstruction_Reject',
97
435
  choiceArgument: {
@@ -108,16 +446,32 @@ export class TokenStandardService {
108
446
  throw e;
109
447
  }
110
448
  }
111
- async createWithdrawTransferInstruction(transferInstructionCid, transferFactoryRegistryUrl) {
112
- try {
113
- const client = this.getTokenStandardClient(transferFactoryRegistryUrl);
114
- const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw', {}, {
115
- path: {
116
- transferInstructionId: transferInstructionCid,
117
- },
449
+ async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
450
+ if (prefetchedRegistryChoiceContext) {
451
+ return this.createRejectTransferInstructionFromContext(transferInstructionCid, {
452
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
453
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts,
118
454
  });
455
+ }
456
+ const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
457
+ return this.createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext);
458
+ }
459
+ async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
460
+ const client = this.core.getTokenStandardClient(registryUrl);
461
+ const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw', {}, {
462
+ path: {
463
+ transferInstructionId: transferInstructionCid,
464
+ },
465
+ });
466
+ return {
467
+ choiceContextData: choiceContext.choiceContextData,
468
+ disclosedContracts: choiceContext.disclosedContracts,
469
+ };
470
+ }
471
+ async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
472
+ try {
119
473
  const exercise = {
120
- templateId: TransferInstructionInterface,
474
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
121
475
  contractId: transferInstructionCid,
122
476
  choice: 'TransferInstruction_Withdraw',
123
477
  choiceArgument: {
@@ -134,35 +488,77 @@ export class TokenStandardService {
134
488
  throw e;
135
489
  }
136
490
  }
137
- // <T> is shape of viewValue related to queried interface.
138
- // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
139
- async listContractsByInterface(interfaceId, partyId) {
491
+ async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
492
+ if (prefetchedRegistryChoiceContext) {
493
+ return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, {
494
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
495
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts,
496
+ });
497
+ }
498
+ const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
499
+ return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext);
500
+ }
501
+ }
502
+ export class TokenStandardService {
503
+ ledgerClient;
504
+ scanProxyClient;
505
+ logger;
506
+ accessToken;
507
+ isMasterUser;
508
+ core;
509
+ allocation;
510
+ transfer;
511
+ constructor(ledgerClient, scanProxyClient, logger, accessToken, isMasterUser) {
512
+ this.ledgerClient = ledgerClient;
513
+ this.scanProxyClient = scanProxyClient;
514
+ this.logger = logger;
515
+ this.accessToken = accessToken;
516
+ this.isMasterUser = isMasterUser;
517
+ this.core = new CoreService(ledgerClient, scanProxyClient, logger, accessToken, isMasterUser);
518
+ this.allocation = new AllocationService(this.core, this.logger);
519
+ this.transfer = new TransferService(this.core, this.logger);
520
+ }
521
+ async getTransferPreApprovalByParty(partyId) {
522
+ const { transfer_preapproval } = await this.scanProxyClient.get('/v0/scan-proxy/transfer-preapprovals/by-party/{party}', {
523
+ path: {
524
+ party: partyId,
525
+ },
526
+ });
527
+ return transfer_preapproval;
528
+ }
529
+ async getFeaturedAppsByParty(partyId) {
530
+ const { featured_app_right } = await this.scanProxyClient.get('/v0/scan-proxy/featured-apps/{provider_party_id}', {
531
+ path: {
532
+ provider_party_id: partyId,
533
+ },
534
+ });
535
+ return featured_app_right;
536
+ }
537
+ async getInstrumentById(registryUrl, instrumentId) {
140
538
  try {
141
- const ledgerEnd = await this.ledgerClient.get('/v2/state/ledger-end');
142
- const acsResponses = await this.ledgerClient.post('/v2/state/active-contracts', {
143
- filter: {
144
- filtersByParty: filtersByParty(partyId, [interfaceId], false),
539
+ const params = {
540
+ path: {
541
+ instrumentId,
145
542
  },
146
- verbose: false,
147
- activeAtOffset: ledgerEnd.offset,
148
- });
149
- /* This filters out responses with entries of:
150
- - JsEmpty
151
- - JsIncompleteAssigned
152
- - JsIncompleteUnassigned
153
- while leaving JsActiveContract.
154
- It works fine only with single synchronizer
155
- TODO (#353) add support for multiple synchronizers
156
- */
157
- const isActiveContractEntry = (acsResponse) => !!acsResponse.contractEntry.JsActiveContract?.createdEvent;
158
- const activeContractEntries = acsResponses.filter(isActiveContractEntry);
159
- return activeContractEntries.map((response) => this.toPrettyContract(interfaceId, response));
543
+ };
544
+ const client = this.core.getTokenStandardClient(registryUrl);
545
+ return client.get('/registry/metadata/v1/instruments/{instrumentId}', params);
160
546
  }
161
- catch (err) {
162
- this.logger.error(`Failed to list contracts of interface ${interfaceId}`, err);
163
- throw err;
547
+ catch (e) {
548
+ this.logger.error(e);
549
+ throw new Error(`Instrument id ${instrumentId} does not exist for this instrument admin.`);
164
550
  }
165
551
  }
552
+ async getInstrumentAdmin(registryUrl) {
553
+ const client = this.core.getTokenStandardClient(registryUrl);
554
+ const info = await client.get('/registry/metadata/v1/info');
555
+ return info.adminId;
556
+ }
557
+ // <T> is shape of viewValue related to queried interface.
558
+ // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
559
+ async listContractsByInterface(interfaceId, partyId) {
560
+ return this.core.listContractsByInterface(interfaceId, partyId);
561
+ }
166
562
  async listHoldingTransactions(partyId, afterOffset, beforeOffset) {
167
563
  try {
168
564
  this.logger.debug('Set or query offset');
@@ -175,10 +571,11 @@ export class TokenStandardService {
175
571
  const updatesResponse = await this.ledgerClient.post('/v2/updates/flats', {
176
572
  updateFormat: {
177
573
  includeTransactions: {
178
- eventFormat: {
179
- filtersByParty: filtersByParty(partyId, TokenStandardTransactionInterfaces, true),
180
- verbose: false,
181
- },
574
+ eventFormat: EventFilterBySetup(TokenStandardTransactionInterfaces, {
575
+ includeWildcard: true,
576
+ isMasterUser: this.isMasterUser,
577
+ partyId: partyId,
578
+ }),
182
579
  transactionShape: 'TRANSACTION_SHAPE_LEDGER_EFFECTS',
183
580
  },
184
581
  },
@@ -186,7 +583,7 @@ export class TokenStandardService {
186
583
  endInclusive: beforeOffsetOrLatest,
187
584
  verbose: false,
188
585
  });
189
- return this.toPrettyTransactions(updatesResponse, partyId, this.ledgerClient);
586
+ return this.core.toPrettyTransactions(updatesResponse, partyId, this.ledgerClient);
190
587
  }
191
588
  catch (err) {
192
589
  this.logger.error('Failed to list holding transactions.', err);
@@ -194,94 +591,50 @@ export class TokenStandardService {
194
591
  }
195
592
  }
196
593
  async getTransactionById(updateId, partyId) {
197
- const filter = filtersByParty(partyId, TokenStandardTransactionInterfaces, true);
198
594
  const transactionFormat = {
199
- eventFormat: {
200
- filtersByParty: filter,
201
- verbose: false,
202
- },
595
+ eventFormat: EventFilterBySetup(TokenStandardTransactionInterfaces, {
596
+ includeWildcard: true,
597
+ isMasterUser: this.isMasterUser,
598
+ partyId: partyId,
599
+ }),
203
600
  transactionShape: 'TRANSACTION_SHAPE_LEDGER_EFFECTS',
204
601
  };
205
602
  const getTransactionResponse = await this.ledgerClient.post('/v2/updates/transaction-by-id', {
206
603
  updateId,
207
604
  transactionFormat,
208
605
  });
209
- return this.toPrettyTransaction(getTransactionResponse, partyId, this.ledgerClient);
606
+ return this.core.toPrettyTransaction(getTransactionResponse, partyId, this.ledgerClient);
210
607
  }
211
- async createTransfer(sender, receiver, amount, instrumentAdmin, // TODO (#907): replace with registry call
212
- instrumentId, transferFactoryRegistryUrl, inputUtxos, memo, expiryDate, meta) {
213
- try {
214
- let inputHoldingCids;
215
- const now = new Date();
216
- if (inputUtxos && inputUtxos.length > 0) {
217
- inputHoldingCids = inputUtxos;
218
- }
219
- else {
220
- const senderHoldings = await this.listContractsByInterface(HoldingInterface, sender);
221
- if (senderHoldings.length === 0) {
222
- throw new Error("Sender has no holdings, so transfer can't be executed.");
223
- }
224
- inputHoldingCids = senderHoldings
225
- .filter((utxo) => {
226
- //filter out locked holdings
227
- const lock = utxo.interfaceViewValue.lock;
228
- if (!lock)
229
- return true;
230
- const expiresAt = lock.expiresAt;
231
- if (!expiresAt)
232
- return false;
233
- const expiresAtDate = new Date(expiresAt);
234
- return expiresAtDate <= now;
235
- })
236
- .map((h) => h.contractId);
237
- /* TODO: optimize input holding selection, currently if you transfer 10 CC and have 10 inputs of 1000 CC,
238
- then all 10 of those are chose as input.
239
- */
240
- }
241
- const choiceArgs = {
242
- expectedAdmin: instrumentAdmin,
243
- transfer: {
244
- sender,
245
- receiver,
246
- amount,
247
- instrumentId: { admin: instrumentAdmin, id: instrumentId },
248
- lock: null,
249
- requestedAt: now.toISOString(),
250
- //given expiryDate or 24 hours
251
- executeBefore: (expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1000)).toISOString(),
252
- inputHoldingCids,
253
- meta: { values: { [MEMO_KEY]: memo || '', ...meta } },
254
- },
255
- extraArgs: {
256
- context: { values: {} },
257
- meta: { values: {} },
258
- },
259
- };
260
- this.logger.debug('Creating transfer factory...');
261
- const transferFactory = await this.getTokenStandardClient(transferFactoryRegistryUrl).post('/registry/transfer-instruction/v1/transfer-factory', {
262
- choiceArguments: choiceArgs,
263
- });
264
- this.logger.debug(transferFactory, 'Transfer factory created');
265
- choiceArgs.extraArgs.context = {
266
- ...transferFactory.choiceContext.choiceContextData,
267
- values: transferFactory.choiceContext.choiceContextData?.values ??
268
- {},
269
- };
270
- const exercise = {
271
- templateId: TransferFactoryInterface,
272
- contractId: transferFactory.factoryId,
273
- choice: 'TransferFactory_Transfer',
274
- choiceArgument: choiceArgs,
275
- };
276
- return [exercise, transferFactory.choiceContext.disclosedContracts];
277
- }
278
- catch (e) {
279
- this.logger.error('Failed to execute transfer:', e);
280
- throw e;
281
- }
608
+ async getInputHoldingsCids(sender, inputUtxos) {
609
+ return this.core.getInputHoldingsCids(sender, inputUtxos);
610
+ }
611
+ async createDelegateProxyTranfser(sender, receiver, exchangeParty, amount, instrumentAdmin, // TODO (#907): replace with registry call
612
+ instrumentId, registryUrl, featuredAppRightCid, proxyCid, inputUtxos, memo, expiryDate, meta) {
613
+ const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta);
614
+ const choiceArgs = {
615
+ cid: transferCommand.contractId,
616
+ proxyArg: {
617
+ featuredAppRightCid: featuredAppRightCid,
618
+ beneficiaries: [
619
+ {
620
+ beneficiary: exchangeParty,
621
+ weight: 1.0,
622
+ },
623
+ ],
624
+ choiceArg: transferCommand.choiceArgument,
625
+ },
626
+ };
627
+ const exercise = {
628
+ templateId: '#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy',
629
+ contractId: proxyCid,
630
+ choice: 'DelegateProxy_TransferFactory_Transfer',
631
+ choiceArgument: choiceArgs,
632
+ };
633
+ return [exercise, disclosedContracts];
282
634
  }
635
+ // TODO(#583) as it's not a part of token standard, should be moved somewhere else
283
636
  async createTap(receiver, amount, instrumentAdmin, // TODO (#907): replace with registry call
284
- instrumentId, transferFactoryRegistryUrl) {
637
+ instrumentId, registryUrl) {
285
638
  const now = new Date();
286
639
  const tomorrow = new Date(now);
287
640
  tomorrow.setDate(tomorrow.getDate() + 1);
@@ -293,7 +646,7 @@ export class TokenStandardService {
293
646
  amount,
294
647
  instrumentId: { admin: instrumentAdmin, id: instrumentId },
295
648
  lock: null,
296
- requestedAt: now.toISOString(),
649
+ requestedAt: new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
297
650
  executeBefore: tomorrow.toISOString(),
298
651
  inputHoldingCids: [],
299
652
  meta: { values: {} },
@@ -303,7 +656,9 @@ export class TokenStandardService {
303
656
  meta: { values: {} },
304
657
  },
305
658
  };
306
- const transferFactory = await this.getTokenStandardClient(transferFactoryRegistryUrl).post('/registry/transfer-instruction/v1/transfer-factory', {
659
+ const transferFactory = await this.core
660
+ .getTokenStandardClient(registryUrl)
661
+ .post('/registry/transfer-instruction/v1/transfer-factory', {
307
662
  choiceArguments: choiceArgs,
308
663
  });
309
664
  const disclosedContracts = transferFactory.choiceContext.disclosedContracts;
@@ -332,8 +687,8 @@ export class TokenStandardService {
332
687
  contractId: amuletRules.contract_id,
333
688
  choice: 'AmuletRules_DevNet_Tap',
334
689
  choiceArgument: {
335
- receiver: receiver,
336
- amount: amount,
690
+ receiver,
691
+ amount,
337
692
  openRound: latestOpenMiningRound.contract_id,
338
693
  },
339
694
  },
@@ -346,7 +701,7 @@ export class TokenStandardService {
346
701
  templateId: amuletRules.template_id,
347
702
  contractId: amuletRules.contract_id,
348
703
  createdEventBlob: amuletRules.created_event_blob,
349
- synchronizerId: synchronizerId,
704
+ synchronizerId,
350
705
  };
351
706
  return [
352
707
  {
@@ -360,45 +715,4 @@ export class TokenStandardService {
360
715
  [disclosedContracts],
361
716
  ];
362
717
  }
363
- async toPrettyTransactions(updates, partyId, ledgerClient) {
364
- // Runtime filters that also let TS know which of OneOfs types to check against
365
- const isOffsetCheckpointUpdate = (updateResponse) => !!updateResponse?.update?.OffsetCheckpoint;
366
- const isTransactionUpdate = (updateResponse) => !!updateResponse.update?.Transaction?.value;
367
- const offsetCheckpoints = updates
368
- .filter(isOffsetCheckpointUpdate)
369
- .map((update) => update.update.OffsetCheckpoint.value.offset);
370
- const latestCheckpointOffset = Math.max(...offsetCheckpoints);
371
- const transactions = await Promise.all(updates
372
- // exclude OffsetCheckpoint, Reassignment, TopologyTransaction
373
- .filter(isTransactionUpdate)
374
- .map(async (update) => {
375
- const tx = update.update.Transaction.value;
376
- const parser = new TransactionParser(tx, ledgerClient, partyId);
377
- return await parser.parseTransaction();
378
- }));
379
- return {
380
- // OffsetCheckpoint can be anywhere... or not at all, maybe
381
- nextOffset: Math.max(latestCheckpointOffset, ...transactions.map((tx) => tx.offset)),
382
- transactions: transactions
383
- .filter((tx) => tx.events.length > 0)
384
- .map(renderTransaction),
385
- };
386
- }
387
- async toPrettyTransaction(getTransactionResponse, partyId, ledgerClient) {
388
- const tx = getTransactionResponse.transaction;
389
- const parser = new TransactionParser(tx, ledgerClient, partyId);
390
- const parsedTx = await parser.parseTransaction();
391
- return renderTransaction(parsedTx);
392
- }
393
- // returns object with JsActiveContract content
394
- // and contractId and interface view value extracted from it as separate fields for convenience
395
- toPrettyContract(interfaceId, response) {
396
- const activeContract = response.contractEntry.JsActiveContract;
397
- const { createdEvent } = activeContract;
398
- return {
399
- contractId: createdEvent.contractId,
400
- activeContract,
401
- interfaceViewValue: ensureInterfaceViewIsPresent(createdEvent, interfaceId).viewValue,
402
- };
403
- }
404
718
  }