@canton-network/core-token-standard-service 1.13.0 → 1.14.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,54 +1,37 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
2
24
  let _canton_network_core_token_standard = require("@canton-network/core-token-standard");
3
25
  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
26
  let _canton_network_core_tx_parser = require("@canton-network/core-tx-parser");
6
27
  let decimal_js = require("decimal.js");
7
- //#region \0@oxc-project+runtime@0.151.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.151.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.151.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.151.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
28
+ decimal_js = __toESM(decimal_js, 1);
29
+ let _canton_network_core_token_standard_v2 = require("@canton-network/core-token-standard-v2");
30
+ let _canton_network_core_acs_reader = require("@canton-network/core-acs-reader");
31
+ //#region src/types.ts
46
32
  const REQUESTED_AT_SKEW_MS = 6e4;
47
33
  const EMPTY_META = { values: {} };
48
34
  const SUPPORTED_VERSIONS = ["v1", "v2"];
49
- function isApiVersion(v) {
50
- return SUPPORTED_VERSIONS.includes(v);
51
- }
52
35
  const KEY_MAPPING = {
53
36
  holding: "holding",
54
37
  "transfer-instruction": "transferInstruction",
@@ -56,304 +39,115 @@ const KEY_MAPPING = {
56
39
  "allocation-instruction": "allocationInstruction",
57
40
  "allocation-request": "allocationRequest"
58
41
  };
59
- function resolveCapabilities(opts) {
60
- const supportedApis = opts.supportedApis;
61
- const resolvedCapabilities = {
62
- holding: [],
63
- transferInstruction: [],
64
- allocation: [],
65
- allocationInstruction: [],
66
- allocationRequest: []
67
- };
68
- for (const key of Object.keys(supportedApis)) {
69
- const match = key.match(/^splice-api-token-(?<capabilityName>.+)-(?<version>v\d+)$/);
70
- if (match?.groups) {
71
- const { capabilityName, version } = match.groups;
72
- const targetKey = KEY_MAPPING[capabilityName];
73
- if (targetKey && supportedApis[key] === 1 && isApiVersion(version)) resolvedCapabilities[targetKey].push(version);
74
- }
75
- }
76
- for (const key in resolvedCapabilities) resolvedCapabilities[key].sort();
77
- return resolvedCapabilities;
78
- }
79
- var CoreService = class CoreService {
80
- constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
81
- this.ledgerProvider = ledgerProvider;
82
- this.logger = logger;
83
- this.accessTokenProvider = accessTokenProvider;
84
- this.isMasterUser = isMasterUser;
85
- }
86
- getTokenStandardClient(registryUrl) {
87
- return new _canton_network_core_token_standard.TokenStandardClient(registryUrl, this.logger, this.accessTokenProvider);
88
- }
89
- async getInputHoldingsCids(options) {
90
- const { sender, instrumentAdmin, instrumentId } = options;
91
- const now = /* @__PURE__ */ new Date();
92
- if (options.inputUtxos && options.inputUtxos.length > 0) return options.inputUtxos;
93
- const senderHoldings = await this.listContractsByInterface(_canton_network_core_token_standard.HOLDING_INTERFACE_ID, sender, void 0, void 0, options.continueUntilCompletion);
94
- if (senderHoldings.length === 0) throw new Error("Sender has no holdings, so transfer can't be executed.");
95
- const unlockedSenderHoldings = senderHoldings.filter((utxo) => !TokenStandardService.isHoldingLocked(utxo, now));
96
- if (unlockedSenderHoldings.length > 100) this.logger.warn(`Sender has more than 100 unlocked utxos.`);
97
- const unlockedHoldingsForInstrument = instrumentAdmin && instrumentId ? await CoreService.filterHoldingsByInstrument({
98
- holdings: unlockedSenderHoldings,
99
- instrumentAdmin,
100
- instrumentId
101
- }) : unlockedSenderHoldings;
102
- if (options.amount) return CoreService.getInputHoldingsCidsForAmount(options.amount, unlockedHoldingsForInstrument);
103
- else return unlockedHoldingsForInstrument.map((h) => h.contractId);
104
- }
105
- static async filterHoldingsByInstrument(options) {
106
- const { holdings, instrumentAdmin, instrumentId } = options;
107
- return holdings.filter((utxo) => {
108
- return utxo.interfaceViewValue.instrumentId.id === instrumentId && utxo.interfaceViewValue.instrumentId.admin === instrumentAdmin;
109
- });
110
- }
111
- static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
112
- const exactAmount = unlockedSenderHoldings.find((holding) => new decimal_js.Decimal(holding.interfaceViewValue.amount).equals(amount));
113
- if (exactAmount) return [exactAmount.contractId];
114
- const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted((a, b) => new decimal_js.Decimal(a.interfaceViewValue.amount).comparedTo(new decimal_js.Decimal(b.interfaceViewValue.amount)));
115
- const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
116
- if (!largestHoldingAmount) throw new Error(`Sender doesn't have any unlocked holdings`);
117
- let currentSum = new decimal_js.Decimal(largestHoldingAmount.interfaceViewValue.amount);
118
- const cIds = [largestHoldingAmount.contractId];
119
- for (const h of sortedUnlockedSenderHoldings) {
120
- if (currentSum.greaterThanOrEqualTo(amount)) break;
121
- const currentHoldingAmount = new decimal_js.Decimal(h.interfaceViewValue.amount);
122
- currentSum = currentSum.plus(currentHoldingAmount);
123
- cIds.push(h.contractId);
124
- }
125
- if (currentSum.lessThan(amount)) throw new Error(`Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount.minus(currentSum)}`);
126
- if (cIds.length > 100) throw new Error(`Exceeded the maximum of 100 utxos in 1 transaction`);
127
- return cIds;
128
- }
129
- async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
130
- try {
131
- const ledgerEnd = offset ?? (await this.ledgerProvider.request({
132
- method: "ledgerApi",
133
- params: {
134
- resource: "/v2/state/ledger-end",
135
- requestMethod: "get",
136
- query: {}
137
- }
138
- })).offset;
139
- const options = {
140
- offset: ledgerEnd,
141
- interfaceIds: [interfaceId],
142
- parties: [partyId],
143
- filterByParty: true,
144
- continueUntilCompletion: Boolean(continueUntilCompletion)
145
- };
146
- if (limit !== void 0) options.limit = limit;
147
- this.logger.info(`continue to completion: ${Boolean(continueUntilCompletion)}`);
148
- const acsResponses = await new _canton_network_core_acs_reader.ACSReader(this.ledgerProvider).raw.read(options);
149
- const isActiveContractEntry = (acsResponse) => acsResponse.contractEntry != null && "JsActiveContract" in acsResponse.contractEntry && acsResponse.contractEntry.JsActiveContract != null && acsResponse.contractEntry.JsActiveContract.createdEvent != null;
150
- return acsResponses.filter(isActiveContractEntry).map((response) => this.toPrettyContract(interfaceId, response, ledgerEnd));
151
- } catch (err) {
152
- this.logger.error(`Failed to list contracts of interface ${interfaceId}`, err);
153
- throw err;
154
- }
155
- }
156
- async toPrettyTransactions(updates, partyId) {
157
- const isOffsetCheckpointUpdate = (updateResponse) => updateResponse.update != null && "OffsetCheckpoint" in updateResponse.update;
158
- const isTransactionUpdate = (updateResponse) => updateResponse.update != null && "Transaction" in updateResponse.update && !!updateResponse.update.Transaction?.value;
159
- const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map((update) => update.update.OffsetCheckpoint.value.offset);
160
- const latestCheckpointOffset = offsetCheckpoints.length > 0 ? Math.max(...offsetCheckpoints) : 0;
161
- const transactions = await Promise.all(updates.filter(isTransactionUpdate).map(async (update) => {
162
- const tx = update.update.Transaction.value;
163
- return await new _canton_network_core_tx_parser.TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
164
- }));
165
- const transactionOffsets = transactions.map((tx) => tx.offset).filter((offset) => offset !== void 0);
166
- return {
167
- nextOffset: Math.max(latestCheckpointOffset, ...transactionOffsets.length > 0 ? transactionOffsets : [0]),
168
- transactions: transactions.filter((tx) => tx.events.length > 0).map(_canton_network_core_tx_parser.renderTransaction)
169
- };
170
- }
171
- async toPrettyTransaction(getUpdateResponse, partyId) {
172
- const tx = this.getTransactionFromUpdate(getUpdateResponse);
173
- const parsedTx = await new _canton_network_core_tx_parser.TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
174
- return (0, _canton_network_core_tx_parser.renderTransaction)(parsedTx);
175
- }
176
- async toPrettyTransferObjects(getUpdateResponse, partyId) {
177
- const tx = this.getTransactionFromUpdate(getUpdateResponse);
178
- return await new _canton_network_core_tx_parser.TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransferObjects();
179
- }
180
- getTransactionFromUpdate(getUpdateResponse) {
181
- const update = getUpdateResponse.update;
182
- if (!update || !("Transaction" in update)) throw new Error("Expected transaction update");
183
- return update.Transaction.value;
184
- }
185
- async toPrettyTransactionsPerParty(updates, parties) {
186
- const all = await Promise.all(parties.map(async (partyId) => [partyId, await this.toPrettyTransactions(updates, partyId)]));
187
- return new Map(all);
188
- }
189
- toPrettyContract(interfaceId, response, offset) {
190
- const activeContract = response.contractEntry.JsActiveContract;
191
- const { createdEvent } = activeContract;
192
- return {
193
- contractId: createdEvent.contractId,
194
- activeContract,
195
- interfaceViewValue: (0, _canton_network_core_tx_parser.ensureInterfaceViewIsPresent)(createdEvent, interfaceId).viewValue,
196
- fetchedAtOffset: offset
197
- };
198
- }
199
- toQualifiedMemberId(memberId) {
200
- if (!memberId) throw new Error("memberId is required");
201
- return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
202
- }
203
- };
204
- var AllocationService = class {
42
+ //#endregion
43
+ //#region src/v2/transfer-service.ts
44
+ var TransferServiceV2 = class {
205
45
  constructor(core, logger) {
206
46
  this.core = core;
207
47
  this.logger = logger;
208
48
  }
209
- async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
210
- const allocationSpecificationNormalized = {
211
- ...allocationSpecification,
212
- settlement: {
213
- ...allocationSpecification.settlement,
214
- meta: allocationSpecification.settlement.meta ?? { values: {} }
215
- },
216
- transferLeg: {
217
- ...allocationSpecification.transferLeg,
218
- meta: allocationSpecification.transferLeg.meta ?? { values: {} }
219
- }
220
- };
221
- const inputHoldingCids = await this.core.getInputHoldingsCids({
222
- sender: allocationSpecificationNormalized.transferLeg.sender,
223
- inputUtxos: inputUtxos ?? [],
224
- instrumentAdmin: allocationSpecificationNormalized.transferLeg.instrumentId.admin,
225
- instrumentId: allocationSpecificationNormalized.transferLeg.instrumentId.id
49
+ async buildTransferChoiceArgs(opts) {
50
+ const inputHoldingCids = await this.core.getInputHoldingCidsForAccount({
51
+ account: opts.sender,
52
+ instrumentAdmin: opts.instrumentAdmin,
53
+ instrumentId: opts.instrumentId,
54
+ inputUtxos: opts.inputUtxos ?? [],
55
+ amount: new decimal_js.default(opts.amount),
56
+ continueUntilCompletion: opts.continueUntilCompletion ?? false
226
57
  });
227
58
  return {
228
- expectedAdmin,
229
- allocation: allocationSpecificationNormalized,
230
- requestedAt: requestedAt ?? (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
231
- inputHoldingCids,
59
+ actors: opts.actors ?? [opts.sender.owner, opts.sender.provider].flatMap((partyId) => partyId != null ? [partyId] : []),
60
+ transfer: {
61
+ sender: opts.sender,
62
+ receiver: opts.receiver,
63
+ amount: opts.amount,
64
+ instrumentId: {
65
+ admin: opts.instrumentAdmin,
66
+ id: opts.instrumentId
67
+ },
68
+ requestedAt: (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
69
+ executeBefore: (opts.expiryDate ?? new Date(Date.now() + 864e5)).toISOString(),
70
+ inputHoldingCids,
71
+ meta: { values: {
72
+ [TokenStandardService.MEMO_KEY]: opts.memo || "",
73
+ ...opts.meta?.values
74
+ } }
75
+ },
232
76
  extraArgs: {
233
77
  context: { values: {} },
234
78
  meta: { values: {} }
235
79
  }
236
80
  };
237
81
  }
238
- async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
239
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocation-instruction/v1/allocation-factory", {
82
+ async createTransfer(args, registryUrl, prefetched) {
83
+ const choiceArgs = await this.buildTransferChoiceArgs(args);
84
+ const { factoryId, choiceContext } = prefetched ?? await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/transfer-factory", {
240
85
  choiceArguments: choiceArgs,
241
- excludeDebugFields
86
+ excludeDebugFields: true
242
87
  });
88
+ return this.createTransferFromContext(factoryId, choiceArgs, choiceContext);
243
89
  }
244
- async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
90
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
91
+ this.logger.debug("Creating transfer from pre-fetched context...");
245
92
  choiceArgs.extraArgs.context = {
246
93
  ...choiceContext.choiceContextData,
247
94
  values: choiceContext.choiceContextData?.values ?? {}
248
95
  };
249
96
  return [{
250
- templateId: _canton_network_core_token_standard.ALLOCATION_FACTORY_INTERFACE_ID,
97
+ templateId: _canton_network_core_token_standard_v2.TRANSFER_FACTORY_INTERFACE_ID_V2,
251
98
  contractId: factoryId,
252
- choice: "AllocationFactory_Allocate",
99
+ choice: "TransferFactory_Transfer",
253
100
  choiceArgument: choiceArgs
254
101
  }, choiceContext.disclosedContracts];
255
102
  }
256
- async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
257
- const choiceArgs = await this.buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt);
258
- if (prefetchedRegistryChoiceContext) return this.createAllocationInstructionFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
259
- const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs);
260
- return this.createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext);
103
+ async rejectTransferInstruction(transferInstructionCid, actors, registryUrl) {
104
+ const ctx = await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/{transferInstructionId}/choice-contexts/reject", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
105
+ return [{
106
+ templateId: _canton_network_core_token_standard_v2.TRANSFER_INSTRUCTION_INTERFACE_ID_V2,
107
+ contractId: transferInstructionCid,
108
+ choice: _canton_network_core_token_standard_v2.TransferInstruction.TransferInstruction_Reject.choiceName,
109
+ choiceArgument: {
110
+ actors,
111
+ extraArgs: {
112
+ context: ctx.choiceContextData,
113
+ meta: EMPTY_META
114
+ }
115
+ }
116
+ }, ctx.disclosedContracts ?? []];
261
117
  }
