@canton-network/core-ledger-client 0.11.0 → 0.13.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, FEATURED_APP_DELEGATE_PROXY_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,132 @@ 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.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,
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;
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
+ async getActiveOpenMiningRound() {
130
+ const openMiningRounds = await this.scanProxyClient.getOpenMiningRounds();
131
+ if (!(Array.isArray(openMiningRounds) && openMiningRounds.length)) {
132
+ throw new Error('OpenMiningRound contract not found');
137
133
  }
134
+ const nowForOpenMiningRounds = Date.now();
135
+ const latestOpenMiningRound = openMiningRounds.findLast((openMiningRound) => {
136
+ const { opensAt, targetClosesAt } = openMiningRound.payload;
137
+ const opensAtMs = Number(new Date(opensAt));
138
+ const targetClosesAtMs = Number(new Date(targetClosesAt));
139
+ return (opensAtMs <= nowForOpenMiningRounds &&
140
+ targetClosesAtMs > nowForOpenMiningRounds);
141
+ });
142
+ return latestOpenMiningRound ?? null;
143
+ }
144
+ }
145
+ class AllocationService {
146
+ core;
147
+ logger;
148
+ constructor(core, logger) {
149
+ this.core = core;
150
+ this.logger = logger;
138
151
  }
139
- async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, extraContext) {
152
+ async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
140
153
  const allocationSpecificationNormalized = {
141
154
  ...allocationSpecification,
142
155
  settlement: {
@@ -150,46 +163,248 @@ export class TokenStandardService {
150
163
  },
151
164
  },
152
165
  };
153
- const inputHoldingCids = await this.getInputHoldingsCids(allocationSpecificationNormalized.transferLeg.sender, inputUtxos);
154
- const choiceArgs = {
155
- expectedAdmin: expectedAdmin,
166
+ const inputHoldingCids = await this.core.getInputHoldingsCids(allocationSpecificationNormalized.transferLeg.sender, inputUtxos);
167
+ return {
168
+ expectedAdmin,
156
169
  allocation: allocationSpecificationNormalized,
157
- requestedAt: requestedAt ?? new Date().toISOString(),
170
+ requestedAt: requestedAt ??
171
+ new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
158
172
  inputHoldingCids,
159
173
  extraArgs: {
160
- context: { values: { ...(extraContext ?? {}) } },
174
+ context: { values: {} },
161
175
  meta: { values: {} },
162
176
  },
163
177
  };
164
- const allocationFactory = await this.getTokenStandardClient(registryUrl).post('/registry/allocation-instruction/v1/allocation-factory', {
178
+ }
179
+ async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs) {
180
+ return this.core
181
+ .getTokenStandardClient(registryUrl)
182
+ .post('/registry/allocation-instruction/v1/allocation-factory', {
165
183
  choiceArguments: choiceArgs,
166
184
  });
185
+ }
186
+ async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
167
187
  choiceArgs.extraArgs.context = {
168
- ...allocationFactory.choiceContext.choiceContextData,
169
- values: allocationFactory.choiceContext.choiceContextData?.values ?? {},
188
+ ...choiceContext.choiceContextData,
189
+ values: choiceContext.choiceContextData?.values ?? {},
170
190
  };
171
191
  const exercise = {
172
192
  templateId: ALLOCATION_FACTORY_INTERFACE_ID,
173
- contractId: allocationFactory.factoryId,
193
+ contractId: factoryId,
174
194
  choice: 'AllocationFactory_Allocate',
175
195
  choiceArgument: choiceArgs,
176
196
  };
177
- return [exercise, allocationFactory.choiceContext.disclosedContracts];
197
+ return [exercise, choiceContext.disclosedContracts];
198
+ }
199
+ async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
200
+ const choiceArgs = await this.buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt);
201
+ if (prefetchedRegistryChoiceContext) {
202
+ return this.createAllocationInstructionFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
203
+ }
204
+ const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs);
205
+ return this.createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext);
206
+ }
207
+ buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
208
+ const exercise = {
209
+ templateId,
210
+ contractId,
211
+ choice,
212
+ choiceArgument: {
213
+ extraArgs: {
214
+ context: choiceContext.choiceContextData,
215
+ meta: EMPTY_META,
216
+ },
217
+ },
218
+ };
219
+ return [exercise, choiceContext.disclosedContracts ?? []];
178
220
  }
