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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,381 +1,183 @@
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.142.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.142.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.142.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.142.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
- var CoreService = class CoreService {
48
- constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
49
- this.ledgerProvider = ledgerProvider;
10
+ const SUPPORTED_VERSIONS = ["v1", "v2"];
11
+ const KEY_MAPPING = {
12
+ holding: "holding",
13
+ "transfer-instruction": "transferInstruction",
14
+ allocation: "allocation",
15
+ "allocation-instruction": "allocationInstruction",
16
+ "allocation-request": "allocationRequest"
17
+ };
18
+ //#endregion
19
+ //#region src/v2/transfer-service.ts
20
+ var TransferServiceV2 = class {
21
+ constructor(core, logger) {
22
+ this.core = core;
50
23
  this.logger = logger;
51
- this.accessTokenProvider = accessTokenProvider;
52
- this.isMasterUser = isMasterUser;
53
- }
54
- getTokenStandardClient(registryUrl) {
55
- return new TokenStandardClient(registryUrl, this.logger, this.accessTokenProvider);
56
- }
57
- async getInputHoldingsCids(options) {
58
- const { sender, instrumentAdmin, instrumentId } = options;
59
- const now = /* @__PURE__ */ new Date();
60
- if (options.inputUtxos && options.inputUtxos.length > 0) return options.inputUtxos;
61
- const senderHoldings = await this.listContractsByInterface(HOLDING_INTERFACE_ID, sender, void 0, void 0, options.continueUntilCompletion);
62
- if (senderHoldings.length === 0) throw new Error("Sender has no holdings, so transfer can't be executed.");
63
- const unlockedSenderHoldings = senderHoldings.filter((utxo) => !TokenStandardService.isHoldingLocked(utxo, now));
64
- if (unlockedSenderHoldings.length > 100) this.logger.warn(`Sender has more than 100 unlocked utxos.`);
65
- const unlockedHoldingsForInstrument = instrumentAdmin && instrumentId ? await CoreService.filterHoldingsByInstrument({
66
- holdings: unlockedSenderHoldings,
67
- instrumentAdmin,
68
- instrumentId
69
- }) : unlockedSenderHoldings;
70
- if (options.amount) return CoreService.getInputHoldingsCidsForAmount(options.amount, unlockedHoldingsForInstrument);
71
- else return unlockedHoldingsForInstrument.map((h) => h.contractId);
72
24
  }
73
- static async filterHoldingsByInstrument(options) {
74
- const { holdings, instrumentAdmin, instrumentId } = options;
75
- return holdings.filter((utxo) => {
76
- return utxo.interfaceViewValue.instrumentId.id === instrumentId && utxo.interfaceViewValue.instrumentId.admin === instrumentAdmin;
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
77
33
  });
78
- }
79
- static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
80
- const exactAmount = unlockedSenderHoldings.find((holding) => new Decimal(holding.interfaceViewValue.amount).equals(amount));
81
- if (exactAmount) return [exactAmount.contractId];
82
- const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted((a, b) => new Decimal(a.interfaceViewValue.amount).comparedTo(new Decimal(b.interfaceViewValue.amount)));
83
- const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
84
- if (!largestHoldingAmount) throw new Error(`Sender doesn't have any unlocked holdings`);
85
- let currentSum = new Decimal(largestHoldingAmount.interfaceViewValue.amount);
86
- const cIds = [largestHoldingAmount.contractId];
87
- for (const h of sortedUnlockedSenderHoldings) {
88
- if (currentSum.greaterThanOrEqualTo(amount)) break;
89
- const currentHoldingAmount = new Decimal(h.interfaceViewValue.amount);
90
- currentSum = currentSum.plus(currentHoldingAmount);
91
- cIds.push(h.contractId);
92
- }
93
- if (currentSum.lessThan(amount)) throw new Error(`Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount.minus(currentSum)}`);
94
- if (cIds.length > 100) throw new Error(`Exceeded the maximum of 100 utxos in 1 transaction`);
95
- return cIds;
96
- }
97
- async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
98
- try {
99
- const ledgerEnd = offset ?? (await this.ledgerProvider.request({
100
- method: "ledgerApi",
101
- params: {
102
- resource: "/v2/state/ledger-end",
103
- requestMethod: "get",
104
- query: {}
105
- }
106
- })).offset;
107
- const options = {
108
- offset: ledgerEnd,
109
- interfaceIds: [interfaceId],
110
- parties: [partyId],
111
- filterByParty: true,
112
- continueUntilCompletion: Boolean(continueUntilCompletion)
113
- };
114
- if (limit !== void 0) options.limit = limit;
115
- this.logger.info(`continue to completion: ${Boolean(continueUntilCompletion)}`);
116
- const acsResponses = await new ACSReader(this.ledgerProvider).raw.read(options);
117
- const isActiveContractEntry = (acsResponse) => acsResponse.contractEntry != null && "JsActiveContract" in acsResponse.contractEntry && acsResponse.contractEntry.JsActiveContract != null && acsResponse.contractEntry.JsActiveContract.createdEvent != null;
118
- return acsResponses.filter(isActiveContractEntry).map((response) => this.toPrettyContract(interfaceId, response, ledgerEnd));
119
- } catch (err) {
120
- this.logger.error(`Failed to list contracts of interface ${interfaceId}`, err);
121
- throw err;
122
- }
123
- }
124
- async toPrettyTransactions(updates, partyId) {
125
- const isOffsetCheckpointUpdate = (updateResponse) => updateResponse.update != null && "OffsetCheckpoint" in updateResponse.update;
126
- const isTransactionUpdate = (updateResponse) => updateResponse.update != null && "Transaction" in updateResponse.update && !!updateResponse.update.Transaction?.value;
127
- const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map((update) => update.update.OffsetCheckpoint.value.offset);
128
- const latestCheckpointOffset = offsetCheckpoints.length > 0 ? Math.max(...offsetCheckpoints) : 0;
129
- const transactions = await Promise.all(updates.filter(isTransactionUpdate).map(async (update) => {
130
- const tx = update.update.Transaction.value;
131
- return await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
132
- }));
133
- const transactionOffsets = transactions.map((tx) => tx.offset).filter((offset) => offset !== void 0);
134
34
  return {
135
- nextOffset: Math.max(latestCheckpointOffset, ...transactionOffsets.length > 0 ? transactionOffsets : [0]),
136
- transactions: transactions.filter((tx) => tx.events.length > 0).map(renderTransaction)
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
+ },
52
+ extraArgs: {
53
+ context: { values: {} },
54
+ meta: { values: {} }
55
+ }
137
56
  };
