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