179
- async getAllocationExecuteTransferChoiceContext(allocationId, registryUrl) {
180
- return this.getTokenStandardClient(registryUrl).post('/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer', {}, {
221
+ async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
222
+ return this.core.getTokenStandardClient(registryUrl).post('/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer', {}, {
181
223
  path: {
182
224
  allocationId,
183
225
  },
184
226
  });
185
227
  }
186
- async createExecuteTransferAllocation(allocationCid, registryUrl) {
228
+ createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
229
+ return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, 'Allocation_ExecuteTransfer', choiceContext);
230
+ }
231
+ async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
232
+ if (prefetchedRegistryChoiceContext) {
233
+ return this.createExecuteTransferAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
234
+ }
235
+ const choiceContext = await this.fetchExecuteTransferChoiceContext(allocationCid, registryUrl);
236
+ return this.createExecuteTransferAllocationFromContext(allocationCid, choiceContext);
237
+ }
238
+ async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
239
+ return this.core
240
+ .getTokenStandardClient(registryUrl)
241
+ .post('/registry/allocations/v1/{allocationId}/choice-contexts/withdraw', {}, { path: { allocationId: allocationCid } });
242
+ }
243
+ createWithdrawAllocationFromContext(allocationCid, choiceContext) {
244
+ return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, 'Allocation_Withdraw', choiceContext);
245
+ }
246
+ async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
247
+ if (prefetchedRegistryChoiceContext) {
248
+ return this.createWithdrawAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
249
+ }
250
+ const choiceContext = await this.fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl);
251
+ return this.createWithdrawAllocationFromContext(allocationCid, choiceContext);
252
+ }
253
+ async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
254
+ return this.core
255
+ .getTokenStandardClient(registryUrl)
256
+ .post('/registry/allocations/v1/{allocationId}/choice-contexts/cancel', {}, { path: { allocationId: allocationCid } });
257
+ }
258
+ createCancelAllocationFromContext(allocationCid, choiceContext) {
259
+ return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, 'Allocation_Cancel', choiceContext);
260
+ }
261
+ async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
262
+ if (prefetchedRegistryChoiceContext) {
263
+ return this.createCancelAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
264
+ }
265
+ const choiceContext = await this.fetchCancelAllocationChoiceContext(allocationCid, registryUrl);
266
+ return this.createCancelAllocationFromContext(allocationCid, choiceContext);
267
+ }
268
+ async createWithdrawAllocationInstruction(allocationInstructionCid) {
269
+ const exercise = {
270
+ templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
271
+ contractId: allocationInstructionCid,
272
+ choice: 'AllocationInstruction_Withdraw',
273
+ choiceArgument: {
274
+ extraArgs: {
275
+ context: { values: {} },
276
+ meta: { values: {} },
277
+ },
278
+ },
279
+ };
280
+ return [exercise, []];
281
+ }
282
+ async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
283
+ const exercise = {
284
+ templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
285
+ contractId: allocationInstructionCid,
286
+ choice: 'AllocationInstruction_Update',
287
+ choiceArgument: {
288
+ extraActors,
289
+ extraArgs: {
290
+ context: { values: extraArgsContext },
291
+ meta: { values: extraArgsMeta },
292
+ },
293
+ },
294
+ };
295
+ return [exercise, []];
296
+ }
297
+ async createRejectAllocationRequest(allocationRequestCid, actor) {
298
+ const exercise = {
299
+ templateId: ALLOCATION_REQUEST_INTERFACE_ID,
300
+ contractId: allocationRequestCid,
301
+ choice: 'AllocationRequest_Reject',
302
+ choiceArgument: {
303
+ actor,
304
+ extraArgs: {
305
+ context: { values: {} },
306
+ meta: { values: {} },
307
+ },
308
+ },
309
+ };
310
+ return [exercise, []];
311
+ }
312
+ async createWithdrawAllocationRequest(allocationRequestCid) {
313
+ const exercise = {
314
+ templateId: ALLOCATION_REQUEST_INTERFACE_ID,
315
+ contractId: allocationRequestCid,
316
+ choice: 'AllocationRequest_Withdraw',
317
+ choiceArgument: {
318
+ extraArgs: {
319
+ context: { values: {} },
320
+ meta: { values: {} },
321
+ },
322
+ },
323
+ };
324
+ return [exercise, []];
325
+ }
326
+ }
327
+ class TransferService {
328
+ core;
329
+ logger;
330
+ constructor(core, logger) {
331
+ this.core = core;
332
+ this.logger = logger;
333
+ }
334
+ async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta) {
335
+ const inputHoldingCids = await this.core.getInputHoldingsCids(sender, inputUtxos);
336
+ return {
337
+ expectedAdmin: instrumentAdmin,
338
+ transfer: {
339
+ sender,
340
+ receiver,
341
+ amount,
342
+ instrumentId: { admin: instrumentAdmin, id: instrumentId },
343
+ requestedAt: new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
344
+ executeBefore: (expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1000)).toISOString(),
345
+ inputHoldingCids,
346
+ meta: { values: { [MEMO_KEY]: memo || '', ...meta?.values } },
347
+ },
348
+ extraArgs: {
349
+ context: { values: {} },
350
+ meta: { values: {} },
351
+ },
352
+ };
353
+ }
354
+ async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs) {
355
+ return await this.core
356
+ .getTokenStandardClient(registryUrl)
357
+ .post('/registry/transfer-instruction/v1/transfer-factory', {
358
+ choiceArguments: choiceArgs,
359
+ });
360
+ }
361
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
362
+ this.logger.debug('Creating transfer from pre-fetched context...');
363
+ choiceArgs.extraArgs.context = {
364
+ ...choiceContext.choiceContextData,
365
+ values: choiceContext.choiceContextData?.values ?? {},
366
+ };
367
+ const exercise = {
368
+ templateId: TRANSFER_FACTORY_INTERFACE_ID,
369
+ contractId: factoryId,
370
+ choice: 'TransferFactory_Transfer',
371
+ choiceArgument: choiceArgs,
372
+ };
373
+ return [exercise, choiceContext.disclosedContracts];
374
+ }
375
+ async createTransfer(sender, receiver, amount, instrumentAdmin, // TODO (#907): replace with registry call
376
+ instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext) {
377
+ try {
378
+ const choiceArgs = await this.buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta);
379
+ if (prefetchedRegistryChoiceContext) {
380
+ return this.createTransferFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
381
+ }
382
+ const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(registryUrl, choiceArgs);
383
+ return this.createTransferFromContext(factoryId, choiceArgs, choiceContext);
384
+ }
385
+ catch (e) {
386
+ this.logger.error('Failed to execute transfer:', e);
387
+ throw e;
388
+ }
389
+ }
390
+ async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
391
+ const client = this.core.getTokenStandardClient(registryUrl);
392
+ const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept', {}, {
393
+ path: {
394
+ transferInstructionId: transferInstructionCid,
395
+ },
396
+ });
397
+ return {
398
+ choiceContextData: choiceContext.choiceContextData,
399
+ disclosedContracts: choiceContext.disclosedContracts,
400
+ };
401
+ }
402
+ async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
187
403
  try {
188
- const choiceContext = await this.getAllocationExecuteTransferChoiceContext(allocationCid, registryUrl);
189
404
  const exercise = {
190
- templateId: ALLOCATION_INTERFACE_ID,
191
- contractId: allocationCid,
192
- choice: 'Allocation_ExecuteTransfer',
405
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
406
+ contractId: transferInstructionCid,
407
+ choice: 'TransferInstruction_Accept',
193
408
  choiceArgument: {
194
409
  extraArgs: {
195
410
  context: choiceContext.choiceContextData,
@@ -200,22 +415,102 @@ export class TokenStandardService {
200
415
  return [exercise, choiceContext.disclosedContracts];
201
416
  }
202
417
  catch (e) {
203
- this.logger.error('Failed to create allocation execute transfer:', e);
418
+ this.logger.error('Failed to create accept transfer instruction:', e);
204
419
  throw e;
205
420
  }
206
421
  }
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
- },
422
+ async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
423
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(transferInstructionCid, registryUrl.href);
424
+ const choiceArgs = {
425
+ cid: acceptTransferInstructionContext.contractId,
426
+ proxyArg: {
427
+ featuredAppRightCid: featuredAppRightCid,
428
+ beneficiaries: beneficiaries,
429
+ choiceArg: acceptTransferInstructionContext.choiceArgument,
430
+ },
431
+ };
432
+ return [
433
+ {
434
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
435
+ contractId: proxyCid,
436
+ choice: 'DelegateProxy_TransferInstruction_Accept',
437
+ choiceArgument: choiceArgs,
438
+ },
439
+ disclosedContracts,
440
+ ];
441
+ }
442
+ async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
443
+ const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(transferInstructionCid, registryUrl.href);
444
+ const choiceArgs = {
445
+ cid: rejectTransferInstructionContext.contractId,
446
+ proxyArg: {
447
+ featuredAppRightCid: featuredAppRightCid,
448
+ beneficiaries,
449
+ choiceArg: rejectTransferInstructionContext.choiceArgument,
450
+ },
451
+ };
452
+ return [
453
+ {
454
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
455
+ contractId: proxyCid,
456
+ choice: 'DelegateProxy_TransferInstruction_Reject',
457
+ choiceArgument: choiceArgs,
458
+ },
459
+ disclosedContracts,
460
+ ];
461
+ }
462
+ async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
463
+ const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl.href);
464
+ const sumOfWeights = beneficiaries.reduce((totalWeight, beneficiary) => totalWeight + beneficiary.weight, 0);
465
+ if (sumOfWeights > 1.0) {
466
+ throw new Error('Sum of beneficiary weights is larger than 1.');
467
+ }
468
+ const choiceArgs = {
469
+ cid: withdrawTransferInstructionContext.contractId,
470
+ proxyArg: {
471
+ featuredAppRightCid: featuredAppRightCid,
472
+ beneficiaries,
473
+ choiceArg: withdrawTransferInstructionContext.choiceArgument,
474
+ },
475
+ };
476
+ return [
477
+ {
478
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
479
+ contractId: proxyCid,
480
+ choice: 'DelegateProxy_TransferInstruction_Withdraw',
481
+ choiceArgument: choiceArgs,
482
+ },
483
+ disclosedContracts,
484
+ ];
485
+ }
486
+ async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
487
+ if (prefetchedRegistryChoiceContext) {
488
+ return this.createAcceptTransferInstructionFromContext(transferInstructionCid, {
489
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
490
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts,
214
491
  });
492
+ }
493
+ const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
494
+ return this.createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext);
495
+ }
496
+ async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
497
+ const client = this.core.getTokenStandardClient(registryUrl);
498
+ const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject', {}, {
499
+ path: {
500
+ transferInstructionId: transferInstructionCid,
501
+ },
502
+ });
503
+ return {
504
+ choiceContextData: choiceContext.choiceContextData,
505
+ disclosedContracts: choiceContext.disclosedContracts,
506
+ };
507
+ }
508
+ async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
509
+ try {
215
510
  const exercise = {
216
- templateId: ALLOCATION_INTERFACE_ID,
217
- contractId: allocationCid,
218
- choice: 'Allocation_Withdraw',
511
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
512
+ contractId: transferInstructionCid,
513
+ choice: 'TransferInstruction_Reject',
219
514
  choiceArgument: {
220
515
  extraArgs: {
221
516
  context: choiceContext.choiceContextData,
@@ -226,22 +521,38 @@ export class TokenStandardService {
226
521
  return [exercise, choiceContext.disclosedContracts];
227
522
  }
228
523
  catch (e) {
229
- this.logger.error('Failed to create withdraw allocation:', e);
524
+ this.logger.error('Failed to create reject transfer instruction:', e);
230
525
  throw e;
231
526
  }
232
527
  }
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
- },
528
+ async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
529
+ if (prefetchedRegistryChoiceContext) {
530
+ return this.createRejectTransferInstructionFromContext(transferInstructionCid, {
531
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
532
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts,
240
533
  });
534
+ }
535
+ const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
536
+ return this.createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext);
537
+ }
538
+ async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
539
+ const client = this.core.getTokenStandardClient(registryUrl);
540
+ const choiceContext = await client.post('/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw', {}, {
541
+ path: {
542
+ transferInstructionId: transferInstructionCid,
543
+ },
544
+ });
545
+ return {
546
+ choiceContextData: choiceContext.choiceContextData,
547
+ disclosedContracts: choiceContext.disclosedContracts,
548
+ };
549
+ }
550
+ async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
551
+ try {
241
552
  const exercise = {
242
- templateId: ALLOCATION_INTERFACE_ID,
243
- contractId: allocationCid,
244
- choice: 'Allocation_Cancel',
553
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
554
+ contractId: transferInstructionCid,
555
+ choice: 'TransferInstruction_Withdraw',
245
556
  choiceArgument: {
246
557
  extraArgs: {
247
558
  context: choiceContext.choiceContextData,
@@ -256,104 +567,87 @@ export class TokenStandardService {
256
567
  throw e;
257
568
  }
258
569
  }
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, []];
570
+ async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
571
+ if (prefetchedRegistryChoiceContext) {
572
+ return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, {
573
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
574
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts,
575
+ });
576
+ }
577
+ const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
578
+ return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext);
272
579
  }
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
- },
580
+ }
581
+ export class TokenStandardService {
582
+ ledgerClient;
583
+ scanProxyClient;
584
+ logger;
585
+ accessToken;
586
+ isMasterUser;
587
+ core;
588
+ allocation;
589
+ transfer;
590
+ constructor(ledgerClient, scanProxyClient, logger, accessToken, isMasterUser) {
591
+ this.ledgerClient = ledgerClient;
592
+ this.scanProxyClient = scanProxyClient;
593
+ this.logger = logger;
594
+ this.accessToken = accessToken;
595
+ this.isMasterUser = isMasterUser;
596
+ this.core = new CoreService(ledgerClient, scanProxyClient, logger, accessToken, isMasterUser);
597
+ this.allocation = new AllocationService(this.core, this.logger);
598
+ this.transfer = new TransferService(this.core, this.logger);
599
+ }
600
+ async getTransferPreApprovalByParty(partyId) {
601
+ const { transfer_preapproval } = await this.scanProxyClient.get('/v0/scan-proxy/transfer-preapprovals/by-party/{party}', {
602
+ path: {
603
+ party: partyId,
284
604
  },
285
- };
286
- return [exercise, []];
605
+ });
606
+ return transfer_preapproval;
287
607
  }
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
- },
608
+ async getFeaturedAppsByParty(partyId) {
609
+ const { featured_app_right } = await this.scanProxyClient.get('/v0/scan-proxy/featured-apps/{provider_party_id}', {
610
+ path: {
611
+ provider_party_id: partyId,
299
612
  },
300
- };
301
- return [exercise, []];
613
+ });
614
+ return featured_app_right;
302
615
  }
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: {} },
616
+ async getInstrumentById(registryUrl, instrumentId) {
617
+ try {
618
+ const params = {
619
+ path: {
620
+ instrumentId,
312
621
  },
313
- },
314
- };
315
- return [exercise, []];
622
+ };
623
+ const client = this.core.getTokenStandardClient(registryUrl);
624
+ return client.get('/registry/metadata/v1/instruments/{instrumentId}', params);
625
+ }
626
+ catch (e) {
627
+ this.logger.error(e);
628
+ throw new Error(`Instrument id ${instrumentId} does not exist for this instrument admin.`);
629
+ }
630
+ }
631
+ async getInstrumentAdmin(registryUrl) {
632
+ const client = this.core.getTokenStandardClient(registryUrl);
633
+ const info = await client.get('/registry/metadata/v1/info');
634
+ return info.adminId;
316
635
  }