138
57
  }
139
- async toPrettyTransaction(getUpdateResponse, partyId) {
140
- const tx = this.getTransactionFromUpdate(getUpdateResponse);
141
- const parsedTx = await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
142
- return renderTransaction(parsedTx);
143
- }
144
- async toPrettyTransferObjects(getUpdateResponse, partyId) {
145
- const tx = this.getTransactionFromUpdate(getUpdateResponse);
146
- return await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransferObjects();
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", {
61
+ choiceArguments: choiceArgs,
62
+ excludeDebugFields: true
63
+ });
64
+ return this.createTransferFromContext(factoryId, choiceArgs, choiceContext);
147
65
  }
148
- getTransactionFromUpdate(getUpdateResponse) {
149
- const update = getUpdateResponse.update;
150
- if (!update || !("Transaction" in update)) throw new Error("Expected transaction update");
151
- return update.Transaction.value;
66
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
67
+ this.logger.debug("Creating transfer from pre-fetched context...");
68
+ choiceArgs.extraArgs.context = {
69
+ ...choiceContext.choiceContextData,
70
+ values: choiceContext.choiceContextData?.values ?? {}
71
+ };
72
+ return [{
73
+ templateId: TRANSFER_FACTORY_INTERFACE_ID_V2,
74
+ contractId: factoryId,
75
+ choice: "TransferFactory_Transfer",
76
+ choiceArgument: choiceArgs
77
+ }, choiceContext.disclosedContracts];
152
78
  }
