@canton-network/core-token-standard-service 1.12.3 → 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,382 +1,207 @@
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.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
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
- var CoreService = class CoreService {
49
- constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
50
- this.ledgerProvider = ledgerProvider;
34
+ const SUPPORTED_VERSIONS = ["v1", "v2"];
35
+ const KEY_MAPPING = {
36
+ holding: "holding",
37
+ "transfer-instruction": "transferInstruction",
38
+ allocation: "allocation",
39
+ "allocation-instruction": "allocationInstruction",
40
+ "allocation-request": "allocationRequest"
41
+ };
42
+ //#endregion
43
+ //#region src/v2/transfer-service.ts
44
+ var TransferServiceV2 = class {
45
+ constructor(core, logger) {
46
+ this.core = core;
51
47
  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) => !TokenStandardService.isHoldingLocked(utxo, now));
65
- if (unlockedSenderHoldings.length > 100) this.logger.warn(`Sender has more than 100 unlocked utxos.`);
66
- const unlockedHoldingsForInstrument = instrumentAdmin && instrumentId ? await CoreService.filterHoldingsByInstrument({
67
- holdings: unlockedSenderHoldings,
68
- instrumentAdmin,
69
- instrumentId
70
- }) : unlockedSenderHoldings;
71
- if (options.amount) return CoreService.getInputHoldingsCidsForAmount(options.amount, unlockedHoldingsForInstrument);
72
- else return unlockedHoldingsForInstrument.map((h) => h.contractId);
73
48
  }
74
- static async filterHoldingsByInstrument(options) {
75
- const { holdings, instrumentAdmin, instrumentId } = options;
76
- return holdings.filter((utxo) => {
77
- return utxo.interfaceViewValue.instrumentId.id === instrumentId && utxo.interfaceViewValue.instrumentId.admin === instrumentAdmin;
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
78
57
  });
79
- }
80
- static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
81
- const exactAmount = unlockedSenderHoldings.find((holding) => new decimal_js.Decimal(holding.interfaceViewValue.amount).equals(amount));
82
- if (exactAmount) return [exactAmount.contractId];
83
- const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted((a, b) => new decimal_js.Decimal(a.interfaceViewValue.amount).comparedTo(new decimal_js.Decimal(b.interfaceViewValue.amount)));
84
- const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
85
- if (!largestHoldingAmount) throw new Error(`Sender doesn't have any unlocked holdings`);
86
- let currentSum = new decimal_js.Decimal(largestHoldingAmount.interfaceViewValue.amount);
87
- const cIds = [largestHoldingAmount.contractId];
88
- for (const h of sortedUnlockedSenderHoldings) {
89
- if (currentSum.greaterThanOrEqualTo(amount)) break;
90
- const currentHoldingAmount = new decimal_js.Decimal(h.interfaceViewValue.amount);
91
- currentSum = currentSum.plus(currentHoldingAmount);
92
- cIds.push(h.contractId);
93
- }
94
- if (currentSum.lessThan(amount)) throw new Error(`Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount.minus(currentSum)}`);
95
- if (cIds.length > 100) throw new Error(`Exceeded the maximum of 100 utxos in 1 transaction`);
96
- return cIds;
97
- }
98
- async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
99
- try {
100
- const ledgerEnd = offset ?? (await this.ledgerProvider.request({
101
- method: "ledgerApi",
102
- params: {
103
- resource: "/v2/state/ledger-end",
104
- requestMethod: "get",
105
- query: {}
106
- }
107
- })).offset;
108
- const options = {
109
- offset: ledgerEnd,
110
- interfaceIds: [interfaceId],
111
- parties: [partyId],
112
- filterByParty: true,
113
- continueUntilCompletion: Boolean(continueUntilCompletion)
114
- };
115
- if (limit !== void 0) options.limit = limit;
116
- this.logger.info(`continue to completion: ${Boolean(continueUntilCompletion)}`);
117
- const acsResponses = await new _canton_network_core_acs_reader.ACSReader(this.ledgerProvider).raw.read(options);
118
- const isActiveContractEntry = (acsResponse) => acsResponse.contractEntry != null && "JsActiveContract" in acsResponse.contractEntry && acsResponse.contractEntry.JsActiveContract != null && acsResponse.contractEntry.JsActiveContract.createdEvent != null;
119
- return acsResponses.filter(isActiveContractEntry).map((response) => this.toPrettyContract(interfaceId, response, ledgerEnd));
120
- } catch (err) {
121
- this.logger.error(`Failed to list contracts of interface ${interfaceId}`, err);
122
- throw err;
123
- }
124
- }
125
- async toPrettyTransactions(updates, partyId) {
126
- const isOffsetCheckpointUpdate = (updateResponse) => updateResponse.update != null && "OffsetCheckpoint" in updateResponse.update;
127
- const isTransactionUpdate = (updateResponse) => updateResponse.update != null && "Transaction" in updateResponse.update && !!updateResponse.update.Transaction?.value;
128
- const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map((update) => update.update.OffsetCheckpoint.value.offset);
129
- const latestCheckpointOffset = offsetCheckpoints.length > 0 ? Math.max(...offsetCheckpoints) : 0;
130
- const transactions = await Promise.all(updates.filter(isTransactionUpdate).map(async (update) => {
131
- const tx = update.update.Transaction.value;
132
- return await new _canton_network_core_tx_parser.TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
133
- }));
134
- const transactionOffsets = transactions.map((tx) => tx.offset).filter((offset) => offset !== void 0);
135
58
  return {
136
- nextOffset: Math.max(latestCheckpointOffset, ...transactionOffsets.length > 0 ? transactionOffsets : [0]),
137
- transactions: transactions.filter((tx) => tx.events.length > 0).map(_canton_network_core_tx_parser.renderTransaction)
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
+ },
76
+ extraArgs: {
77
+ context: { values: {} },
78
+ meta: { values: {} }
79
+ }
138
80
  };