317
636
  // <T> is shape of viewValue related to queried interface.
318
637
  // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
319
638
  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
- }
639
+ return this.core.listContractsByInterface(interfaceId, partyId);
346
640
  }
347
641
  async listHoldingTransactions(partyId, afterOffset, beforeOffset) {
348
642
  try {
349
643
  this.logger.debug('Set or query offset');
350
644
  const afterOffsetOrLatest = Number(afterOffset) ||
351
- (await this.ledgerClient.get('/v2/state/latest-pruned-offsets'))
352
- .participantPrunedUpToInclusive;
645
+ (await this.ledgerClient.getWithRetry('/v2/state/latest-pruned-offsets')).participantPrunedUpToInclusive;
353
646
  const beforeOffsetOrLatest = Number(beforeOffset) ||
354
- (await this.ledgerClient.get('/v2/state/ledger-end')).offset;
647
+ (await this.ledgerClient.getWithRetry('/v2/state/ledger-end'))
648
+ .offset;
355
649
  this.logger.debug(afterOffsetOrLatest, 'Using offset');
356
- const updatesResponse = await this.ledgerClient.post('/v2/updates/flats', {
650
+ const updatesResponse = await this.ledgerClient.postWithRetry('/v2/updates/flats', {
357
651
  updateFormat: {
358
652
  includeTransactions: {
359
653
  eventFormat: EventFilterBySetup(TokenStandardTransactionInterfaces, {
@@ -368,7 +662,7 @@ export class TokenStandardService {
368
662
  endInclusive: beforeOffsetOrLatest,
369
663
  verbose: false,
370
664
  });
371
- return this.toPrettyTransactions(updatesResponse, partyId, this.ledgerClient);
665
+ return this.core.toPrettyTransactions(updatesResponse, partyId, this.ledgerClient);
372
666
  }
373
667
  catch (err) {
374
668
  this.logger.error('Failed to list holding transactions.', err);
@@ -384,84 +678,39 @@ export class TokenStandardService {
384
678
  }),
385
679
  transactionShape: 'TRANSACTION_SHAPE_LEDGER_EFFECTS',
386
680
  };
387
- const getTransactionResponse = await this.ledgerClient.post('/v2/updates/transaction-by-id', {
681
+ const getTransactionResponse = await this.ledgerClient.postWithRetry('/v2/updates/transaction-by-id', {
388
682
  updateId,
389
683
  transactionFormat,
390
684
  });
391
- return this.toPrettyTransaction(getTransactionResponse, partyId, this.ledgerClient);
685
+ return this.core.toPrettyTransaction(getTransactionResponse, partyId, this.ledgerClient);
392
686
  }
393
687
  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
- */
688
+ return this.core.getInputHoldingsCids(sender, inputUtxos);
418
689
  }
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;
690
+ async createDelegateProxyTranfser(sender, receiver, amount, instrumentAdmin, // TODO (#907): replace with registry call
691
+ instrumentId, registryUrl, featuredAppRightCid, proxyCid, beneficiaries, inputUtxos, memo, expiryDate, meta) {
692
+ const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta);
693
+ const sumOfWeights = beneficiaries.reduce((totalWeight, beneficiary) => totalWeight + beneficiary.weight, 0);
694
+ if (sumOfWeights > 1.0) {
695
+ throw new Error('Sum of beneficiary weights is larger than 1.');
463
696
  }
697
+ const choiceArgs = {
698
+ cid: transferCommand.contractId,
699
+ proxyArg: {
700
+ featuredAppRightCid: featuredAppRightCid,
701
+ beneficiaries,
702
+ choiceArg: transferCommand.choiceArgument,
703
+ },
704
+ };
705
+ const exercise = {
706
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
707
+ contractId: proxyCid,
708
+ choice: 'DelegateProxy_TransferFactory_Transfer',
709
+ choiceArgument: choiceArgs,
710
+ };
711
+ return [exercise, disclosedContracts];
464
712
  }
713
+ // TODO(#583) as it's not a part of token standard, should be moved somewhere else
465
714
  async createTap(receiver, amount, instrumentAdmin, // TODO (#907): replace with registry call
466
715
  instrumentId, registryUrl) {
467
716
  const now = new Date();
@@ -475,7 +724,7 @@ export class TokenStandardService {
475
724
  amount,
476
725
  instrumentId: { admin: instrumentAdmin, id: instrumentId },
477
726
  lock: null,
478
- requestedAt: now.toISOString(),
727
+ requestedAt: new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
479
728
  executeBefore: tomorrow.toISOString(),
480
729
  inputHoldingCids: [],
481
730
  meta: { values: {} },
@@ -485,26 +734,17 @@ export class TokenStandardService {
485
734
  meta: { values: {} },
486
735
  },
487
736
  };
488
- const transferFactory = await this.getTokenStandardClient(registryUrl).post('/registry/transfer-instruction/v1/transfer-factory', {
737
+ const transferFactory = await this.core
738
+ .getTokenStandardClient(registryUrl)
739
+ .post('/registry/transfer-instruction/v1/transfer-factory', {
489
740
  choiceArguments: choiceArgs,
490
741
  });
491
742
  const disclosedContracts = transferFactory.choiceContext.disclosedContracts;
492
743
  const amuletRules = await this.scanProxyClient.getAmuletRules();
493
- const openMiningRounds = await this.scanProxyClient.getOpenMiningRounds();
494
744
  if (!amuletRules) {
495
745
  throw new Error('AmuletRules contract not found');
496
746
  }
497
- if (!(Array.isArray(openMiningRounds) && openMiningRounds.length)) {
498
- throw new Error('OpenMiningRound contract not found');
499
- }
500
- const nowForOpenMiningRounds = Date.now();
501
- const latestOpenMiningRound = openMiningRounds.findLast((openMiningRound) => {
502
- const { opensAt, targetClosesAt } = openMiningRound.payload;
503
- const opensAtMs = Number(new Date(opensAt));
504
- const targetClosesAtMs = Number(new Date(targetClosesAt));
505
- return (opensAtMs <= nowForOpenMiningRounds &&
506
- targetClosesAtMs > nowForOpenMiningRounds);
507
- });
747
+ const latestOpenMiningRound = await this.core.getActiveOpenMiningRound();
508
748
  if (!latestOpenMiningRound) {
509
749
  throw new Error('OpenMiningRound active at current moment not found');
510
750
  }
@@ -514,8 +754,8 @@ export class TokenStandardService {
514
754
  contractId: amuletRules.contract_id,
515
755
  choice: 'AmuletRules_DevNet_Tap',
516
756
  choiceArgument: {
517
- receiver: receiver,
518
- amount: amount,
757
+ receiver,
758
+ amount,
519
759
  openRound: latestOpenMiningRound.contract_id,
520
760
  },
521
761
  },
@@ -528,7 +768,7 @@ export class TokenStandardService {
528
768
  templateId: amuletRules.template_id,
529
769
  contractId: amuletRules.contract_id,
530
770
  createdEventBlob: amuletRules.created_event_blob,
531
- synchronizerId: synchronizerId,
771
+ synchronizerId,
532
772
  };
533
773
  return [
534
774
  {
@@ -542,52 +782,88 @@ export class TokenStandardService {
542
782
  [disclosedContracts],
543
783
  ];
544
784
  }
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),
785
+ async cancelTransferPreapproval(contractId, templateId, actor) {
786
+ const exercise = {
787
+ templateId,
788
+ contractId,
789
+ choice: 'TransferPreapproval_Cancel',
790
+ choiceArgument: { p: actor },
574
791
  };
792
+ return [exercise, []];
575
793
  }
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);
794
+ async renewTransferPreapproval(contractId, templateId, provider, synchronizerId, newExpiresAt, inputUtxos) {
795
+ const amuletRules = await this.scanProxyClient.getAmuletRules();
796
+ const activeRound = await this.core.getActiveOpenMiningRound();
797
+ if (!amuletRules) {
798
+ throw new Error('AmuletRules contract not found');
799
+ }
800
+ if (!activeRound) {
801
+ throw new Error('OpenMiningRound active at current moment not found');
802
+ }
803
+ const disclosed = [
804
+ {
805
+ templateId: amuletRules.template_id,
806
+ contractId: amuletRules.contract_id,
807
+ createdEventBlob: amuletRules.created_event_blob,
808
+ synchronizerId,
809
+ },
810
+ {
811
+ templateId: activeRound.template_id,
812
+ contractId: activeRound.contract_id,
813
+ createdEventBlob: activeRound.created_event_blob,
814
+ synchronizerId,
815
+ },
816
+ ];
817
+ const inputHoldings = await this.core.getInputHoldingsCids(provider, inputUtxos);
818
+ const context = {
819
+ context: {
820
+ openMiningRound: activeRound.contract_id,
821
+ issuingMiningRounds: [],
822
+ validatorRights: [],
823
+ featuredAppRight: null,
824
+ },
825
+ amuletRules: amuletRules.contract_id,
826
+ };
827
+ // Defaults to 90 days
828
+ const effectiveNewExpiresAt = newExpiresAt ?? new Date(Date.now() + 90 * 24 * 3600 * 1000);
829
+ const exercise = {
830
+ templateId,
831
+ contractId,
832
+ choice: 'TransferPreapproval_Renew',
833
+ choiceArgument: {
834
+ context,
835
+ inputs: inputHoldings.map((cid) => ({
836
+ tag: 'InputAmulet',
837
+ value: cid,
838
+ })),
839
+ newExpiresAt: effectiveNewExpiresAt.toISOString(),
840
+ },
841
+ };
842
+ return [exercise, disclosed];
581
843
  }
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,
844
+ async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
845
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(transferInstructionCid, registryUrl);
846
+ const choiceArgs = {
847
+ cid: acceptTransferInstructionContext.contractId,
848
+ proxyArg: {
849
+ featuredAppRightCid: featuredAppRightCid,
850
+ beneficiaries: [
851
+ {
852
+ beneficiary: exchangeParty,
853
+ weight: 1.0,
854
+ },
855
+ ],
856
+ choiceArg: acceptTransferInstructionContext.choiceArgument,
857
+ },
591
858
  };
859
+ return [
860
+ {
861
+ templateId: '#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy',
862
+ contractId: proxyCid,
863
+ choice: 'DelegateProxy_TransferInstruction_Accept',
864
+ choiceArgument: choiceArgs,
865
+ },
866
+ disclosedContracts,
867
+ ];
592
868
  }
593
869
  }