153
- async toPrettyTransactionsPerParty(updates, parties) {
154
- const all = await Promise.all(parties.map(async (partyId) => [partyId, await this.toPrettyTransactions(updates, partyId)]));
155
- return new Map(all);
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 } });
81
+ return [{
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 ?? []];
156
93
  }
157
- toPrettyContract(interfaceId, response, offset) {
158
- const activeContract = response.contractEntry.JsActiveContract;
159
- const { createdEvent } = activeContract;
160
- return {
161
- contractId: createdEvent.contractId,
162
- activeContract,
163
- interfaceViewValue: ensureInterfaceViewIsPresent(createdEvent, interfaceId).viewValue,
164
- fetchedAtOffset: offset
165
- };
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 ?? []];
166
108
  }
167
- toQualifiedMemberId(memberId) {
168
- if (!memberId) throw new Error("memberId is required");
169
- return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
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 ?? []];
170
123
  }
171
124
  };
172
- var AllocationService = class {
125
+ //#endregion
126
+ //#region src/v1/transfer-service.ts
127
+ var TransferService = class {
173
128
  constructor(core, logger) {
174
129
  this.core = core;
175
130
  this.logger = logger;
176
131
  }
177
- async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
178
- const allocationSpecificationNormalized = {
179
- ...allocationSpecification,
180
- settlement: {
181
- ...allocationSpecification.settlement,
182
- meta: allocationSpecification.settlement.meta ?? { values: {} }
183
- },
184
- transferLeg: {
185
- ...allocationSpecification.transferLeg,
186
- meta: allocationSpecification.transferLeg.meta ?? { values: {} }
187
- }
188
- };
132
+ async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion) {
189
133
  const inputHoldingCids = await this.core.getInputHoldingsCids({
190
- sender: allocationSpecificationNormalized.transferLeg.sender,
134
+ sender,
135
+ instrumentAdmin,
136
+ instrumentId,
191
137
  inputUtxos: inputUtxos ?? [],
192
- instrumentAdmin: allocationSpecificationNormalized.transferLeg.instrumentId.admin,
193
- instrumentId: allocationSpecificationNormalized.transferLeg.instrumentId.id
138
+ amount: new Decimal(amount),
139
+ continueUntilCompletion: continueUntilCompletion ?? false
194
140
  });
195
141
  return {
196
- expectedAdmin,
197
- allocation: allocationSpecificationNormalized,
198
- requestedAt: requestedAt ?? (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
199
- inputHoldingCids,
142
+ expectedAdmin: instrumentAdmin,
143
+ transfer: {
144
+ sender,
145
+ receiver,
146
+ amount,
147
+ instrumentId: {
148
+ admin: instrumentAdmin,
149
+ id: instrumentId
150
+ },
151
+ requestedAt: (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
152
+ executeBefore: (expiryDate ?? new Date(Date.now() + 864e5)).toISOString(),
153
+ inputHoldingCids,
154
+ meta: { values: {
155
+ [TokenStandardService.MEMO_KEY]: memo || "",
156
+ ...meta?.values
157
+ } }
158
+ },
200
159
  extraArgs: {
201
160
  context: { values: {} },
202
161
  meta: { values: {} }
203
162
  }
204
163
  };
205
164
  }
206
- async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
207
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocation-instruction/v1/allocation-factory", {
165
+ async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
166
+ return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
208
167
  choiceArguments: choiceArgs,
209
168
  excludeDebugFields
210
169
  });
211
170
  }
212
- async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
171
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
172
+ this.logger.debug("Creating transfer from pre-fetched context...");
213
173
  choiceArgs.extraArgs.context = {
214
174
  ...choiceContext.choiceContextData,
215
175
  values: choiceContext.choiceContextData?.values ?? {}
216
176
  };
