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