139
81
  }
140
- async toPrettyTransaction(getUpdateResponse, partyId) {
141
- const tx = this.getTransactionFromUpdate(getUpdateResponse);
142
- const parsedTx = await new _canton_network_core_tx_parser.TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
143
- return (0, _canton_network_core_tx_parser.renderTransaction)(parsedTx);
144
- }
145
- async toPrettyTransferObjects(getUpdateResponse, partyId) {
146
- const tx = this.getTransactionFromUpdate(getUpdateResponse);
147
- return await new _canton_network_core_tx_parser.TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransferObjects();
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", {
85
+ choiceArguments: choiceArgs,
86
+ excludeDebugFields: true
87
+ });
88
+ return this.createTransferFromContext(factoryId, choiceArgs, choiceContext);
148
89
  }
149
- getTransactionFromUpdate(getUpdateResponse) {
150
- const update = getUpdateResponse.update;
151
- if (!update || !("Transaction" in update)) throw new Error("Expected transaction update");
152
- return update.Transaction.value;
90
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
91
+ this.logger.debug("Creating transfer from pre-fetched context...");
92
+ choiceArgs.extraArgs.context = {
93
+ ...choiceContext.choiceContextData,
94
+ values: choiceContext.choiceContextData?.values ?? {}
95
+ };
96
+ return [{
97
+ templateId: _canton_network_core_token_standard_v2.TRANSFER_FACTORY_INTERFACE_ID_V2,
98
+ contractId: factoryId,
99
+ choice: "TransferFactory_Transfer",
100
+ choiceArgument: choiceArgs
101
+ }, choiceContext.disclosedContracts];
153
102
  }
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);
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 ?? []];
157
117
  }
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
- };
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 } });
120
+ return [{
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 ?? []];
167
132
  }
168
- toQualifiedMemberId(memberId) {
169
- if (!memberId) throw new Error("memberId is required");
170
- return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
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 ?? []];
171
147
  }
172
148
  };