262
- buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
118
+ async withdrawTransferInstruction(transferInstructionCid, actors, registryUrl) {
119
+ const ctx = await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/{transferInstructionId}/choice-contexts/withdraw", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
263
120
  return [{
264
- templateId,
265
- contractId,
266
- choice,
267
- choiceArgument: { extraArgs: {
268
- context: choiceContext.choiceContextData,
269
- meta: EMPTY_META
270
- } }
271
- }, choiceContext.disclosedContracts ?? []];
121
+ templateId: _canton_network_core_token_standard_v2.TRANSFER_INSTRUCTION_INTERFACE_ID_V2,
122
+ contractId: transferInstructionCid,
123
+ choice: _canton_network_core_token_standard_v2.TransferInstruction.TransferInstruction_Withdraw.choiceName,
124
+ choiceArgument: {
125
+ actors,
126
+ extraArgs: {
127
+ context: ctx.choiceContextData,
128
+ meta: EMPTY_META
129
+ }
130
+ }
131
+ }, ctx.disclosedContracts ?? []];
272
132
  }
273
- async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
274
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer", { excludeDebugFields: true }, { path: { allocationId } });
275
- }
276
- createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
277
- return this.buildAllocationExerciseWithContext(_canton_network_core_token_standard.ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_ExecuteTransfer", choiceContext);
278
- }
279
- async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
280
- if (prefetchedRegistryChoiceContext) return this.createExecuteTransferAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
281
- const choiceContext = await this.fetchExecuteTransferChoiceContext(allocationCid, registryUrl);
282
- return this.createExecuteTransferAllocationFromContext(allocationCid, choiceContext);
283
- }
284
- async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
285
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/withdraw", { excludeDebugFields: true }, { path: { allocationId: allocationCid } });
286
- }
287
- createWithdrawAllocationFromContext(allocationCid, choiceContext) {
288
- return this.buildAllocationExerciseWithContext(_canton_network_core_token_standard.ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_Withdraw", choiceContext);
289
- }
290
- async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
291
- if (prefetchedRegistryChoiceContext) return this.createWithdrawAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
292
- const choiceContext = await this.fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl);
293
- return this.createWithdrawAllocationFromContext(allocationCid, choiceContext);
294
- }
295
- async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
296
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/cancel", { excludeDebugFields: true }, { path: { allocationId: allocationCid } });
297
- }
298
- createCancelAllocationFromContext(allocationCid, choiceContext) {
299
- return this.buildAllocationExerciseWithContext(_canton_network_core_token_standard.ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_Cancel", choiceContext);
300
- }
301
- async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
302
- if (prefetchedRegistryChoiceContext) return this.createCancelAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
303
- const choiceContext = await this.fetchCancelAllocationChoiceContext(allocationCid, registryUrl);
304
- return this.createCancelAllocationFromContext(allocationCid, choiceContext);
305
- }
306
- async createWithdrawAllocationInstruction(allocationInstructionCid) {
307
- return [{
308
- templateId: _canton_network_core_token_standard.ALLOCATION_INSTRUCTION_INTERFACE_ID,
309
- contractId: allocationInstructionCid,
310
- choice: "AllocationInstruction_Withdraw",
311
- choiceArgument: { extraArgs: {
312
- context: { values: {} },
313
- meta: { values: {} }
314
- } }
315
- }, []];
316
- }
317
- async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
318
- return [{
319
- templateId: _canton_network_core_token_standard.ALLOCATION_INSTRUCTION_INTERFACE_ID,
320
- contractId: allocationInstructionCid,
321
- choice: "AllocationInstruction_Update",
322
- choiceArgument: {
323
- extraActors,
324
- extraArgs: {
325
- context: { values: extraArgsContext },
326
- meta: { values: extraArgsMeta }
327
- }
328
- }
329
- }, []];
330
- }
331
- async createRejectAllocationRequest(allocationRequestCid, actor) {
332
- return [{
333
- templateId: _canton_network_core_token_standard.ALLOCATION_REQUEST_INTERFACE_ID,
334
- contractId: allocationRequestCid,
335
- choice: "AllocationRequest_Reject",
336
- choiceArgument: {
337
- actor,
338
- extraArgs: {
339
- context: { values: {} },
340
- meta: { values: {} }
341
- }
342
- }
343
- }, []];
344
- }
345
- async createWithdrawAllocationRequest(allocationRequestCid) {
346
- return [{
347
- templateId: _canton_network_core_token_standard.ALLOCATION_REQUEST_INTERFACE_ID,
348
- contractId: allocationRequestCid,
349
- choice: "AllocationRequest_Withdraw",
350
- choiceArgument: { extraArgs: {
351
- context: { values: {} },
352
- meta: { values: {} }
353
- } }
354
- }, []];
133
+ async acceptTransferInstruction(transferInstructionCid, actors, registryUrl) {
134
+ const ctx = await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/{transferInstructionId}/choice-contexts/accept", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
135
+ return [{
136
+ templateId: _canton_network_core_token_standard_v2.TRANSFER_INSTRUCTION_INTERFACE_ID_V2,
137
+ contractId: transferInstructionCid,
138
+ choice: _canton_network_core_token_standard_v2.TransferInstruction.TransferInstruction_Accept.choiceName,
139
+ choiceArgument: {
140
+ actors,
141
+ extraArgs: {
142
+ context: ctx.choiceContextData,
143
+ meta: EMPTY_META
144
+ }
145
+ }
146
+ }, ctx.disclosedContracts ?? []];
355
147
  }
356
148
  };
