@canton-network/core-token-standard-service 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,1080 @@
1
+ import { TokenStandardClient, HOLDING_INTERFACE_ID, FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID, ALLOCATION_FACTORY_INTERFACE_ID, ALLOCATION_INTERFACE_ID, ALLOCATION_INSTRUCTION_INTERFACE_ID, ALLOCATION_REQUEST_INTERFACE_ID, TRANSFER_FACTORY_INTERFACE_ID, TRANSFER_INSTRUCTION_INTERFACE_ID } from '@canton-network/core-token-standard';
2
+ import { EventFilterBySetup } from '@canton-network/core-ledger-client-types';
3
+ import { TransactionParser, renderTransaction, ensureInterfaceViewIsPresent, TokenStandardTransactionInterfaces } from '@canton-network/core-tx-parser';
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
+ var REQUESTED_AT_SKEW_MS = 6e4;
9
+ var EMPTY_META = { values: {} };
10
+ var CoreService = class _CoreService {
11
+ constructor(ledgerClient, logger, accessTokenProvider, isMasterUser, isAdmin = false, accessToken = "") {
12
+ this.ledgerClient = ledgerClient;
13
+ this.logger = logger;
14
+ this.accessTokenProvider = accessTokenProvider;
15
+ this.isMasterUser = isMasterUser;
16
+ this.isAdmin = isAdmin;
17
+ this.accessToken = accessToken;
18
+ }
19
+ getTokenStandardClient(registryUrl) {
20
+ return new TokenStandardClient(
21
+ registryUrl,
22
+ this.logger,
23
+ this.isAdmin,
24
+ this.accessToken,
25
+ this.accessTokenProvider
26
+ );
27
+ }
28
+ // TODO: probably needs a filter by instrument ID as well?
29
+ async getInputHoldingsCids(sender, inputUtxos, amount, continueUntilCompletion) {
30
+ const now = /* @__PURE__ */ new Date();
31
+ if (inputUtxos && inputUtxos.length > 0) {
32
+ return inputUtxos;
33
+ }
34
+ const senderHoldings = await this.listContractsByInterface(
35
+ HOLDING_INTERFACE_ID,
36
+ sender,
37
+ void 0,
38
+ void 0,
39
+ continueUntilCompletion
40
+ );
41
+ if (senderHoldings.length === 0) {
42
+ throw new Error(
43
+ "Sender has no holdings, so transfer can't be executed."
44
+ );
45
+ }
46
+ const unlockedSenderHoldings = senderHoldings.filter((utxo) => {
47
+ const lock = utxo.interfaceViewValue.lock;
48
+ if (!lock) return true;
49
+ const expiresAt = lock.expiresAt;
50
+ if (!expiresAt) return false;
51
+ const expiresAtDate = new Date(expiresAt);
52
+ return expiresAtDate <= now;
53
+ });
54
+ if (unlockedSenderHoldings.length > 100) {
55
+ this.logger.warn(`Sender has more than 100 unlocked utxos.`);
56
+ }
57
+ if (amount) {
58
+ return _CoreService.getInputHoldingsCidsForAmount(
59
+ amount,
60
+ unlockedSenderHoldings
61
+ );
62
+ } else {
63
+ return unlockedSenderHoldings.map((h) => h.contractId);
64
+ }
65
+ }
66
+ static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
67
+ const exactAmount = unlockedSenderHoldings.find(
68
+ (holding) => parseFloat(holding.interfaceViewValue.amount) === amount
69
+ );
70
+ if (exactAmount) {
71
+ return [exactAmount.contractId];
72
+ }
73
+ const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted(
74
+ (a, b) => parseFloat(a.interfaceViewValue.amount) - parseFloat(b.interfaceViewValue.amount)
75
+ );
76
+ const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
77
+ if (!largestHoldingAmount) {
78
+ throw new Error(`Sender doesn't have any unlocked holdings`);
79
+ }
80
+ let currentSum = parseFloat(
81
+ largestHoldingAmount.interfaceViewValue.amount
82
+ );
83
+ const cIds = [largestHoldingAmount.contractId];
84
+ for (const h of sortedUnlockedSenderHoldings) {
85
+ if (currentSum >= amount) {
86
+ break;
87
+ }
88
+ const currentHoldingAmount = parseFloat(h.interfaceViewValue.amount);
89
+ currentSum += currentHoldingAmount;
90
+ cIds.push(h.contractId);
91
+ }
92
+ if (currentSum < amount) {
93
+ throw new Error(
94
+ `Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount - currentSum}`
95
+ );
96
+ }
97
+ if (cIds.length > 100) {
98
+ throw new Error(
99
+ `Exceeded the maximum of 100 utxos in 1 transaction`
100
+ );
101
+ }
102
+ return cIds;
103
+ }
104
+ async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
105
+ try {
106
+ const ledgerEnd = offset ?? (await this.ledgerClient.getWithRetry("/v2/state/ledger-end")).offset;
107
+ const options = {
108
+ offset: ledgerEnd,
109
+ interfaceIds: [interfaceId],
110
+ parties: [partyId],
111
+ filterByParty: true,
112
+ continueUntilCompletion: Boolean(continueUntilCompletion)
113
+ };
114
+ if (limit !== void 0) {
115
+ options.limit = limit;
116
+ }
117
+ const acsResponses = await this.ledgerClient.activeContracts(options);
118
+ const isActiveContractEntry = (acsResponse) => "JsActiveContract" in acsResponse.contractEntry && !!acsResponse.contractEntry.JsActiveContract?.createdEvent;
119
+ const activeContractEntries = acsResponses.filter(
120
+ isActiveContractEntry
121
+ );
122
+ return activeContractEntries.map(
123
+ (response) => this.toPrettyContract(interfaceId, response, ledgerEnd)
124
+ );
125
+ } catch (err) {
126
+ this.logger.error(
127
+ `Failed to list contracts of interface ${interfaceId}`,
128
+ err
129
+ );
130
+ throw err;
131
+ }
132
+ }
133
+ async toPrettyTransactions(updates, partyId, ledgerClient) {
134
+ const isOffsetCheckpointUpdate = (updateResponse) => "OffsetCheckpoint" in updateResponse.update;
135
+ const isTransactionUpdate = (updateResponse) => "Transaction" in updateResponse.update && !!updateResponse.update.Transaction?.value;
136
+ const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map((update) => update.update.OffsetCheckpoint.value.offset);
137
+ const latestCheckpointOffset = Math.max(...offsetCheckpoints);
138
+ const transactions = await Promise.all(
139
+ updates.filter(isTransactionUpdate).map(async (update) => {
140
+ const tx = update.update.Transaction.value;
141
+ const parser = new TransactionParser(
142
+ tx,
143
+ ledgerClient,
144
+ partyId,
145
+ this.isMasterUser
146
+ );
147
+ return await parser.parseTransaction();
148
+ })
149
+ );
150
+ return {
151
+ // OffsetCheckpoint can be anywhere... or not at all, maybe
152
+ nextOffset: Math.max(
153
+ latestCheckpointOffset,
154
+ ...transactions.map((tx) => tx.offset)
155
+ ),
156
+ transactions: transactions.filter((tx) => tx.events.length > 0).map(renderTransaction)
157
+ };
158
+ }
159
+ async toPrettyTransaction(getTransactionResponse, partyId, ledgerClient) {
160
+ const tx = getTransactionResponse.transaction;
161
+ const parser = new TransactionParser(
162
+ tx,
163
+ ledgerClient,
164
+ partyId,
165
+ this.isMasterUser
166
+ );
167
+ const parsedTx = await parser.parseTransaction();
168
+ return renderTransaction(parsedTx);
169
+ }
170
+ async toPrettyTransferObjects(getTransactionResponse, partyId, ledgerClient) {
171
+ const tx = getTransactionResponse.transaction;
172
+ const parser = new TransactionParser(
173
+ tx,
174
+ ledgerClient,
175
+ partyId,
176
+ this.isMasterUser
177
+ );
178
+ return await parser.parseTransferObjects();
179
+ }
180
+ async toPrettyTransactionsPerParty(updates, parties, ledgerClient) {
181
+ const all = await Promise.all(
182
+ parties.map(
183
+ async (partyId) => [
184
+ partyId,
185
+ await this.toPrettyTransactions(
186
+ updates,
187
+ partyId,
188
+ ledgerClient
189
+ )
190
+ ]
191
+ )
192
+ );
193
+ return new Map(all);
194
+ }
195
+ // returns object with JsActiveContract content
196
+ // and contractId and interface view value extracted from it as separate fields for convenience
197
+ toPrettyContract(interfaceId, response, offset) {
198
+ const activeContract = response.contractEntry.JsActiveContract;
199
+ const { createdEvent } = activeContract;
200
+ return {
201
+ contractId: createdEvent.contractId,
202
+ activeContract,
203
+ interfaceViewValue: ensureInterfaceViewIsPresent(
204
+ createdEvent,
205
+ interfaceId
206
+ ).viewValue,
207
+ fetchedAtOffset: offset
208
+ };
209
+ }
210
+ toQualifiedMemberId(memberId) {
211
+ if (!memberId) throw new Error("memberId is required");
212
+ return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
213
+ }
214
+ };
215
+ var AllocationService = class {
216
+ constructor(core, logger) {
217
+ this.core = core;
218
+ this.logger = logger;
219
+ }
220
+ async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
221
+ const allocationSpecificationNormalized = {
222
+ ...allocationSpecification,
223
+ settlement: {
224
+ ...allocationSpecification.settlement,
225
+ meta: allocationSpecification.settlement.meta ?? { values: {} }
226
+ },
227
+ transferLeg: {
228
+ ...allocationSpecification.transferLeg,
229
+ meta: allocationSpecification.transferLeg.meta ?? {
230
+ values: {}
231
+ }
232
+ }
233
+ };
234
+ const inputHoldingCids = await this.core.getInputHoldingsCids(
235
+ allocationSpecificationNormalized.transferLeg.sender,
236
+ inputUtxos
237
+ );
238
+ return {
239
+ expectedAdmin,
240
+ allocation: allocationSpecificationNormalized,
241
+ requestedAt: requestedAt ?? new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
242
+ inputHoldingCids,
243
+ extraArgs: {
244
+ context: { values: {} },
245
+ meta: { values: {} }
246
+ }
247
+ };
248
+ }
249
+ async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
250
+ return this.core.getTokenStandardClient(registryUrl).post("/registry/allocation-instruction/v1/allocation-factory", {
251
+ choiceArguments: choiceArgs,
252
+ excludeDebugFields
253
+ });
254
+ }
255
+ async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
256
+ choiceArgs.extraArgs.context = {
257
+ ...choiceContext.choiceContextData,
258
+ values: choiceContext.choiceContextData?.values ?? {}
259
+ };
260
+ const exercise = {
261
+ templateId: ALLOCATION_FACTORY_INTERFACE_ID,
262
+ contractId: factoryId,
263
+ choice: "AllocationFactory_Allocate",
264
+ choiceArgument: choiceArgs
265
+ };
266
+ return [exercise, choiceContext.disclosedContracts];
267
+ }
268
+ async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
269
+ const choiceArgs = await this.buildAllocationFactoryChoiceArgs(
270
+ allocationSpecification,
271
+ expectedAdmin,
272
+ inputUtxos,
273
+ requestedAt
274
+ );
275
+ if (prefetchedRegistryChoiceContext) {
276
+ return this.createAllocationInstructionFromContext(
277
+ prefetchedRegistryChoiceContext.factoryId,
278
+ choiceArgs,
279
+ prefetchedRegistryChoiceContext.choiceContext
280
+ );
281
+ }
282
+ const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(
283
+ registryUrl,
284
+ choiceArgs
285
+ );
286
+ return this.createAllocationInstructionFromContext(
287
+ factoryId,
288
+ choiceArgs,
289
+ choiceContext
290
+ );
291
+ }
292
+ buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
293
+ const exercise = {
294
+ templateId,
295
+ contractId,
296
+ choice,
297
+ choiceArgument: {
298
+ extraArgs: {
299
+ context: choiceContext.choiceContextData,
300
+ meta: EMPTY_META
301
+ }
302
+ }
303
+ };
304
+ return [exercise, choiceContext.disclosedContracts ?? []];
305
+ }
306
+ async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
307
+ return this.core.getTokenStandardClient(registryUrl).post(
308
+ "/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer",
309
+ {
310
+ excludeDebugFields: true
311
+ },
312
+ {
313
+ path: {
314
+ allocationId
315
+ }
316
+ }
317
+ );
318
+ }
319
+ createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
320
+ return this.buildAllocationExerciseWithContext(
321
+ ALLOCATION_INTERFACE_ID,
322
+ allocationCid,
323
+ "Allocation_ExecuteTransfer",
324
+ choiceContext
325
+ );
326
+ }
327
+ async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
328
+ if (prefetchedRegistryChoiceContext) {
329
+ return this.createExecuteTransferAllocationFromContext(
330
+ allocationCid,
331
+ prefetchedRegistryChoiceContext
332
+ );
333
+ }
334
+ const choiceContext = await this.fetchExecuteTransferChoiceContext(
335
+ allocationCid,
336
+ registryUrl
337
+ );
338
+ return this.createExecuteTransferAllocationFromContext(
339
+ allocationCid,
340
+ choiceContext
341
+ );
342
+ }
343
+ async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
344
+ return this.core.getTokenStandardClient(registryUrl).post(
345
+ "/registry/allocations/v1/{allocationId}/choice-contexts/withdraw",
346
+ {
347
+ excludeDebugFields: true
348
+ },
349
+ { path: { allocationId: allocationCid } }
350
+ );
351
+ }
352
+ createWithdrawAllocationFromContext(allocationCid, choiceContext) {
353
+ return this.buildAllocationExerciseWithContext(
354
+ ALLOCATION_INTERFACE_ID,
355
+ allocationCid,
356
+ "Allocation_Withdraw",
357
+ choiceContext
358
+ );
359
+ }
360
+ async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
361
+ if (prefetchedRegistryChoiceContext) {
362
+ return this.createWithdrawAllocationFromContext(
363
+ allocationCid,
364
+ prefetchedRegistryChoiceContext
365
+ );
366
+ }
367
+ const choiceContext = await this.fetchWithdrawAllocationChoiceContext(
368
+ allocationCid,
369
+ registryUrl
370
+ );
371
+ return this.createWithdrawAllocationFromContext(
372
+ allocationCid,
373
+ choiceContext
374
+ );
375
+ }
376
+ async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
377
+ return this.core.getTokenStandardClient(registryUrl).post(
378
+ "/registry/allocations/v1/{allocationId}/choice-contexts/cancel",
379
+ {
380
+ excludeDebugFields: true
381
+ },
382
+ { path: { allocationId: allocationCid } }
383
+ );
384
+ }
385
+ createCancelAllocationFromContext(allocationCid, choiceContext) {
386
+ return this.buildAllocationExerciseWithContext(
387
+ ALLOCATION_INTERFACE_ID,
388
+ allocationCid,
389
+ "Allocation_Cancel",
390
+ choiceContext
391
+ );
392
+ }
393
+ async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
394
+ if (prefetchedRegistryChoiceContext) {
395
+ return this.createCancelAllocationFromContext(
396
+ allocationCid,
397
+ prefetchedRegistryChoiceContext
398
+ );
399
+ }
400
+ const choiceContext = await this.fetchCancelAllocationChoiceContext(
401
+ allocationCid,
402
+ registryUrl
403
+ );
404
+ return this.createCancelAllocationFromContext(
405
+ allocationCid,
406
+ choiceContext
407
+ );
408
+ }
409
+ async createWithdrawAllocationInstruction(allocationInstructionCid) {
410
+ const exercise = {
411
+ templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
412
+ contractId: allocationInstructionCid,
413
+ choice: "AllocationInstruction_Withdraw",
414
+ choiceArgument: {
415
+ extraArgs: {
416
+ context: { values: {} },
417
+ meta: { values: {} }
418
+ }
419
+ }
420
+ };
421
+ return [exercise, []];
422
+ }
423
+ async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
424
+ const exercise = {
425
+ templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
426
+ contractId: allocationInstructionCid,
427
+ choice: "AllocationInstruction_Update",
428
+ choiceArgument: {
429
+ extraActors,
430
+ extraArgs: {
431
+ context: { values: extraArgsContext },
432
+ meta: { values: extraArgsMeta }
433
+ }
434
+ }
435
+ };
436
+ return [exercise, []];
437
+ }
438
+ async createRejectAllocationRequest(allocationRequestCid, actor) {
439
+ const exercise = {
440
+ templateId: ALLOCATION_REQUEST_INTERFACE_ID,
441
+ contractId: allocationRequestCid,
442
+ choice: "AllocationRequest_Reject",
443
+ choiceArgument: {
444
+ actor,
445
+ extraArgs: {
446
+ context: { values: {} },
447
+ meta: { values: {} }
448
+ }
449
+ }
450
+ };
451
+ return [exercise, []];
452
+ }
453
+ async createWithdrawAllocationRequest(allocationRequestCid) {
454
+ const exercise = {
455
+ templateId: ALLOCATION_REQUEST_INTERFACE_ID,
456
+ contractId: allocationRequestCid,
457
+ choice: "AllocationRequest_Withdraw",
458
+ choiceArgument: {
459
+ extraArgs: {
460
+ context: { values: {} },
461
+ meta: { values: {} }
462
+ }
463
+ }
464
+ };
465
+ return [exercise, []];
466
+ }
467
+ };
468
+ var TransferService = class {
469
+ constructor(core, logger) {
470
+ this.core = core;
471
+ this.logger = logger;
472
+ }
473
+ async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion) {
474
+ const inputHoldingCids = await this.core.getInputHoldingsCids(
475
+ sender,
476
+ inputUtxos,
477
+ parseFloat(amount),
478
+ continueUntilCompletion
479
+ );
480
+ return {
481
+ expectedAdmin: instrumentAdmin,
482
+ transfer: {
483
+ sender,
484
+ receiver,
485
+ amount,
486
+ instrumentId: { admin: instrumentAdmin, id: instrumentId },
487
+ requestedAt: new Date(
488
+ Date.now() - REQUESTED_AT_SKEW_MS
489
+ ).toISOString(),
490
+ executeBefore: (expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1e3)).toISOString(),
491
+ inputHoldingCids,
492
+ meta: {
493
+ values: {
494
+ [TokenStandardService.MEMO_KEY]: memo || "",
495
+ ...meta?.values
496
+ }
497
+ }
498
+ },
499
+ extraArgs: {
500
+ context: { values: {} },
501
+ meta: { values: {} }
502
+ }
503
+ };
504
+ }
505
+ async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
506
+ return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
507
+ choiceArguments: choiceArgs,
508
+ excludeDebugFields
509
+ });
510
+ }
511
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
512
+ this.logger.debug("Creating transfer from pre-fetched context...");
513
+ choiceArgs.extraArgs.context = {
514
+ ...choiceContext.choiceContextData,
515
+ values: choiceContext.choiceContextData?.values ?? {}
516
+ };
517
+ const exercise = {
518
+ templateId: TRANSFER_FACTORY_INTERFACE_ID,
519
+ contractId: factoryId,
520
+ choice: "TransferFactory_Transfer",
521
+ choiceArgument: choiceArgs
522
+ };
523
+ return [exercise, choiceContext.disclosedContracts];
524
+ }
525
+ // TODO: use named parameters
526
+ async createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext, continueUntilCompletion) {
527
+ try {
528
+ const choiceArgs = await this.buildTransferChoiceArgs(
529
+ sender,
530
+ receiver,
531
+ amount,
532
+ instrumentAdmin,
533
+ instrumentId,
534
+ inputUtxos,
535
+ memo,
536
+ expiryDate,
537
+ meta,
538
+ continueUntilCompletion
539
+ );
540
+ if (prefetchedRegistryChoiceContext) {
541
+ return this.createTransferFromContext(
542
+ prefetchedRegistryChoiceContext.factoryId,
543
+ choiceArgs,
544
+ prefetchedRegistryChoiceContext.choiceContext
545
+ );
546
+ }
547
+ const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(
548
+ registryUrl,
549
+ choiceArgs
550
+ );
551
+ return this.createTransferFromContext(
552
+ factoryId,
553
+ choiceArgs,
554
+ choiceContext
555
+ );
556
+ } catch (e) {
557
+ this.logger.error("Failed to execute transfer:", e);
558
+ throw e;
559
+ }
560
+ }
561
+ async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
562
+ const client = this.core.getTokenStandardClient(registryUrl);
563
+ const choiceContext = await client.post(
564
+ "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept",
565
+ {
566
+ excludeDebugFields: true
567
+ },
568
+ {
569
+ path: {
570
+ transferInstructionId: transferInstructionCid
571
+ }
572
+ }
573
+ );
574
+ return {
575
+ choiceContextData: choiceContext.choiceContextData,
576
+ disclosedContracts: choiceContext.disclosedContracts
577
+ };
578
+ }
579
+ async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
580
+ try {
581
+ const exercise = {
582
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
583
+ contractId: transferInstructionCid,
584
+ choice: "TransferInstruction_Accept",
585
+ choiceArgument: {
586
+ extraArgs: {
587
+ context: choiceContext.choiceContextData,
588
+ meta: { values: {} }
589
+ }
590
+ }
591
+ };
592
+ return [exercise, choiceContext.disclosedContracts];
593
+ } catch (e) {
594
+ this.logger.error(
595
+ "Failed to create accept transfer instruction:",
596
+ e
597
+ );
598
+ throw e;
599
+ }
600
+ }
601
+ async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
602
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(
603
+ transferInstructionCid,
604
+ registryUrl.href
605
+ );
606
+ const choiceArgs = {
607
+ cid: acceptTransferInstructionContext.contractId,
608
+ proxyArg: {
609
+ featuredAppRightCid,
610
+ beneficiaries,
611
+ choiceArg: acceptTransferInstructionContext.choiceArgument
612
+ }
613
+ };
614
+ return [
615
+ {
616
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
617
+ contractId: proxyCid,
618
+ choice: "DelegateProxy_TransferInstruction_Accept",
619
+ choiceArgument: choiceArgs
620
+ },
621
+ disclosedContracts
622
+ ];
623
+ }
624
+ async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
625
+ const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(
626
+ transferInstructionCid,
627
+ registryUrl.href
628
+ );
629
+ const choiceArgs = {
630
+ cid: rejectTransferInstructionContext.contractId,
631
+ proxyArg: {
632
+ featuredAppRightCid,
633
+ beneficiaries,
634
+ choiceArg: rejectTransferInstructionContext.choiceArgument
635
+ }
636
+ };
637
+ return [
638
+ {
639
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
640
+ contractId: proxyCid,
641
+ choice: "DelegateProxy_TransferInstruction_Reject",
642
+ choiceArgument: choiceArgs
643
+ },
644
+ disclosedContracts
645
+ ];
646
+ }
647
+ async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
648
+ const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(
649
+ transferInstructionCid,
650
+ registryUrl.href
651
+ );
652
+ const sumOfWeights = beneficiaries.reduce(
653
+ (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
654
+ 0
655
+ );
656
+ if (sumOfWeights > 1) {
657
+ throw new Error("Sum of beneficiary weights is larger than 1.");
658
+ }
659
+ const choiceArgs = {
660
+ cid: withdrawTransferInstructionContext.contractId,
661
+ proxyArg: {
662
+ featuredAppRightCid,
663
+ beneficiaries,
664
+ choiceArg: withdrawTransferInstructionContext.choiceArgument
665
+ }
666
+ };
667
+ return [
668
+ {
669
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
670
+ contractId: proxyCid,
671
+ choice: "DelegateProxy_TransferInstruction_Withdraw",
672
+ choiceArgument: choiceArgs
673
+ },
674
+ disclosedContracts
675
+ ];
676
+ }
677
+ async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
678
+ if (prefetchedRegistryChoiceContext) {
679
+ return this.createAcceptTransferInstructionFromContext(
680
+ transferInstructionCid,
681
+ {
682
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
683
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
684
+ }
685
+ );
686
+ }
687
+ const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(
688
+ transferInstructionCid,
689
+ registryUrl
690
+ );
691
+ return this.createAcceptTransferInstructionFromContext(
692
+ transferInstructionCid,
693
+ choiceContext
694
+ );
695
+ }
696
+ async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
697
+ const client = this.core.getTokenStandardClient(registryUrl);
698
+ const choiceContext = await client.post(
699
+ "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject",
700
+ {
701
+ excludeDebugFields: true
702
+ },
703
+ {
704
+ path: {
705
+ transferInstructionId: transferInstructionCid
706
+ }
707
+ }
708
+ );
709
+ return {
710
+ choiceContextData: choiceContext.choiceContextData,
711
+ disclosedContracts: choiceContext.disclosedContracts
712
+ };
713
+ }
714
+ async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
715
+ try {
716
+ const exercise = {
717
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
718
+ contractId: transferInstructionCid,
719
+ choice: "TransferInstruction_Reject",
720
+ choiceArgument: {
721
+ extraArgs: {
722
+ context: choiceContext.choiceContextData,
723
+ meta: { values: {} }
724
+ }
725
+ }
726
+ };
727
+ return [exercise, choiceContext.disclosedContracts];
728
+ } catch (e) {
729
+ this.logger.error(
730
+ "Failed to create reject transfer instruction:",
731
+ e
732
+ );
733
+ throw e;
734
+ }
735
+ }
736
+ async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
737
+ if (prefetchedRegistryChoiceContext) {
738
+ return this.createRejectTransferInstructionFromContext(
739
+ transferInstructionCid,
740
+ {
741
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
742
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
743
+ }
744
+ );
745
+ }
746
+ const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(
747
+ transferInstructionCid,
748
+ registryUrl
749
+ );
750
+ return this.createRejectTransferInstructionFromContext(
751
+ transferInstructionCid,
752
+ choiceContext
753
+ );
754
+ }
755
+ async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
756
+ const client = this.core.getTokenStandardClient(registryUrl);
757
+ const choiceContext = await client.post(
758
+ "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw",
759
+ {
760
+ excludeDebugFields: true
761
+ },
762
+ {
763
+ path: {
764
+ transferInstructionId: transferInstructionCid
765
+ }
766
+ }
767
+ );
768
+ return {
769
+ choiceContextData: choiceContext.choiceContextData,
770
+ disclosedContracts: choiceContext.disclosedContracts
771
+ };
772
+ }
773
+ async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
774
+ try {
775
+ const exercise = {
776
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
777
+ contractId: transferInstructionCid,
778
+ choice: "TransferInstruction_Withdraw",
779
+ choiceArgument: {
780
+ extraArgs: {
781
+ context: choiceContext.choiceContextData,
782
+ meta: { values: {} }
783
+ }
784
+ }
785
+ };
786
+ return [exercise, choiceContext.disclosedContracts];
787
+ } catch (e) {
788
+ this.logger.error(
789
+ "Failed to create withdraw transfer instruction:",
790
+ e
791
+ );
792
+ throw e;
793
+ }
794
+ }
795
+ async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
796
+ if (prefetchedRegistryChoiceContext) {
797
+ return this.createWithdrawTransferInstructionFromContext(
798
+ transferInstructionCid,
799
+ {
800
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
801
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
802
+ }
803
+ );
804
+ }
805
+ const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(
806
+ transferInstructionCid,
807
+ registryUrl
808
+ );
809
+ return this.createWithdrawTransferInstructionFromContext(
810
+ transferInstructionCid,
811
+ choiceContext
812
+ );
813
+ }
814
+ async createTransferInstruction(transferInstructionCid, registryUrl, instructionChoice, prefetchedRegistryChoiceContext) {
815
+ switch (instructionChoice) {
816
+ case "Accept":
817
+ return this.createAcceptTransferInstruction(
818
+ transferInstructionCid,
819
+ registryUrl,
820
+ prefetchedRegistryChoiceContext
821
+ );
822
+ case "Reject":
823
+ return this.createRejectTransferInstruction(
824
+ transferInstructionCid,
825
+ registryUrl,
826
+ prefetchedRegistryChoiceContext
827
+ );
828
+ case "Withdraw":
829
+ return this.createWithdrawTransferInstruction(
830
+ transferInstructionCid,
831
+ registryUrl,
832
+ prefetchedRegistryChoiceContext
833
+ );
834
+ }
835
+ }
836
+ };
837
+ var TokenStandardService = class {
838
+ constructor(ledgerClient, logger, accessTokenProvider, isMasterUser) {
839
+ this.ledgerClient = ledgerClient;
840
+ this.logger = logger;
841
+ this.accessTokenProvider = accessTokenProvider;
842
+ this.isMasterUser = isMasterUser;
843
+ __publicField(this, "core");
844
+ __publicField(this, "allocation");
845
+ __publicField(this, "transfer");
846
+ this.core = new CoreService(
847
+ ledgerClient,
848
+ logger,
849
+ accessTokenProvider,
850
+ isMasterUser,
851
+ void 0,
852
+ void 0
853
+ );
854
+ this.allocation = new AllocationService(this.core, this.logger);
855
+ this.transfer = new TransferService(this.core, this.logger);
856
+ }
857
+ async getInstrumentById(registryUrl, instrumentId) {
858
+ try {
859
+ const params = {
860
+ path: {
861
+ instrumentId
862
+ }
863
+ };
864
+ const client = this.core.getTokenStandardClient(registryUrl);
865
+ return client.get(
866
+ "/registry/metadata/v1/instruments/{instrumentId}",
867
+ params
868
+ );
869
+ } catch (e) {
870
+ this.logger.error(e);
871
+ throw new Error(
872
+ `Instrument id ${instrumentId} does not exist for this instrument admin.`
873
+ );
874
+ }
875
+ }
876
+ async getInstrumentAdmin(registryUrl) {
877
+ const client = this.core.getTokenStandardClient(registryUrl);
878
+ const info = await client.get("/registry/metadata/v1/info");
879
+ return info.adminId;
880
+ }
881
+ async listInstruments(registryUrl, pageSize, pageToken) {
882
+ const client = this.core.getTokenStandardClient(registryUrl);
883
+ return client.get("/registry/metadata/v1/instruments", {
884
+ query: {
885
+ ...pageSize && { pageSize },
886
+ ...pageToken && { pageToken }
887
+ }
888
+ });
889
+ }
890
+ async instrumentsToAsset(registryUrl) {
891
+ const instrumentsResponse = await this.listInstruments(registryUrl);
892
+ const instrumentAdmin = await this.getInstrumentAdmin(registryUrl);
893
+ return instrumentsResponse.instruments.map((instrument) => ({
894
+ id: instrument.id,
895
+ displayName: instrument.name,
896
+ symbol: instrument.symbol,
897
+ registryUrl,
898
+ admin: instrumentAdmin
899
+ }));
900
+ }
901
+ async registriesToAssets(registryUrls) {
902
+ const allInstruments = [];
903
+ for (const registryUrl of registryUrls) {
904
+ const instruments = await this.instrumentsToAsset(registryUrl);
905
+ allInstruments.push(...instruments);
906
+ }
907
+ return allInstruments;
908
+ }
909
+ // <T> is shape of viewValue related to queried interface.
910
+ // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
911
+ async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
912
+ return this.core.listContractsByInterface(
913
+ interfaceId,
914
+ partyId,
915
+ limit,
916
+ offset,
917
+ continueUntilCompletion
918
+ );
919
+ }
920
+ async listHoldingTransactions(partyId, afterOffset, beforeOffset) {
921
+ try {
922
+ this.logger.debug("Set or query offset");
923
+ const afterOffsetOrLatest = Number(afterOffset) || (await this.ledgerClient.getWithRetry(
924
+ "/v2/state/latest-pruned-offsets"
925
+ )).participantPrunedUpToInclusive;
926
+ const beforeOffsetOrLatest = Number(beforeOffset) || (await this.ledgerClient.getWithRetry("/v2/state/ledger-end")).offset;
927
+ this.logger.debug(afterOffsetOrLatest, "Using offset");
928
+ const updatesResponse = await this.ledgerClient.postWithRetry("/v2/updates/flats", {
929
+ updateFormat: {
930
+ includeTransactions: {
931
+ eventFormat: EventFilterBySetup({
932
+ interfaceIds: TokenStandardTransactionInterfaces,
933
+ isMasterUser: this.isMasterUser,
934
+ partyId,
935
+ includeWildcard: true
936
+ }),
937
+ transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
938
+ }
939
+ },
940
+ beginExclusive: afterOffsetOrLatest,
941
+ endInclusive: beforeOffsetOrLatest,
942
+ verbose: false
943
+ });
944
+ return this.core.toPrettyTransactions(
945
+ updatesResponse,
946
+ partyId,
947
+ this.ledgerClient
948
+ );
949
+ } catch (err) {
950
+ this.logger.error("Failed to list holding transactions.", err);
951
+ throw err;
952
+ }
953
+ }
954
+ async getTransactionById(updateId, partyId) {
955
+ const transactionFormat = {
956
+ eventFormat: EventFilterBySetup({
957
+ interfaceIds: TokenStandardTransactionInterfaces,
958
+ isMasterUser: this.isMasterUser,
959
+ partyId,
960
+ includeWildcard: true
961
+ }),
962
+ transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
963
+ };
964
+ const getTransactionResponse = await this.ledgerClient.postWithRetry(
965
+ "/v2/updates/transaction-by-id",
966
+ {
967
+ updateId,
968
+ transactionFormat
969
+ }
970
+ );
971
+ return this.core.toPrettyTransaction(
972
+ getTransactionResponse,
973
+ partyId,
974
+ this.ledgerClient
975
+ );
976
+ }
977
+ async getTransferObjectsById(updateId, partyId) {
978
+ const transactionFormat = {
979
+ eventFormat: EventFilterBySetup({
980
+ interfaceIds: TokenStandardTransactionInterfaces,
981
+ isMasterUser: this.isMasterUser,
982
+ partyId,
983
+ includeWildcard: true
984
+ }),
985
+ transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
986
+ };
987
+ const getTransactionResponse = await this.ledgerClient.postWithRetry(
988
+ "/v2/updates/transaction-by-id",
989
+ {
990
+ updateId,
991
+ transactionFormat
992
+ }
993
+ );
994
+ return this.core.toPrettyTransferObjects(
995
+ getTransactionResponse,
996
+ partyId,
997
+ this.ledgerClient
998
+ );
999
+ }
1000
+ async getInputHoldingsCids(sender, inputUtxos, amount) {
1001
+ return this.core.getInputHoldingsCids(sender, inputUtxos, amount);
1002
+ }
1003
+ async createDelegateProxyTranfser(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, featuredAppRightCid, proxyCid, beneficiaries, inputUtxos, memo, expiryDate, meta) {
1004
+ const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(
1005
+ sender,
1006
+ receiver,
1007
+ amount,
1008
+ instrumentAdmin,
1009
+ instrumentId,
1010
+ registryUrl,
1011
+ inputUtxos,
1012
+ memo,
1013
+ expiryDate,
1014
+ meta
1015
+ );
1016
+ const sumOfWeights = beneficiaries.reduce(
1017
+ (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
1018
+ 0
1019
+ );
1020
+ if (sumOfWeights > 1) {
1021
+ throw new Error("Sum of beneficiary weights is larger than 1.");
1022
+ }
1023
+ const choiceArgs = {
1024
+ cid: transferCommand.contractId,
1025
+ proxyArg: {
1026
+ featuredAppRightCid,
1027
+ beneficiaries,
1028
+ choiceArg: transferCommand.choiceArgument
1029
+ }
1030
+ };
1031
+ const exercise = {
1032
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1033
+ contractId: proxyCid,
1034
+ choice: "DelegateProxy_TransferFactory_Transfer",
1035
+ choiceArgument: choiceArgs
1036
+ };
1037
+ return [exercise, disclosedContracts];
1038
+ }
1039
+ async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
1040
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(
1041
+ transferInstructionCid,
1042
+ registryUrl
1043
+ );
1044
+ const choiceArgs = {
1045
+ cid: acceptTransferInstructionContext.contractId,
1046
+ proxyArg: {
1047
+ featuredAppRightCid,
1048
+ beneficiaries: [
1049
+ {
1050
+ beneficiary: exchangeParty,
1051
+ weight: 1
1052
+ }
1053
+ ],
1054
+ choiceArg: acceptTransferInstructionContext.choiceArgument
1055
+ }
1056
+ };
1057
+ return [
1058
+ {
1059
+ templateId: "#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy",
1060
+ contractId: proxyCid,
1061
+ choice: "DelegateProxy_TransferInstruction_Accept",
1062
+ choiceArgument: choiceArgs
1063
+ },
1064
+ disclosedContracts
1065
+ ];
1066
+ }
1067
+ static isHoldingLocked(holding, currentTime = /* @__PURE__ */ new Date()) {
1068
+ const lock = holding.lock;
1069
+ if (!lock) return false;
1070
+ const expiresAt = lock.expiresAt;
1071
+ if (!expiresAt) return true;
1072
+ const expiresAtDate = new Date(expiresAt);
1073
+ return currentTime < expiresAtDate;
1074
+ }
1075
+ };
1076
+ __publicField(TokenStandardService, "MEMO_KEY", "splice.lfdecentralizedtrust.org/reason");
1077
+
1078
+ export { CoreService, TokenStandardService };
1079
+ //# sourceMappingURL=index.js.map
1080
+ //# sourceMappingURL=index.js.map