@canton-network/core-ledger-client 0.11.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,12 +1,14 @@
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, HOLDING_INTERFACE_ID, ALLOCATION_FACTORY_INTERFACE_ID, ALLOCATION_INTERFACE_ID, ALLOCATION_REQUEST_INTERFACE_ID, ALLOCATION_INSTRUCTION_INTERFACE_ID, TRANSFER_INSTRUCTION_INTERFACE_ID, TRANSFER_FACTORY_INTERFACE_ID, } from '@canton-network/core-token-standard';
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
4
  import { TokenStandardTransactionInterfaces } from './constants.js';
5
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;
@@ -22,121 +24,117 @@ export class TokenStandardService {
22
24
  getTokenStandardClient(registryUrl) {
23
25
  return new TokenStandardClient(registryUrl, this.logger, this.accessToken);
24
26
  }
25
- async getTransferPreApprovalByParty(partyId) {
26
- const { transfer_preapproval } = await this.scanProxyClient.get('/v0/scan-proxy/transfer-preapprovals/by-party/{party}', {
27
- path: {
28
- party: partyId,
29
- },
30
- });
31
- return transfer_preapproval;
32
- }
33
- async getFeaturedAppsByParty(partyId) {
34
- const { featured_app_right } = await this.scanProxyClient.get('/v0/scan-proxy/featured-apps/{provider_party_id}', {
35
- path: {
36
- provider_party_id: partyId,
37
- },
38
- });
39
- return featured_app_right;
40
- }
41
- async getInstrumentById(registryUrl, instrumentId) {
42
- try {
43
- const params = {
44
- path: {
45
- instrumentId,
46
- },
47
- };
48
- const client = this.getTokenStandardClient(registryUrl);
49
- return client.get('/registry/metadata/v1/instruments/{instrumentId}', params);
27
+ async getInputHoldingsCids(sender, inputUtxos) {
28
+ const now = new Date();
29
+ if (inputUtxos && inputUtxos.length > 0) {
30
+ return inputUtxos;
50
31
  }
51
- catch (e) {
52
- this.logger.error(e);
53
- throw new Error(`Instrument id ${instrumentId} does not exist for this instrument admin.`);
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.");
54
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
+ */
55
52
  }
56
- async getInstrumentAdmin(registryUrl) {
57
- const client = this.getTokenStandardClient(registryUrl);
58
- const info = await client.get('/registry/metadata/v1/info');
59
- return info.adminId;
60
- }
61
- async createAcceptTransferInstruction(transferInstructionCid, registryUrl) {
53
+ async listContractsByInterface(interfaceId, partyId) {
62
54
  try {
63
- const client = this.getTokenStandardClient(registryUrl);
64
- const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept', {}, {
65
- path: {
66
- transferInstructionId: transferInstructionCid,
67
- },
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,
68
63
  });
69
- const exercise = {
70
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
71
- contractId: transferInstructionCid,
72
- choice: 'TransferInstruction_Accept',
73
- choiceArgument: {
74
- extraArgs: {
75
- context: choiceContext.choiceContextData,
76
- meta: { values: {} },
77
- },
78
- },
79
- };
80
- return [exercise, choiceContext.disclosedContracts];
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));
81
75
  }
82
- catch (e) {
83
- this.logger.error('Failed to create accept transfer instruction:', e);
84
- throw e;
76
+ catch (err) {
77
+ this.logger.error(`Failed to list contracts of interface ${interfaceId}`, err);
78
+ throw err;
85
79
  }
86
80
  }
87
- async createRejectTransferInstruction(transferInstructionCid, registryUrl) {
88
- try {
89
- const client = this.getTokenStandardClient(registryUrl);
90
- const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject', {}, {
91
- path: {
92
- transferInstructionId: transferInstructionCid,
93
- },
94
- });
95
- const exercise = {
96
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
97
- contractId: transferInstructionCid,
98
- choice: 'TransferInstruction_Reject',
99
- choiceArgument: {
100
- extraArgs: {
101
- context: choiceContext.choiceContextData,
102
- meta: { values: {} },
103
- },
104
- },
105
- };
106
- return [exercise, choiceContext.disclosedContracts];
107
- }
108
- catch (e) {
109
- this.logger.error('Failed to create reject transfer instruction:', e);
110
- throw e;
111
- }
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
+ };
112
104
  }
