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