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