@canton-network/core-token-standard-service 1.13.0 → 1.14.0

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