113
- async createWithdrawTransferInstruction(transferInstructionCid, registryUrl) {
114
- try {
115
- const client = this.getTokenStandardClient(registryUrl);
116
- const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw', {}, {
117
- path: {
118
- transferInstructionId: transferInstructionCid,
119
- },
120
- });
121
- const exercise = {
122
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
123
- contractId: transferInstructionCid,
124
- choice: 'TransferInstruction_Withdraw',
125
- choiceArgument: {
126
- extraArgs: {
127
- context: choiceContext.choiceContextData,
128
- meta: { values: {} },
129
- },
130
- },
131
- };
132
- return [exercise, choiceContext.disclosedContracts];
133
- }
134
- catch (e) {
135
- this.logger.error('Failed to create withdraw transfer instruction:', e);
136
- throw e;
137
- }
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);
138
117
  }
139
- async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, extraContext) {
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) {
140
138
  const allocationSpecificationNormalized = {
141
139
  ...allocationSpecification,
142
140
  settlement: {
@@ -150,46 +148,248 @@ export class TokenStandardService {
150
148
  },
151
149
  },
152
150
  };
153
- const inputHoldingCids = await this.getInputHoldingsCids(allocationSpecificationNormalized.transferLeg.sender, inputUtxos);
154
- const choiceArgs = {
155
- expectedAdmin: expectedAdmin,
151
+ const inputHoldingCids = await this.core.getInputHoldingsCids(allocationSpecificationNormalized.transferLeg.sender, inputUtxos);
152
+ return {
153
+ expectedAdmin,
156
154
  allocation: allocationSpecificationNormalized,
157
- requestedAt: requestedAt ?? new Date().toISOString(),
155
+ requestedAt: requestedAt ??
156
+ new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
158
157
  inputHoldingCids,
159
158
  extraArgs: {
160
- context: { values: { ...(extraContext ?? {}) } },
159
+ context: { values: {} },
161
160
  meta: { values: {} },
162
161
  },
163
162
  };
164
- const allocationFactory = await this.getTokenStandardClient(registryUrl).post('/registry/allocation-instruction/v1/allocation-factory', {
163
+ }
164
+ async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs) {
165
+ return this.core
166
+ .getTokenStandardClient(registryUrl)
167
+ .post('/registry/allocation-instruction/v1/allocation-factory', {
165
168
  choiceArguments: choiceArgs,
166
169
  });
170
+ }
171
+ async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
167
172
  choiceArgs.extraArgs.context = {
168
- ...allocationFactory.choiceContext.choiceContextData,
169
- values: allocationFactory.choiceContext.choiceContextData?.values ?? {},
173
+ ...choiceContext.choiceContextData,
174
+ values: choiceContext.choiceContextData?.values ?? {},
170
175
  };
171
176
  const exercise = {
172
177
  templateId: ALLOCATION_FACTORY_INTERFACE_ID,
173
- contractId: allocationFactory.factoryId,
178
+ contractId: factoryId,
174
179
  choice: 'AllocationFactory_Allocate',
175
180
  choiceArgument: choiceArgs,
176
181
  };
177
- return [exercise, allocationFactory.choiceContext.disclosedContracts];
182
+ return [exercise, choiceContext.disclosedContracts];
178
183
  }
179
- async getAllocationExecuteTransferChoiceContext(allocationId, registryUrl) {
180
- return this.getTokenStandardClient(registryUrl).post('/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer', {}, {
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', {}, {
181
208
  path: {
182
209
  allocationId,
183
210
  },
184
211
  });
185
212
  }
186
- async createExecuteTransferAllocation(allocationCid, registryUrl) {
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: {} },
262
+ },
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);
369
+ }
370
+ catch (e) {
371
+ this.logger.error('Failed to execute transfer:', e);
372
+ throw e;
373
+ }
374
+ }
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) {
187
388
  try {
188
- const choiceContext = await this.getAllocationExecuteTransferChoiceContext(allocationCid, registryUrl);
189
389
  const exercise = {
190
- templateId: ALLOCATION_INTERFACE_ID,
191
- contractId: allocationCid,
192
- choice: 'Allocation_ExecuteTransfer',
390
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
391
+ contractId: transferInstructionCid,
392
+ choice: 'TransferInstruction_Accept',
193
393
  choiceArgument: {
194
394
  extraArgs: {
195
395
  context: choiceContext.choiceContextData,
@@ -200,22 +400,38 @@ export class TokenStandardService {
200
400
  return [exercise, choiceContext.disclosedContracts];
201
401
  }
202
402
  catch (e) {
203
- this.logger.error('Failed to create allocation execute transfer:', e);
403
+ this.logger.error('Failed to create accept transfer instruction:', e);
204
404
  throw e;
205
405
  }
206
406
  }
207
- async createWithdrawAllocation(allocationCid, registryUrl) {
208
- try {
209
- const client = this.getTokenStandardClient(registryUrl);
210
- const choiceContext = await client.post('/registry/allocations/v1/{allocationId}/choice-contexts/withdraw', {}, {
211
- path: {
212
- allocationId: allocationCid,
213
- },
407
+ async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
408
+ if (prefetchedRegistryChoiceContext) {
409
+ return this.createAcceptTransferInstructionFromContext(transferInstructionCid, {
410
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
411
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts,
214
412
  });
413
+ }
414
+ const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
415
+ return this.createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext);
416
+ }
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) {
430
+ try {
215
431
  const exercise = {
216
- templateId: ALLOCATION_INTERFACE_ID,
217
- contractId: allocationCid,
218
- choice: 'Allocation_Withdraw',
432
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
433
+ contractId: transferInstructionCid,
434
+ choice: 'TransferInstruction_Reject',
219
435
  choiceArgument: {
220
436
  extraArgs: {
221
437
  context: choiceContext.choiceContextData,
@@ -226,22 +442,38 @@ export class TokenStandardService {
226
442
  return [exercise, choiceContext.disclosedContracts];
227
443
  }
228
444
  catch (e) {
229
- this.logger.error('Failed to create withdraw allocation:', e);
445
+ this.logger.error('Failed to create reject transfer instruction:', e);
230
446
  throw e;
231
447
  }
232
448
  }
233
- async createCancelAllocation(allocationCid, registryUrl) {
234
- try {
235
- const client = this.getTokenStandardClient(registryUrl);
236
- const choiceContext = await client.post('/registry/allocations/v1/{allocationId}/choice-contexts/cancel', {}, {
237
- path: {
238
- allocationId: allocationCid,
239
- },
449
+ async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
450
+ if (prefetchedRegistryChoiceContext) {
451
+ return this.createRejectTransferInstructionFromContext(transferInstructionCid, {
452
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
453
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts,
240
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 {
241
473
  const exercise = {
242
- templateId: ALLOCATION_INTERFACE_ID,
243
- contractId: allocationCid,
244
- choice: 'Allocation_Cancel',
474
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
475
+ contractId: transferInstructionCid,
476
+ choice: 'TransferInstruction_Withdraw',
245
477
  choiceArgument: {
246
478
  extraArgs: {
247
479
  context: choiceContext.choiceContextData,
@@ -256,93 +488,76 @@ export class TokenStandardService {
256
488
  throw e;
257
489
  }
258
490
  }
259
- async createWithdrawAllocationInstruction(registryUrl) {
260
- const exercise = {
261
- templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
262
- contractId: registryUrl,
263
- choice: 'AllocationInstruction_Withdraw',
264
- choiceArgument: {
265
- extraArgs: {
266
- context: { values: {} },
267
- meta: { values: {} },
268
- },
269
- },
270
- };
271
- return [exercise, []];
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);
272
500
  }
273
- async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
274
- const exercise = {
275
- templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
276
- contractId: allocationInstructionCid,
277
- choice: 'AllocationInstruction_Update',
278
- choiceArgument: {
279
- extraActors,
280
- extraArgs: {
281
- context: { values: extraArgsContext },
282
- meta: { values: extraArgsMeta },
283
- },
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,
284
525
  },
285
- };
286
- return [exercise, []];
526
+ });
527
+ return transfer_preapproval;
287
528
  }
288
- async createRejectAllocationRequest(allocationRequestCid, actor) {
289
- const exercise = {
290
- templateId: ALLOCATION_REQUEST_INTERFACE_ID,
291
- contractId: allocationRequestCid,
292
- choice: 'AllocationRequest_Reject',
293
- choiceArgument: {
294
- actor,
295
- extraArgs: {
296
- context: { values: {} },
297
- meta: { values: {} },
298
- },
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,
299
533
  },
300
- };
301
- return [exercise, []];
534
+ });
535
+ return featured_app_right;
302
536
  }
303
- async createWithdrawAllocationRequest(allocationRequestCid) {
304
- const exercise = {
305
- templateId: ALLOCATION_REQUEST_INTERFACE_ID,
306
- contractId: allocationRequestCid,
307
- choice: 'AllocationRequest_Withdraw',
308
- choiceArgument: {
309
- extraArgs: {
310
- context: { values: {} },
311
- meta: { values: {} },
537
+ async getInstrumentById(registryUrl, instrumentId) {
538
+ try {
539
+ const params = {
540
+ path: {
541
+ instrumentId,
312
542
  },
313
- },
314
- };
315
- return [exercise, []];
543
+ };
544
+ const client = this.core.getTokenStandardClient(registryUrl);
545
+ return client.get('/registry/metadata/v1/instruments/{instrumentId}', params);
546
+ }
547
+ catch (e) {
548
+ this.logger.error(e);
549
+ throw new Error(`Instrument id ${instrumentId} does not exist for this instrument admin.`);
550
+ }
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;
316
556
  }
317
557
  // <T> is shape of viewValue related to queried interface.
318
558
  // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
319
559
  async listContractsByInterface(interfaceId, partyId) {
320
- try {
321
- const ledgerEnd = await this.ledgerClient.get('/v2/state/ledger-end');
322
- const acsResponses = await this.ledgerClient.post('/v2/state/active-contracts', {
323
- filter: TransactionFilterBySetup(interfaceId, {
324
- isMasterUser: this.isMasterUser,
325
- partyId: partyId,
326
- }),
327
- verbose: false,
328
- activeAtOffset: ledgerEnd.offset,
329
- });
330
- /* This filters out responses with entries of:
331
- - JsEmpty
332
- - JsIncompleteAssigned
333
- - JsIncompleteUnassigned
334
- while leaving JsActiveContract.
335
- It works fine only with single synchronizer
336
- TODO (#353) add support for multiple synchronizers
337
- */
338
- const isActiveContractEntry = (acsResponse) => !!acsResponse.contractEntry.JsActiveContract?.createdEvent;
339
- const activeContractEntries = acsResponses.filter(isActiveContractEntry);
340
- return activeContractEntries.map((response) => this.toPrettyContract(interfaceId, response));
341
- }
342
- catch (err) {
343
- this.logger.error(`Failed to list contracts of interface ${interfaceId}`, err);
344
- throw err;
345
- }
560
+ return this.core.listContractsByInterface(interfaceId, partyId);
346
561
  }
347
562
  async listHoldingTransactions(partyId, afterOffset, beforeOffset) {
348
563
  try {
@@ -368,7 +583,7 @@ export class TokenStandardService {
368
583
  endInclusive: beforeOffsetOrLatest,
369
584
  verbose: false,
370
585
  });
371
- return this.toPrettyTransactions(updatesResponse, partyId, this.ledgerClient);
586
+ return this.core.toPrettyTransactions(updatesResponse, partyId, this.ledgerClient);
372
587
  }
373
588
  catch (err) {
374
589
  this.logger.error('Failed to list holding transactions.', err);
@@ -388,80 +603,36 @@ export class TokenStandardService {
388
603
  updateId,
389
604
  transactionFormat,
390
605
  });
391
- return this.toPrettyTransaction(getTransactionResponse, partyId, this.ledgerClient);
606
+ return this.core.toPrettyTransaction(getTransactionResponse, partyId, this.ledgerClient);
392
607
  }
393
608
  async getInputHoldingsCids(sender, inputUtxos) {
394
- const now = new Date();
395
- if (inputUtxos && inputUtxos.length > 0) {
396
- return inputUtxos;
397
- }
398
- const senderHoldings = await this.listContractsByInterface(HOLDING_INTERFACE_ID, sender);
399
- if (senderHoldings.length === 0) {
400
- throw new Error("Sender has no holdings, so transfer can't be executed.");
401
- }
402
- return senderHoldings
403
- .filter((utxo) => {
404
- //filter out locked holdings
405
- const lock = utxo.interfaceViewValue.lock;
406
- if (!lock)
407
- return true;
408
- const expiresAt = lock.expiresAt;
409
- if (!expiresAt)
410
- return false;
411
- const expiresAtDate = new Date(expiresAt);
412
- return expiresAtDate <= now;
413
- })
414
- .map((h) => h.contractId);
415
- /* TODO: optimize input holding selection, currently if you transfer 10 CC and have 10 inputs of 1000 CC,
416
- then all 10 of those are chose as input.
417
- */
609
+ return this.core.getInputHoldingsCids(sender, inputUtxos);
418
610
  }
419
- async createTransfer(sender, receiver, amount, instrumentAdmin, // TODO (#907): replace with registry call
420
- instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta) {
421
- try {
422
- const inputHoldingCids = await this.getInputHoldingsCids(sender, inputUtxos);
423
- const choiceArgs = {
424
- expectedAdmin: instrumentAdmin,
425
- transfer: {
426
- sender,
427
- receiver,
428
- amount,
429
- instrumentId: { admin: instrumentAdmin, id: instrumentId },
430
- lock: null,
431
- requestedAt: new Date(Date.now() - 60 * 1000).toISOString(),
432
- //given expiryDate or 24 hours
433
- executeBefore: (expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1000)).toISOString(),
434
- inputHoldingCids,
435
- meta: { values: { [MEMO_KEY]: memo || '', ...meta } },
436
- },
437
- extraArgs: {
438
- context: { values: {} },
439
- meta: { values: {} },
440
- },
441
- };
442
- this.logger.debug('Creating transfer factory...');
443
- const transferFactory = await this.getTokenStandardClient(registryUrl).post('/registry/transfer-instruction/v1/transfer-factory', {
444
- choiceArguments: choiceArgs,
445
- });
446
- this.logger.debug(transferFactory, 'Transfer factory created');
447
- choiceArgs.extraArgs.context = {
448
- ...transferFactory.choiceContext.choiceContextData,
449
- values: transferFactory.choiceContext.choiceContextData?.values ??
450
- {},
451
- };
452
- const exercise = {
453
- templateId: TRANSFER_FACTORY_INTERFACE_ID,
454
- contractId: transferFactory.factoryId,
455
- choice: 'TransferFactory_Transfer',
456
- choiceArgument: choiceArgs,
457
- };
458
- return [exercise, transferFactory.choiceContext.disclosedContracts];
459
- }
460
- catch (e) {
461
- this.logger.error('Failed to execute transfer:', e);
462
- throw e;
463
- }
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];
464
634
  }
635
+ // TODO(#583) as it's not a part of token standard, should be moved somewhere else
465
636
  async createTap(receiver, amount, instrumentAdmin, // TODO (#907): replace with registry call
466
637
  instrumentId, registryUrl) {
467
638
  const now = new Date();
@@ -475,7 +646,7 @@ export class TokenStandardService {
475
646
  amount,
476
647
  instrumentId: { admin: instrumentAdmin, id: instrumentId },
477
648
  lock: null,
478
- requestedAt: now.toISOString(),
649
+ requestedAt: new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
479
650
  executeBefore: tomorrow.toISOString(),
480
651
  inputHoldingCids: [],
481
652
  meta: { values: {} },
@@ -485,7 +656,9 @@ export class TokenStandardService {
485
656
  meta: { values: {} },
486
657
  },
487
658
  };
488
- const transferFactory = await this.getTokenStandardClient(registryUrl).post('/registry/transfer-instruction/v1/transfer-factory', {
659
+ const transferFactory = await this.core
660
+ .getTokenStandardClient(registryUrl)
661
+ .post('/registry/transfer-instruction/v1/transfer-factory', {
489
662
  choiceArguments: choiceArgs,
490
663
  });
491
664
  const disclosedContracts = transferFactory.choiceContext.disclosedContracts;
@@ -514,8 +687,8 @@ export class TokenStandardService {
514
687
  contractId: amuletRules.contract_id,
515
688
  choice: 'AmuletRules_DevNet_Tap',
516
689
  choiceArgument: {
517
- receiver: receiver,
518
- amount: amount,
690
+ receiver,
691
+ amount,
519
692
  openRound: latestOpenMiningRound.contract_id,
520
693
  },
521
694
  },
@@ -528,7 +701,7 @@ export class TokenStandardService {
528
701
  templateId: amuletRules.template_id,
529
702
  contractId: amuletRules.contract_id,
530
703
  createdEventBlob: amuletRules.created_event_blob,
531
- synchronizerId: synchronizerId,
704
+ synchronizerId,
532
705
  };
533
706
  return [
534
707
  {
@@ -542,52 +715,4 @@ export class TokenStandardService {
542
715
  [disclosedContracts],
543
716
  ];
544
717
  }
545
- async toPrettyTransactionsPerParty(updates, parties, ledgerClient) {
546
- const all = await Promise.all(parties.map(async (partyId) => [
547
- partyId,
548
- await this.toPrettyTransactions(updates, partyId, ledgerClient),
549
- ]));
550
- return new Map(all);
551
- }
552
- async toPrettyTransactions(updates, partyId, ledgerClient) {
553
- // Runtime filters that also let TS know which of OneOfs types to check against
554
- const isOffsetCheckpointUpdate = (updateResponse) => !!updateResponse?.update?.OffsetCheckpoint;
555
- const isTransactionUpdate = (updateResponse) => !!updateResponse.update?.Transaction?.value;
556
- const offsetCheckpoints = updates
557
- .filter(isOffsetCheckpointUpdate)
558
- .map((update) => update.update.OffsetCheckpoint.value.offset);
559
- const latestCheckpointOffset = Math.max(...offsetCheckpoints);
560
- const transactions = await Promise.all(updates
561
- // exclude OffsetCheckpoint, Reassignment, TopologyTransaction
562
- .filter(isTransactionUpdate)
563
- .map(async (update) => {
564
- const tx = update.update.Transaction.value;
565
- const parser = new TransactionParser(tx, ledgerClient, partyId, this.isMasterUser);
566
- return await parser.parseTransaction();
567
- }));
568
- return {
569
- // OffsetCheckpoint can be anywhere... or not at all, maybe
570
- nextOffset: Math.max(latestCheckpointOffset, ...transactions.map((tx) => tx.offset)),
571
- transactions: transactions
572
- .filter((tx) => tx.events.length > 0)
573
- .map(renderTransaction),
574
- };
575
- }
576
- async toPrettyTransaction(getTransactionResponse, partyId, ledgerClient) {
577
- const tx = getTransactionResponse.transaction;
578
- const parser = new TransactionParser(tx, ledgerClient, partyId, this.isMasterUser);
579
- const parsedTx = await parser.parseTransaction();
580
- return renderTransaction(parsedTx);
581
- }
582
- // returns object with JsActiveContract content
583
- // and contractId and interface view value extracted from it as separate fields for convenience
584
- toPrettyContract(interfaceId, response) {
585
- const activeContract = response.contractEntry.JsActiveContract;
586
- const { createdEvent } = activeContract;
587
- return {
588
- contractId: createdEvent.contractId,
589
- activeContract,
590
- interfaceViewValue: ensureInterfaceViewIsPresent(createdEvent, interfaceId).viewValue,
591
- };
592
- }
593
718
  }