217
177
  return [{
218
- templateId: ALLOCATION_FACTORY_INTERFACE_ID,
178
+ templateId: TRANSFER_FACTORY_INTERFACE_ID,
219
179
  contractId: factoryId,
220
- choice: "AllocationFactory_Allocate",
221
- choiceArgument: choiceArgs
222
- }, choiceContext.disclosedContracts];
223
- }
224
- async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
225
- const choiceArgs = await this.buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt);
226
- if (prefetchedRegistryChoiceContext) return this.createAllocationInstructionFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
227
- const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs);
228
- return this.createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext);
229
- }
230
- buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
231
- return [{
232
- templateId,
233
- contractId,
234
- choice,
235
- choiceArgument: { extraArgs: {
236
- context: choiceContext.choiceContextData,
237
- meta: EMPTY_META
238
- } }
239
- }, choiceContext.disclosedContracts ?? []];
240
- }
241
- async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
242
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer", { excludeDebugFields: true }, { path: { allocationId } });
243
- }
244
- createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
245
- return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_ExecuteTransfer", choiceContext);
246
- }
247
- async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
248
- if (prefetchedRegistryChoiceContext) return this.createExecuteTransferAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
249
- const choiceContext = await this.fetchExecuteTransferChoiceContext(allocationCid, registryUrl);
250
- return this.createExecuteTransferAllocationFromContext(allocationCid, choiceContext);
251
- }
252
- async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
253
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/withdraw", { excludeDebugFields: true }, { path: { allocationId: allocationCid } });
254
- }
255
- createWithdrawAllocationFromContext(allocationCid, choiceContext) {
256
- return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_Withdraw", choiceContext);
257
- }
258
- async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
259
- if (prefetchedRegistryChoiceContext) return this.createWithdrawAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
260
- const choiceContext = await this.fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl);
261
- return this.createWithdrawAllocationFromContext(allocationCid, choiceContext);
262
- }
263
- async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
264
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/cancel", { excludeDebugFields: true }, { path: { allocationId: allocationCid } });
265
- }
266
- createCancelAllocationFromContext(allocationCid, choiceContext) {
267
- return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_Cancel", choiceContext);
268
- }
269
- async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
270
- if (prefetchedRegistryChoiceContext) return this.createCancelAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
271
- const choiceContext = await this.fetchCancelAllocationChoiceContext(allocationCid, registryUrl);
272
- return this.createCancelAllocationFromContext(allocationCid, choiceContext);
273
- }
274
- async createWithdrawAllocationInstruction(allocationInstructionCid) {
275
- return [{
276
- templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
277
- contractId: allocationInstructionCid,
278
- choice: "AllocationInstruction_Withdraw",
279
- choiceArgument: { extraArgs: {
280
- context: { values: {} },
281
- meta: { values: {} }
282
- } }
283
- }, []];
284
- }
285
- async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
286
- return [{
287
- templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
288
- contractId: allocationInstructionCid,
289
- choice: "AllocationInstruction_Update",
290
- choiceArgument: {
291
- extraActors,
292
- extraArgs: {
293
- context: { values: extraArgsContext },
294
- meta: { values: extraArgsMeta }
295
- }
296
- }
297
- }, []];
298
- }
299
- async createRejectAllocationRequest(allocationRequestCid, actor) {
300
- return [{
301
- templateId: ALLOCATION_REQUEST_INTERFACE_ID,
302
- contractId: allocationRequestCid,
303
- choice: "AllocationRequest_Reject",
304
- choiceArgument: {
305
- actor,
306
- extraArgs: {
307
- context: { values: {} },
308
- meta: { values: {} }
309
- }
310
- }
311
- }, []];
312
- }
313
- async createWithdrawAllocationRequest(allocationRequestCid) {
314
- return [{
315
- templateId: ALLOCATION_REQUEST_INTERFACE_ID,
316
- contractId: allocationRequestCid,
317
- choice: "AllocationRequest_Withdraw",
318
- choiceArgument: { extraArgs: {
319
- context: { values: {} },
320
- meta: { values: {} }
321
- } }
322
- }, []];
323
- }
324
- };
325
- var TransferService = class {
326
- constructor(core, logger) {
327
- this.core = core;
328
- this.logger = logger;
329
- }
330
- async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion) {
331
- const inputHoldingCids = await this.core.getInputHoldingsCids({
332
- sender,
333
- instrumentAdmin,
334
- instrumentId,
335
- inputUtxos: inputUtxos ?? [],
336
- amount: new Decimal(amount),
337
- continueUntilCompletion: continueUntilCompletion ?? false
338
- });
339
- return {
340
- expectedAdmin: instrumentAdmin,
341
- transfer: {
342
- sender,
343
- receiver,
344
- amount,
345
- instrumentId: {
346
- admin: instrumentAdmin,
347
- id: instrumentId
348
- },
349
- requestedAt: (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
350
- executeBefore: (expiryDate ?? new Date(Date.now() + 864e5)).toISOString(),
351
- inputHoldingCids,
352
- meta: { values: {
353
- [TokenStandardService.MEMO_KEY]: memo || "",
354
- ...meta?.values
355
- } }
356
- },
357
- extraArgs: {
358
- context: { values: {} },
359
- meta: { values: {} }
360
- }
361
- };
362
- }
363
- async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
364
- return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
365
- choiceArguments: choiceArgs,
366
- excludeDebugFields
367
- });
368
- }
369
- async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
370
- this.logger.debug("Creating transfer from pre-fetched context...");
371
- choiceArgs.extraArgs.context = {
372
- ...choiceContext.choiceContextData,
373
- values: choiceContext.choiceContextData?.values ?? {}
374
- };
375
- return [{
376
- templateId: TRANSFER_FACTORY_INTERFACE_ID,
377
- contractId: factoryId,
378
- choice: "TransferFactory_Transfer",
180
+ choice: "TransferFactory_Transfer",
379
181
  choiceArgument: choiceArgs
380
182
  }, choiceContext.disclosedContracts];