173
- var AllocationService = class {
149
+ //#endregion
150
+ //#region src/v1/transfer-service.ts
151
+ var TransferService = class {
174
152
  constructor(core, logger) {
175
153
  this.core = core;
176
154
  this.logger = logger;
177
155
  }
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
- };
156
+ async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion) {
190
157
  const inputHoldingCids = await this.core.getInputHoldingsCids({
191
- sender: allocationSpecificationNormalized.transferLeg.sender,
158
+ sender,
159
+ instrumentAdmin,
160
+ instrumentId,
192
161
  inputUtxos: inputUtxos ?? [],
193
- instrumentAdmin: allocationSpecificationNormalized.transferLeg.instrumentId.admin,
194
- instrumentId: allocationSpecificationNormalized.transferLeg.instrumentId.id
162
+ amount: new decimal_js.Decimal(amount),
163
+ continueUntilCompletion: continueUntilCompletion ?? false
195
164
  });
196
165
  return {
197
- expectedAdmin,
198
- allocation: allocationSpecificationNormalized,
199
- requestedAt: requestedAt ?? (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
200
- inputHoldingCids,
166
+ expectedAdmin: instrumentAdmin,
167
+ transfer: {
168
+ sender,
169
+ receiver,
170
+ amount,
171
+ instrumentId: {
172
+ admin: instrumentAdmin,
173
+ id: instrumentId
174
+ },
175
+ requestedAt: (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
176
+ executeBefore: (expiryDate ?? new Date(Date.now() + 864e5)).toISOString(),
177
+ inputHoldingCids,
178
+ meta: { values: {
179
+ [TokenStandardService.MEMO_KEY]: memo || "",
180
+ ...meta?.values
181
+ } }
182
+ },
201
183
  extraArgs: {
202
184
  context: { values: {} },
203
185
  meta: { values: {} }
204
186
  }
205
187
  };
206
188
  }
207
- async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
208
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocation-instruction/v1/allocation-factory", {
189
+ async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
190
+ return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
209
191
  choiceArguments: choiceArgs,
210
192
  excludeDebugFields
211
193
  });
212
194
  }
213
- async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
195
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
196
+ this.logger.debug("Creating transfer from pre-fetched context...");
214
197
  choiceArgs.extraArgs.context = {
215
198
  ...choiceContext.choiceContextData,
216
199
  values: choiceContext.choiceContextData?.values ?? {}
217
200
  };
218
201
  return [{
219
- templateId: _canton_network_core_token_standard.ALLOCATION_FACTORY_INTERFACE_ID,
202
+ templateId: _canton_network_core_token_standard.TRANSFER_FACTORY_INTERFACE_ID,
220
203
  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
- }
325
- };
326
- var TransferService = class {
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",
204
+ choice: "TransferFactory_Transfer",
380
205
  choiceArgument: choiceArgs
381
206
  }, choiceContext.disclosedContracts];
382
207
  }