149
+ //#endregion
150
+ //#region src/v1/transfer-service.ts
357
151
  var TransferService = class {
358
152
  constructor(core, logger) {
359
153
  this.core = core;
@@ -434,7 +228,7 @@ var TransferService = class {
434
228
  return [{
435
229
  templateId: _canton_network_core_token_standard.TRANSFER_INSTRUCTION_INTERFACE_ID,
436
230
  contractId: transferInstructionCid,
437
- choice: "TransferInstruction_Accept",
231
+ choice: _canton_network_core_token_standard.TransferInstruction.TransferInstruction_Accept.choiceName,
438
232
  choiceArgument: { extraArgs: {
439
233
  context: choiceContext.choiceContextData,
440
234
  meta: { values: {} }
@@ -446,7 +240,7 @@ var TransferService = class {
446
240
  }
447
241
  }
448
242
  async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
449
- const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(transferInstructionCid, registryUrl.href);
243
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(transferInstructionCid, registryUrl);
450
244
  const choiceArgs = {
451
245
  cid: acceptTransferInstructionContext.contractId,
452
246
  proxyArg: {
@@ -463,7 +257,7 @@ var TransferService = class {
463
257
  }, disclosedContracts];
464
258
  }
465
259
  async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
466
- const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(transferInstructionCid, registryUrl.href);
260
+ const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(transferInstructionCid, registryUrl);
467
261
  const choiceArgs = {
468
262
  cid: rejectTransferInstructionContext.contractId,
469
263
  proxyArg: {
@@ -480,7 +274,7 @@ var TransferService = class {
480
274
  }, disclosedContracts];
481
275
  }
482
276
  async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
483
- const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl.href);
277
+ const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl);
484
278
  if (beneficiaries.reduce((totalWeight, beneficiary) => totalWeight + beneficiary.weight, 0) > 1) throw new Error("Sum of beneficiary weights is larger than 1.");
485
279
  const choiceArgs = {
486
280
  cid: withdrawTransferInstructionContext.contractId,
@@ -517,7 +311,7 @@ var TransferService = class {
517
311
  return [{
518
312
  templateId: _canton_network_core_token_standard.TRANSFER_INSTRUCTION_INTERFACE_ID,
519
313
  contractId: transferInstructionCid,
520
- choice: "TransferInstruction_Reject",
314
+ choice: _canton_network_core_token_standard.TransferInstruction.TransferInstruction_Reject.choiceName,
521
315
  choiceArgument: { extraArgs: {
522
316
  context: choiceContext.choiceContextData,
523
317
  meta: { values: {} }
@@ -548,7 +342,7 @@ var TransferService = class {
548
342
  return [{
549
343
  templateId: _canton_network_core_token_standard.TRANSFER_INSTRUCTION_INTERFACE_ID,
550
344
  contractId: transferInstructionCid,
551
- choice: "TransferInstruction_Withdraw",
345
+ choice: _canton_network_core_token_standard.TransferInstruction.TransferInstruction_Withdraw.choiceName,
552
346
  choiceArgument: { extraArgs: {
553
347
  context: choiceContext.choiceContextData,
554
348
  meta: { values: {} }
@@ -575,6 +369,524 @@ var TransferService = class {
575
369
  }
576
370
  }
577
371
  };
372
+ //#endregion
373
+ //#region src/v1/allocation-service.ts
374
+ var AllocationService$1 = class {
375
+ constructor(core, logger) {
376
+ this.core = core;
377
+ this.logger = logger;
378
+ }
379
+ async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
380
+ const allocationSpecificationNormalized = {
381
+ ...allocationSpecification,
382
+ settlement: {
383
+ ...allocationSpecification.settlement,
384
+ meta: allocationSpecification.settlement.meta ?? { values: {} }
385
+ },
386
+ transferLeg: {
387
+ ...allocationSpecification.transferLeg,
388
+ meta: allocationSpecification.transferLeg.meta ?? { values: {} }
389
+ }
390
+ };
391
+ const inputHoldingCids = await this.core.getInputHoldingsCids({
392
+ sender: allocationSpecificationNormalized.transferLeg.sender,
393
+ inputUtxos: inputUtxos ?? [],
394
+ instrumentAdmin: allocationSpecificationNormalized.transferLeg.instrumentId.admin,
395
+ instrumentId: allocationSpecificationNormalized.transferLeg.instrumentId.id
396
+ });
397
+ return {
398
+ expectedAdmin,
399
+ allocation: allocationSpecificationNormalized,
400
+ requestedAt: requestedAt ?? (/* @__PURE__ */ new Date(Date.now() - 6e4)).toISOString(),
401
+ inputHoldingCids,
402
+ extraArgs: {
403
+ context: { values: {} },
404
+ meta: { values: {} }
405
+ }
406
+ };
407
+ }
408
+ async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
409
+ return this.core.getTokenStandardClient(registryUrl).post("/registry/allocation-instruction/v1/allocation-factory", {
410
+ choiceArguments: choiceArgs,
411
+ excludeDebugFields
412
+ });
413
+ }
414
+ async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
415
+ choiceArgs.extraArgs.context = {
416
+ ...choiceContext.choiceContextData,
417
+ values: choiceContext.choiceContextData?.values ?? {}
418
+ };
419
+ return [{
420
+ templateId: _canton_network_core_token_standard.ALLOCATION_FACTORY_INTERFACE_ID,
421
+ contractId: factoryId,
422
+ choice: "AllocationFactory_Allocate",
423
+ choiceArgument: choiceArgs
424
+ }, choiceContext.disclosedContracts];
425
+ }
426
+ async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
427
+ const choiceArgs = await this.buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt);
428
+ if (prefetchedRegistryChoiceContext) return this.createAllocationInstructionFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
429
+ const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs);
430
+ return this.createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext);
431
+ }
432
+ buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
433
+ return [{
434
+ templateId,
435
+ contractId,
436
+ choice,
437
+ choiceArgument: { extraArgs: {
438
+ context: choiceContext.choiceContextData,
439
+ meta: EMPTY_META
440
+ } }
441
+ }, choiceContext.disclosedContracts ?? []];
442
+ }
443
+ async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
444
+ return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer", { excludeDebugFields: true }, { path: { allocationId } });
445
+ }
446
+ createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
447
+ return this.buildAllocationExerciseWithContext(_canton_network_core_token_standard.ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_ExecuteTransfer", choiceContext);
448
+ }
449
+ async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
450
+ if (prefetchedRegistryChoiceContext) return this.createExecuteTransferAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
451
+ const choiceContext = await this.fetchExecuteTransferChoiceContext(allocationCid, registryUrl);
452
+ return this.createExecuteTransferAllocationFromContext(allocationCid, choiceContext);
453
+ }
454
+ async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
455
+ return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/withdraw", { excludeDebugFields: true }, { path: { allocationId: allocationCid } });
456
+ }
457
+ createWithdrawAllocationFromContext(allocationCid, choiceContext) {
458
+ return this.buildAllocationExerciseWithContext(_canton_network_core_token_standard.ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_Withdraw", choiceContext);
459
+ }
460
+ async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
461
+ if (prefetchedRegistryChoiceContext) return this.createWithdrawAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
462
+ const choiceContext = await this.fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl);
463
+ return this.createWithdrawAllocationFromContext(allocationCid, choiceContext);
464
+ }
465
+ async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
466
+ return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/cancel", { excludeDebugFields: true }, { path: { allocationId: allocationCid } });
467
+ }
468
+ createCancelAllocationFromContext(allocationCid, choiceContext) {
469
+ return this.buildAllocationExerciseWithContext(_canton_network_core_token_standard.ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_Cancel", choiceContext);
470
+ }
471
+ async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
472
+ if (prefetchedRegistryChoiceContext) return this.createCancelAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
473
+ const choiceContext = await this.fetchCancelAllocationChoiceContext(allocationCid, registryUrl);
474
+ return this.createCancelAllocationFromContext(allocationCid, choiceContext);
475
+ }
476
+ async createWithdrawAllocationInstruction(allocationInstructionCid) {
477
+ return [{
478
+ templateId: _canton_network_core_token_standard.ALLOCATION_INSTRUCTION_INTERFACE_ID,
479
+ contractId: allocationInstructionCid,
480
+ choice: "AllocationInstruction_Withdraw",
481
+ choiceArgument: { extraArgs: {
482
+ context: { values: {} },
483
+ meta: { values: {} }
484
+ } }
485
+ }, []];
486
+ }
487
+ async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
488
+ return [{
489
+ templateId: _canton_network_core_token_standard.ALLOCATION_INSTRUCTION_INTERFACE_ID,
490
+ contractId: allocationInstructionCid,
491
+ choice: "AllocationInstruction_Update",
492
+ choiceArgument: {
493
+ extraActors,
494
+ extraArgs: {
495
+ context: { values: extraArgsContext },
496
+ meta: { values: extraArgsMeta }
497
+ }
498
+ }
499
+ }, []];
500
+ }
501
+ async createRejectAllocationRequest(allocationRequestCid, actor) {
502
+ return [{
503
+ templateId: _canton_network_core_token_standard.ALLOCATION_REQUEST_INTERFACE_ID,
504
+ contractId: allocationRequestCid,
505
+ choice: "AllocationRequest_Reject",
506
+ choiceArgument: {
507
+ actor,
508
+ extraArgs: {
509
+ context: { values: {} },
510
+ meta: { values: {} }
511
+ }
512
+ }
513
+ }, []];
514
+ }
515
+ async createWithdrawAllocationRequest(allocationRequestCid) {
516
+ return [{
517
+ templateId: _canton_network_core_token_standard.ALLOCATION_REQUEST_INTERFACE_ID,
518
+ contractId: allocationRequestCid,
519
+ choice: "AllocationRequest_Withdraw",
520
+ choiceArgument: { extraArgs: {
521
+ context: { values: {} },
522
+ meta: { values: {} }
523
+ } }
524
+ }, []];
525
+ }
526
+ };
527
+ //#endregion
528
+ //#region src/core-service.ts
529
+ var CoreService = class CoreService {
530
+ constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
531
+ this.ledgerProvider = ledgerProvider;
532
+ this.logger = logger;
533
+ this.accessTokenProvider = accessTokenProvider;
534
+ this.isMasterUser = isMasterUser;
535
+ }
536
+ getTokenStandardClientWithVersion(registryUrl, version) {
537
+ if (!isApiVersion(version)) throw new Error(`Unsupported token standard api version.`);
538
+ return version === "v2" ? new _canton_network_core_token_standard_v2.TokenStandardClient(registryUrl.href, this.logger, this.accessTokenProvider) : new _canton_network_core_token_standard.TokenStandardClient(registryUrl.href, this.logger, this.accessTokenProvider);
539
+ }
540
+ getTokenStandardClient(registryUrl) {
541
+ return new _canton_network_core_token_standard.TokenStandardClient(registryUrl.href, this.logger, this.accessTokenProvider);
542
+ }
543
+ getTokenStandardClientV2(registryUrl) {
544
+ return new _canton_network_core_token_standard_v2.TokenStandardClient(registryUrl.href, this.logger, this.accessTokenProvider);
545
+ }
546
+ toBasicAccount(partyId) {
547
+ return {
548
+ owner: partyId,
549
+ provider: null,
550
+ id: ""
551
+ };
552
+ }
553
+ isSameAccount(a, b) {
554
+ return a.id === b.id && a.owner === b.owner && a.provider === b.provider;
555
+ }
556
+ async getInputHoldingCidsForAccount(opts) {
557
+ if (opts.inputUtxos?.length) return opts.inputUtxos;
558
+ const party = opts.partyId ?? opts.account.owner;
559
+ if (!party) throw new Error("No party to query as");
560
+ const now = /* @__PURE__ */ new Date();
561
+ const holdings = (await this.listContractsByInterface("#splice-api-token-holding-v2:Splice.Api.Token.HoldingV2:Holding", party, opts.limit, opts.offset, opts.continueUntilCompletion ?? false)).filter((h) => h.interfaceViewValue.instrumentId.admin === opts.instrumentAdmin && h.interfaceViewValue.instrumentId.id == opts.instrumentId && this.isSameAccount(opts.account, h.interfaceViewValue.account) && !TokenStandardService.isHoldingLocked(h, now));
562
+ return opts.amount ? CoreService.getInputHoldingsCidsForAmount(opts.amount, holdings) : holdings.map((h) => h.contractId);
563
+ }
564
+ async getInputHoldingsCids(options) {
565
+ const { sender, instrumentAdmin, instrumentId } = options;
566
+ const now = /* @__PURE__ */ new Date();
567
+ if (options.inputUtxos && options.inputUtxos.length > 0) return options.inputUtxos;
568
+ const senderHoldings = await this.listContractsByInterface(_canton_network_core_token_standard.HOLDING_INTERFACE_ID, sender, void 0, void 0, options.continueUntilCompletion);
569
+ if (senderHoldings.length === 0) throw new Error("Sender has no holdings, so transfer can't be executed.");
570
+ const unlockedSenderHoldings = senderHoldings.filter((utxo) => !TokenStandardService.isHoldingLocked(utxo, now));
571
+ if (unlockedSenderHoldings.length > 100) this.logger.warn(`Sender has more than 100 unlocked utxos.`);
572
+ const unlockedHoldingsForInstrument = instrumentAdmin && instrumentId ? await CoreService.filterHoldingsByInstrument({
573
+ holdings: unlockedSenderHoldings,
574
+ instrumentAdmin,
575
+ instrumentId
576
+ }) : unlockedSenderHoldings;
577
+ if (options.amount) return CoreService.getInputHoldingsCidsForAmount(options.amount, unlockedHoldingsForInstrument);
578
+ else return unlockedHoldingsForInstrument.map((h) => h.contractId);
579
+ }
580
+ static async filterHoldingsByInstrument(options) {
581
+ const { holdings, instrumentAdmin, instrumentId } = options;
582
+ return holdings.filter((utxo) => {
583
+ return utxo.interfaceViewValue.instrumentId.id === instrumentId && utxo.interfaceViewValue.instrumentId.admin === instrumentAdmin;
584
+ });
585
+ }
586
+ static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
587
+ const exactAmount = unlockedSenderHoldings.find((holding) => new decimal_js.Decimal(holding.interfaceViewValue.amount).equals(amount));
588
+ if (exactAmount) return [exactAmount.contractId];
589
+ const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted((a, b) => new decimal_js.Decimal(a.interfaceViewValue.amount).comparedTo(new decimal_js.Decimal(b.interfaceViewValue.amount)));
590
+ const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
591
+ if (!largestHoldingAmount) throw new Error(`Sender doesn't have any unlocked holdings`);
592
+ let currentSum = new decimal_js.Decimal(largestHoldingAmount.interfaceViewValue.amount);
593
+ const cIds = [largestHoldingAmount.contractId];
594
+ for (const h of sortedUnlockedSenderHoldings) {
595
+ if (currentSum.greaterThanOrEqualTo(amount)) break;
596
+ const currentHoldingAmount = new decimal_js.Decimal(h.interfaceViewValue.amount);
597
+ currentSum = currentSum.plus(currentHoldingAmount);
598
+ cIds.push(h.contractId);
599
+ }
600
+ if (currentSum.lessThan(amount)) throw new Error(`Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount.minus(currentSum)}`);
601
+ if (cIds.length > 100) throw new Error(`Exceeded the maximum of 100 utxos in 1 transaction`);
602
+ return cIds;
603
+ }
604
+ async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
605
+ try {
606
+ const ledgerEnd = offset ?? (await this.ledgerProvider.request({
607
+ method: "ledgerApi",
608
+ params: {
609
+ resource: "/v2/state/ledger-end",
610
+ requestMethod: "get",
611
+ query: {}
612
+ }
613
+ })).offset;
614
+ const options = {
615
+ offset: ledgerEnd,
616
+ interfaceIds: [interfaceId],
617
+ parties: [partyId],
618
+ filterByParty: true,
619
+ continueUntilCompletion: Boolean(continueUntilCompletion)
620
+ };
621
+ if (limit !== void 0) options.limit = limit;
622
+ this.logger.info(`continue to completion: ${Boolean(continueUntilCompletion)}`);
623
+ const acsResponses = await new _canton_network_core_acs_reader.ACSReader(this.ledgerProvider).raw.read(options);
624
+ const isActiveContractEntry = (acsResponse) => acsResponse.contractEntry != null && "JsActiveContract" in acsResponse.contractEntry && acsResponse.contractEntry.JsActiveContract != null && acsResponse.contractEntry.JsActiveContract.createdEvent != null;
625
+ return acsResponses.filter(isActiveContractEntry).map((response) => this.toPrettyContract(interfaceId, response, ledgerEnd));
626
+ } catch (err) {
627
+ this.logger.error(`Failed to list contracts of interface ${interfaceId}`, err);
628
+ throw err;
629
+ }
630
+ }
631
+ async toPrettyTransactions(updates, partyId) {
632
+ const isOffsetCheckpointUpdate = (updateResponse) => updateResponse.update != null && "OffsetCheckpoint" in updateResponse.update;
633
+ const isTransactionUpdate = (updateResponse) => updateResponse.update != null && "Transaction" in updateResponse.update && !!updateResponse.update.Transaction?.value;
634
+ const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map((update) => update.update.OffsetCheckpoint.value.offset);
635
+ const latestCheckpointOffset = offsetCheckpoints.length > 0 ? Math.max(...offsetCheckpoints) : 0;
636
+ const transactions = await Promise.all(updates.filter(isTransactionUpdate).map(async (update) => {
637
+ const tx = update.update.Transaction.value;
638
+ return await new _canton_network_core_tx_parser.TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
639
+ }));
640
+ const transactionOffsets = transactions.map((tx) => tx.offset).filter((offset) => offset !== void 0);
641
+ return {
642
+ nextOffset: Math.max(latestCheckpointOffset, ...transactionOffsets.length > 0 ? transactionOffsets : [0]),
643
+ transactions: transactions.filter((tx) => tx.events.length > 0).map(_canton_network_core_tx_parser.renderTransaction)
644
+ };
645
+ }
646
+ async toPrettyTransaction(getUpdateResponse, partyId) {
647
+ const tx = this.getTransactionFromUpdate(getUpdateResponse);
648
+ const parsedTx = await new _canton_network_core_tx_parser.TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
649
+ return (0, _canton_network_core_tx_parser.renderTransaction)(parsedTx);
650
+ }
651
+ async toPrettyTransferObjects(getUpdateResponse, partyId) {
652
+ const tx = this.getTransactionFromUpdate(getUpdateResponse);
653
+ return await new _canton_network_core_tx_parser.TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransferObjects();
654
+ }
655
+ getTransactionFromUpdate(getUpdateResponse) {
656
+ const update = getUpdateResponse.update;
657
+ if (!update || !("Transaction" in update)) throw new Error("Expected transaction update");
658
+ return update.Transaction.value;
659
+ }
660
+ async toPrettyTransactionsPerParty(updates, parties) {
661
+ const all = await Promise.all(parties.map(async (partyId) => [partyId, await this.toPrettyTransactions(updates, partyId)]));
662
+ return new Map(all);
663
+ }
664
+ toPrettyContract(interfaceId, response, offset) {
665
+ const activeContract = response.contractEntry.JsActiveContract;
666
+ const { createdEvent } = activeContract;
667
+ return {
668
+ contractId: createdEvent.contractId,
669
+ activeContract,
670
+ interfaceViewValue: (0, _canton_network_core_tx_parser.ensureInterfaceViewIsPresent)(createdEvent, interfaceId).viewValue,
671
+ fetchedAtOffset: offset
672
+ };
673
+ }
674
+ toQualifiedMemberId(memberId) {
675
+ if (!memberId) throw new Error("memberId is required");
676
+ return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
677
+ }
678
+ };
679
+ //#endregion
680
+ //#region src/v2/allocation-service.ts
681
+ const EMPTY_EXTRA_ARGS = () => ({
682
+ context: { values: {} },
683
+ meta: { values: {} }
684
+ });
685
+ var AllocationService = class AllocationService {
686
+ constructor(core, logger) {
687
+ this.core = core;
688
+ this.logger = logger;
689
+ }
690
+ static fundingNeeds(spec) {
691
+ const needs = /* @__PURE__ */ new Map();
692
+ const add = (id, d) => needs.set(id, (needs.get(id) ?? new decimal_js.default(0)).plus(d));
693
+ for (const leg of spec.transferLegSides) {
694
+ const amount = new decimal_js.default(leg.amount);
695
+ add(leg.instrumentId, leg.side === "SenderSide" ? amount : amount.negated());
696
+ }
697
+ for (const [id, amount] of Object.entries(spec.nextIterationFunding ?? {})) add(id, new decimal_js.default(amount));
698
+ for (const [id, amount] of needs) if (amount.lte(0)) needs.delete(id);
699
+ return needs;
700
+ }
701
+ async buildAllocateChoiceArgs(opts) {
702
+ const { spec, admin } = opts;
703
+ let inputHoldingCids = opts.inputUtxos ?? [];
704
+ if (!opts.inputUtxos?.length) {
705
+ const used = new Set(opts.excludeCids);
706
+ inputHoldingCids = [];
707
+ for (const [instrumentId, amount] of AllocationService.fundingNeeds(spec)) {
708
+ const cids = await this.core.getInputHoldingCidsForAccount({
709
+ account: spec.authorizer,
710
+ instrumentAdmin: admin,
711
+ instrumentId,
712
+ amount
713
+ });
714
+ cids.forEach((c) => used.add(c));
715
+ inputHoldingCids.push(...cids);
716
+ }
717
+ }
718
+ if (!spec.authorizer.owner && !opts.actors) throw new Error("Ownerless authorizer account: actors must be provided explicitly");
719
+ return {
720
+ settlement: opts.settlement,
721
+ allocation: opts.spec,
722
+ requestedAt: opts.requestedAt ?? (/* @__PURE__ */ new Date(Date.now() - 6e4)).toISOString(),
723
+ inputHoldingCids,
724
+ actors: opts.actors ?? [opts.spec.authorizer.owner],
725
+ extraArgs: EMPTY_EXTRA_ARGS()
726
+ };
727
+ }
728
+ async createAllocation(args, registryUrl, prefetched) {
729
+ const choiceArgs = await this.buildAllocateChoiceArgs(args);
730
+ const { factoryId, choiceContext } = prefetched ?? await this.core.getTokenStandardClientV2(registryUrl).post("/registry/allocation-instruction/v2/allocation-factory", {
731
+ choiceArguments: choiceArgs,
732
+ excludeDebugFields: true
733
+ });
734
+ return this.createAllocationFromContext(factoryId, choiceArgs, choiceContext);
735
+ }
736
+ async fetchAllocationChoiceContext(action, allocationCid, registryUrl) {
737
+ return this.core.getTokenStandardClientV2(registryUrl).post(`/registry/allocations/v2/{allocationId}/choice-contexts/${action}`, { excludeDebugFields: true }, { path: { allocationId: allocationCid } });
738
+ }
739
+ async createAllocationChoiceFromContext(action, allocationCid, actors, ctx) {
740
+ return [{
741
+ templateId: _canton_network_core_token_standard_v2.ALLOCATION_INTERFACE_ID_V2,
742
+ contractId: allocationCid,
743
+ choice: action === "withdraw" ? "Allocation_Withdraw" : "Allocation_Cancel",
744
+ choiceArgument: {
745
+ actors,
746
+ extraArgs: {
747
+ context: ctx.choiceContextData,
748
+ meta: { values: {} }
749
+ }
750
+ }
751
+ }, ctx.disclosedContracts ?? []];
752
+ }
753
+ async createAllocationChoice(action, allocationCid, actors, registryUrl, prefetched) {
754
+ const ctx = prefetched ?? await this.fetchAllocationChoiceContext(action, allocationCid, registryUrl);
755
+ return this.createAllocationChoiceFromContext(action, allocationCid, actors, ctx);
756
+ }
757
+ createAllocationRequestChoice(action, allocationRequestCid, actors) {
758
+ return [{
759
+ templateId: _canton_network_core_token_standard_v2.ALLOCATION_REQUEST_INTERFACE_ID_V2,
760
+ contractId: allocationRequestCid,
761
+ choice: action === "reject" ? "AllocationRequest_Reject" : "AllocationRequest_Withdraw",
762
+ choiceArgument: {
763
+ actors,
764
+ extraArgs: EMPTY_EXTRA_ARGS()
765
+ }
766
+ }, []];
767
+ }
768
+ createWithdrawAllocationInstruction(withdrawCid, actors) {
769
+ return [{
770
+ templateId: _canton_network_core_token_standard_v2.ALLOCATION_INSTRUCTION_INTERFACE_ID_V2,
771
+ contractId: withdrawCid,
772
+ choice: "AllocationInstruction_Withdraw",
773
+ choiceArgument: {
774
+ actors,
775
+ extraArgs: EMPTY_EXTRA_ARGS()
776
+ }
777
+ }, []];
778
+ }
779
+ async createAllocationFromContext(factoryId, choiceArgs, choiceContext) {
780
+ this.logger.debug("Creating transfer from pre-fetched context...");
781
+ choiceArgs.extraArgs.context = {
782
+ ...choiceContext.choiceContextData,
783
+ values: choiceContext.choiceContextData?.values ?? {}
784
+ };
785
+ return [{
786
+ templateId: _canton_network_core_token_standard_v2.ALLOCATION_FACTORY_INTERFACE_ID_V2,
787
+ contractId: factoryId,
788
+ choice: "AllocationFactory_Allocate",
789
+ choiceArgument: choiceArgs
790
+ }, choiceContext.disclosedContracts];
791
+ }
792
+ async fetchSettlementFactory(args, registryUrl) {
793
+ return this.core.getTokenStandardClientV2(registryUrl).post("/registry/allocation/v2/settlement-factory", {
794
+ choiceArguments: args,
795
+ excludeDebugFields: true
796
+ });
797
+ }
798
+ async createAllocationsForRequest(opts) {
799
+ const used = /* @__PURE__ */ new Set();
800
+ const results = [];
801
+ for (const spec of opts.request.allocations) {
802
+ const [cmd, dcs] = await this.createAllocation({
803
+ settlement: opts.request.settlement,
804
+ spec,
805
+ admin: spec.admin,
806
+ actors: opts.actors,
807
+ excludeCids: used
808
+ }, await opts.registry(spec.admin));
809
+ for (const cid of cmd.choiceArgument.inputHoldingCids) used.add(cid);
810
+ results.push([cmd, dcs]);
811
+ }
812
+ const acceptActors = opts.actors ?? [...new Set(opts.request.allocations.flatMap((s) => s.authorizer.owner ? [s.authorizer.owner] : []))].slice(0, 1);
813
+ if (acceptActors.length === 0) throw new Error(`Cannot accept allocation requests. No actors given and no authorizer has an owner`);
814
+ results.push([{
815
+ templateId: _canton_network_core_token_standard_v2.ALLOCATION_REQUEST_INTERFACE_ID_V2,
816
+ contractId: opts.requestCid,
817
+ choice: "AllocationRequest_Accept",
818
+ choiceArgument: {
819
+ actors: acceptActors,
820
+ extraArgs: EMPTY_EXTRA_ARGS()
821
+ }
822
+ }, []]);
823
+ const dcs = new Map(results.flatMap(([, d]) => d).filter((d) => d.contractId !== void 0).map((d) => [d.contractId, d]));
824
+ return [results.map(([c]) => c), [...dcs.values()]];
825
+ }
826
+ };
827
+ //#endregion
828
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/typeof.js
829
+ function _typeof(o) {
830
+ "@babel/helpers - typeof";
831
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
832
+ return typeof o;
833
+ } : function(o) {
834
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
835
+ }, _typeof(o);
836
+ }
837
+ //#endregion
838
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPrimitive.js
839
+ function toPrimitive(t, r) {
840
+ if ("object" != _typeof(t) || !t) return t;
841
+ var e = t[Symbol.toPrimitive];
842
+ if (void 0 !== e) {
843
+ var i = e.call(t, r || "default");
844
+ if ("object" != _typeof(i)) return i;
845
+ throw new TypeError("@@toPrimitive must return a primitive value.");
846
+ }
847
+ return ("string" === r ? String : Number)(t);
848
+ }
849
+ //#endregion
850
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/toPropertyKey.js
851
+ function toPropertyKey(t) {
852
+ var i = toPrimitive(t, "string");
853
+ return "symbol" == _typeof(i) ? i : i + "";
854
+ }
855
+ //#endregion
856
+ //#region \0@oxc-project+runtime@0.153.0/helpers/esm/defineProperty.js
857
+ function _defineProperty(e, r, t) {
858
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
859
+ value: t,
860
+ enumerable: !0,
861
+ configurable: !0,
862
+ writable: !0
863
+ }) : e[r] = t, e;
864
+ }
865
+ //#endregion
866
+ //#region src/token-standard-service.ts
867
+ function isApiVersion(v) {
868
+ return SUPPORTED_VERSIONS.includes(v);
869
+ }
870
+ function resolveCapabilities(opts) {
871
+ const supportedApis = opts.supportedApis;
872
+ const resolvedCapabilities = {
873
+ holding: [],
874
+ transferInstruction: [],
875
+ allocation: [],
876
+ allocationInstruction: [],
877
+ allocationRequest: []
878
+ };
879
+ for (const key of Object.keys(supportedApis)) {
880
+ const match = key.match(/^splice-api-token-(?<capabilityName>.+)-(?<version>v\d+)$/);
881
+ if (match?.groups) {
882
+ const { capabilityName, version } = match.groups;
883
+ const targetKey = KEY_MAPPING[capabilityName];
884
+ if (targetKey && supportedApis[key] === 1 && isApiVersion(version)) resolvedCapabilities[targetKey].push(version);
885
+ }
886
+ }
887
+ for (const key in resolvedCapabilities) resolvedCapabilities[key].sort();
888
+ return resolvedCapabilities;
889
+ }
578
890
  var TokenStandardService = class {
579
891
  constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
580
892
  this.ledgerProvider = ledgerProvider;
@@ -584,9 +896,14 @@ var TokenStandardService = class {
584
896
  _defineProperty(this, "core", void 0);
585
897
  _defineProperty(this, "allocation", void 0);
586
898
  _defineProperty(this, "transfer", void 0);
899
+ _defineProperty(this, "v2", void 0);
587
900
  this.core = new CoreService(ledgerProvider, logger, accessTokenProvider, isMasterUser);
588
- this.allocation = new AllocationService(this.core, this.logger);
901
+ this.allocation = new AllocationService$1(this.core, this.logger);
589
902
  this.transfer = new TransferService(this.core, this.logger);
903
+ this.v2 = {
904
+ transfer: new TransferServiceV2(this.core, this.logger),
905
+ allocation: new AllocationService(this.core, this.logger)
906
+ };
590
907
  }
591
908
  async resolveCapabilitiesFromRegistryByInstrumentId(registryUrl, instrumentId) {
592
909
  return resolveCapabilities({ supportedApis: (await this.getInstrumentById(registryUrl, instrumentId)).supportedApis });
@@ -798,8 +1115,12 @@ var TokenStandardService = class {
798
1115
  };
799
1116
  _defineProperty(TokenStandardService, "MEMO_KEY", "splice.lfdecentralizedtrust.org/reason");
800
1117
  //#endregion
801
- exports.CoreService = CoreService;
1118
+ exports.EMPTY_META = EMPTY_META;
1119
+ exports.KEY_MAPPING = KEY_MAPPING;
1120
+ exports.REQUESTED_AT_SKEW_MS = REQUESTED_AT_SKEW_MS;
1121
+ exports.SUPPORTED_VERSIONS = SUPPORTED_VERSIONS;
802
1122
  exports.TokenStandardService = TokenStandardService;
1123
+ exports.isApiVersion = isApiVersion;
803
1124
  exports.resolveCapabilities = resolveCapabilities;
804
1125
 
805
1126
  //# sourceMappingURL=index.cjs.map