381
183
  }
@@ -402,7 +204,7 @@ var TransferService = class {
402
204
  return [{
403
205
  templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
404
206
  contractId: transferInstructionCid,
405
- choice: "TransferInstruction_Accept",
207
+ choice: TransferInstruction.TransferInstruction_Accept.choiceName,
406
208
  choiceArgument: { extraArgs: {
407
209
  context: choiceContext.choiceContextData,
408
210
  meta: { values: {} }
@@ -414,7 +216,7 @@ var TransferService = class {
414
216
  }
415
217
  }
416
218
  async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
417
- const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(transferInstructionCid, registryUrl.href);
219
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(transferInstructionCid, registryUrl);
418
220
  const choiceArgs = {
419
221
  cid: acceptTransferInstructionContext.contractId,
420
222
  proxyArg: {
@@ -431,7 +233,7 @@ var TransferService = class {
431
233
  }, disclosedContracts];
432
234
  }
433
235
  async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
434
- const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(transferInstructionCid, registryUrl.href);
236
+ const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(transferInstructionCid, registryUrl);
435
237
  const choiceArgs = {
436
238
  cid: rejectTransferInstructionContext.contractId,
437
239
  proxyArg: {
@@ -448,7 +250,7 @@ var TransferService = class {
448
250
  }, disclosedContracts];
449
251
  }
450
252
  async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
451
- const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl.href);
253
+ const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl);
452
254
  if (beneficiaries.reduce((totalWeight, beneficiary) => totalWeight + beneficiary.weight, 0) > 1) throw new Error("Sum of beneficiary weights is larger than 1.");
453
255
  const choiceArgs = {
454
256
  cid: withdrawTransferInstructionContext.contractId,
@@ -485,7 +287,7 @@ var TransferService = class {
485
287
  return [{
486
288
  templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
487
289
  contractId: transferInstructionCid,
488
- choice: "TransferInstruction_Reject",
290
+ choice: TransferInstruction.TransferInstruction_Reject.choiceName,
489
291
  choiceArgument: { extraArgs: {
490
292
  context: choiceContext.choiceContextData,
491
293
  meta: { values: {} }
@@ -516,7 +318,7 @@ var TransferService = class {
516
318
  return [{
517
319
  templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
518
320
  contractId: transferInstructionCid,
519
- choice: "TransferInstruction_Withdraw",
321
+ choice: TransferInstruction.TransferInstruction_Withdraw.choiceName,
520
322
  choiceArgument: { extraArgs: {
521
323
  context: choiceContext.choiceContextData,
522
324
  meta: { values: {} }
@@ -543,23 +345,549 @@ var TransferService = class {
543
345
  }
544
346
  }
545
347
  };
546
- var TokenStandardService = class {
547
- constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
548
- this.ledgerProvider = ledgerProvider;
348
+ //#endregion
349
+ //#region src/v1/allocation-service.ts
350
+ var AllocationService$1 = class {
351
+ constructor(core, logger) {
352
+ this.core = core;
549
353
  this.logger = logger;
550
- this.accessTokenProvider = accessTokenProvider;
551
- this.isMasterUser = isMasterUser;
552
- _defineProperty(this, "core", void 0);
553
- _defineProperty(this, "allocation", void 0);
554
- _defineProperty(this, "transfer", void 0);
555
- this.core = new CoreService(ledgerProvider, logger, accessTokenProvider, isMasterUser);
556
- this.allocation = new AllocationService(this.core, this.logger);
557
- this.transfer = new TransferService(this.core, this.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
+ }
866
+ var TokenStandardService = class {
867
+ constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
868
+ this.ledgerProvider = ledgerProvider;
869
+ this.logger = logger;
870
+ this.accessTokenProvider = accessTokenProvider;
871
+ this.isMasterUser = isMasterUser;
872
+ _defineProperty(this, "core", void 0);
873
+ _defineProperty(this, "allocation", void 0);
874
+ _defineProperty(this, "transfer", void 0);
875
+ _defineProperty(this, "v2", void 0);
876
+ this.core = new CoreService(ledgerProvider, logger, accessTokenProvider, isMasterUser);
877
+ this.allocation = new AllocationService$1(this.core, this.logger);
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
+ };
883
+ }
884
+ async resolveCapabilitiesFromRegistryByInstrumentId(registryUrl, instrumentId) {
885
+ return resolveCapabilities({ supportedApis: (await this.getInstrumentById(registryUrl, instrumentId)).supportedApis });
558
886
  }
559
887
  async getInstrumentById(registryUrl, instrumentId) {
560
888
  try {
561
889
  const params = { path: { instrumentId } };
562
- return this.core.getTokenStandardClient(registryUrl).get("/registry/metadata/v1/instruments/{instrumentId}", params);
890
+ return await this.core.getTokenStandardClient(registryUrl).get("/registry/metadata/v1/instruments/{instrumentId}", params);
563
891
  } catch (e) {
564
892
  this.logger.error(e);
565
893
  throw new Error(`Instrument id ${instrumentId} does not exist for this instrument admin.`, { cause: e });
@@ -587,7 +915,8 @@ var TokenStandardService = class {
587
915
  displayName: instrument.name,
588
916
  symbol: instrument.symbol,
589
917
  registryUrl,
590
- admin: instrumentAdmin
918
+ admin: instrumentAdmin,
919
+ capabilities: resolveCapabilities({ supportedApis: instrument.supportedApis })
591
920
  }));
592
921
  }
593
922
  async registriesToAssets(registryUrls) {
@@ -762,6 +1091,6 @@ var TokenStandardService = class {
762
1091
  };
763
1092
  _defineProperty(TokenStandardService, "MEMO_KEY", "splice.lfdecentralizedtrust.org/reason");
764
1093
  //#endregion
765
- export { CoreService, TokenStandardService };
1094
+ export { EMPTY_META, KEY_MAPPING, REQUESTED_AT_SKEW_MS, SUPPORTED_VERSIONS, TokenStandardService, isApiVersion, resolveCapabilities };
766
1095
 
767
1096
  //# sourceMappingURL=index.js.map