@@ -403,7 +228,7 @@ var TransferService = class {
403
228
  return [{
404
229
  templateId: _canton_network_core_token_standard.TRANSFER_INSTRUCTION_INTERFACE_ID,
405
230
  contractId: transferInstructionCid,
406
- choice: "TransferInstruction_Accept",
231
+ choice: _canton_network_core_token_standard.TransferInstruction.TransferInstruction_Accept.choiceName,
407
232
  choiceArgument: { extraArgs: {
408
233
  context: choiceContext.choiceContextData,
409
234
  meta: { values: {} }
@@ -415,7 +240,7 @@ var TransferService = class {
415
240
  }
416
241
  }
417
242
  async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
418
- const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(transferInstructionCid, registryUrl.href);
243
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(transferInstructionCid, registryUrl);
419
244
  const choiceArgs = {
420
245
  cid: acceptTransferInstructionContext.contractId,
421
246
  proxyArg: {
@@ -432,7 +257,7 @@ var TransferService = class {
432
257
  }, disclosedContracts];
433
258
  }
434
259
  async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
435
- const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(transferInstructionCid, registryUrl.href);
260
+ const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(transferInstructionCid, registryUrl);
436
261
  const choiceArgs = {
437
262
  cid: rejectTransferInstructionContext.contractId,
438
263
  proxyArg: {
@@ -449,7 +274,7 @@ var TransferService = class {
449
274
  }, disclosedContracts];
450
275
  }
451
276
  async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
452
- const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl.href);
277
+ const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl);
453
278
  if (beneficiaries.reduce((totalWeight, beneficiary) => totalWeight + beneficiary.weight, 0) > 1) throw new Error("Sum of beneficiary weights is larger than 1.");
454
279
  const choiceArgs = {
455
280
  cid: withdrawTransferInstructionContext.contractId,
@@ -486,7 +311,7 @@ var TransferService = class {
486
311
  return [{
487
312
  templateId: _canton_network_core_token_standard.TRANSFER_INSTRUCTION_INTERFACE_ID,
488
313
  contractId: transferInstructionCid,
489
- choice: "TransferInstruction_Reject",
314
+ choice: _canton_network_core_token_standard.TransferInstruction.TransferInstruction_Reject.choiceName,
490
315
  choiceArgument: { extraArgs: {
491
316
  context: choiceContext.choiceContextData,
492
317
  meta: { values: {} }
@@ -517,7 +342,7 @@ var TransferService = class {
517
342
  return [{
518
343
  templateId: _canton_network_core_token_standard.TRANSFER_INSTRUCTION_INTERFACE_ID,
519
344
  contractId: transferInstructionCid,
520
- choice: "TransferInstruction_Withdraw",
345
+ choice: _canton_network_core_token_standard.TransferInstruction.TransferInstruction_Withdraw.choiceName,
521
346
  choiceArgument: { extraArgs: {
522
347
  context: choiceContext.choiceContextData,
523
348
  meta: { values: {} }
@@ -544,23 +369,549 @@ var TransferService = class {
544
369
  }
545
370
  }
546
371
  };
547
- var TokenStandardService = class {
548
- constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
549
- this.ledgerProvider = ledgerProvider;
372
+ //#endregion
373
+ //#region src/v1/allocation-service.ts
374
+ var AllocationService$1 = class {
375
+ constructor(core, logger) {
376
+ this.core = core;
550
377
  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);
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
+ }
890
+ var TokenStandardService = class {
891
+ constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
892
+ this.ledgerProvider = ledgerProvider;
893
+ this.logger = logger;
894
+ this.accessTokenProvider = accessTokenProvider;
895
+ this.isMasterUser = isMasterUser;
896
+ _defineProperty(this, "core", void 0);
897
+ _defineProperty(this, "allocation", void 0);
898
+ _defineProperty(this, "transfer", void 0);
899
+ _defineProperty(this, "v2", void 0);
900
+ this.core = new CoreService(ledgerProvider, logger, accessTokenProvider, isMasterUser);
901
+ this.allocation = new AllocationService$1(this.core, this.logger);
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
+ };
907
+ }
908
+ async resolveCapabilitiesFromRegistryByInstrumentId(registryUrl, instrumentId) {
909
+ return resolveCapabilities({ supportedApis: (await this.getInstrumentById(registryUrl, instrumentId)).supportedApis });
559
910
  }
560
911
  async getInstrumentById(registryUrl, instrumentId) {
561
912
  try {
562
913
  const params = { path: { instrumentId } };
563
- return this.core.getTokenStandardClient(registryUrl).get("/registry/metadata/v1/instruments/{instrumentId}", params);
914
+ return await this.core.getTokenStandardClient(registryUrl).get("/registry/metadata/v1/instruments/{instrumentId}", params);
564
915
  } catch (e) {
565
916
  this.logger.error(e);
566
917
  throw new Error(`Instrument id ${instrumentId} does not exist for this instrument admin.`, { cause: e });
@@ -588,7 +939,8 @@ var TokenStandardService = class {
588
939
  displayName: instrument.name,
589
940
  symbol: instrument.symbol,
590
941
  registryUrl,
591
- admin: instrumentAdmin
942
+ admin: instrumentAdmin,
943
+ capabilities: resolveCapabilities({ supportedApis: instrument.supportedApis })
592
944
  }));
593
945
  }
594
946
  async registriesToAssets(registryUrls) {
@@ -763,7 +1115,12 @@ var TokenStandardService = class {
763
1115
  };
764
1116
  _defineProperty(TokenStandardService, "MEMO_KEY", "splice.lfdecentralizedtrust.org/reason");
765
1117
  //#endregion
766
- 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;
767
1122
  exports.TokenStandardService = TokenStandardService;
1123
+ exports.isApiVersion = isApiVersion;
1124
+ exports.resolveCapabilities = resolveCapabilities;
768
1125
 
769
1126
  //# sourceMappingURL=index.cjs.map