@canton-network/core-token-standard-service 2.4.0 → 2.5.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,22 +1,11 @@
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
1
  import { EventFilterBySetup } from "@canton-network/core-ledger-client-types";
2
+ 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";
3
3
  import { TokenStandardTransactionInterfaces, TransactionParser, ensureInterfaceViewIsPresent, renderTransaction } from "@canton-network/core-tx-parser";
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, AllocationInstruction, HOLDING_INTERFACE_ID_V2, TRANSFER_FACTORY_INTERFACE_ID_V2, TRANSFER_INSTRUCTION_INTERFACE_ID_V2, TokenStandardClient as TokenStandardClient$1, TransferInstruction as TransferInstruction$1, isSameAccount } from "@canton-network/core-token-standard-v2";
6
4
  import { getLogger } from "@logtape/logtape";
7
5
  import { ACSReader } from "@canton-network/core-acs-reader";
8
- // src/types.ts
9
- const REQUESTED_AT_SKEW_MS = 6e4;
10
- const EMPTY_META = { values: {} };
11
- const SUPPORTED_VERSIONS = ["v1", "v2"];
12
- const KEY_MAPPING = {
13
- holding: "holding",
14
- "transfer-instruction": "transferInstruction",
15
- allocation: "allocation",
16
- "allocation-instruction": "allocationInstruction",
17
- "allocation-request": "allocationRequest"
18
- };
19
- // \0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js
6
+ import { ALLOCATION_FACTORY_INTERFACE_ID_V2, ALLOCATION_INSTRUCTION_INTERFACE_ID_V2, ALLOCATION_INTERFACE_ID_V2, ALLOCATION_REQUEST_INTERFACE_ID_V2, AllocationInstruction, HOLDING_INTERFACE_ID_V2, TRANSFER_FACTORY_INTERFACE_ID_V2, TRANSFER_INSTRUCTION_INTERFACE_ID_V2, TokenStandardClient as TokenStandardClient$1, TransferInstruction as TransferInstruction$1, isSameAccount } from "@canton-network/core-token-standard-v2";
7
+ import { Decimal } from "decimal.js";
8
+ // \0@oxc-project+runtime@0.158.0/helpers/esm/typeof.js
20
9
  function _typeof(o) {
21
10
  "@babel/helpers - typeof";
22
11
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -25,7 +14,7 @@ function _typeof(o) {
25
14
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
26
15
  }, _typeof(o);
27
16
  }
28
- // \0@oxc-project+runtime@0.157.0/helpers/esm/toPrimitive.js
17
+ // \0@oxc-project+runtime@0.158.0/helpers/esm/toPrimitive.js
29
18
  function toPrimitive(t, e) {
30
19
  if ("object" != _typeof(t) || !t) return t;
31
20
  var r;
@@ -36,12 +25,12 @@ function toPrimitive(t, e) {
36
25
  }
37
26
  return ("string" === e ? String : Number)(t);
38
27
  }
39
- // \0@oxc-project+runtime@0.157.0/helpers/esm/toPropertyKey.js
28
+ // \0@oxc-project+runtime@0.158.0/helpers/esm/toPropertyKey.js
40
29
  function toPropertyKey(t) {
41
30
  var i = toPrimitive(t, "string");
42
31
  return "symbol" == _typeof(i) ? i : i + "";
43
32
  }
44
- // \0@oxc-project+runtime@0.157.0/helpers/esm/defineProperty.js
33
+ // \0@oxc-project+runtime@0.158.0/helpers/esm/defineProperty.js
45
34
  function _defineProperty(e, r, t) {
46
35
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
47
36
  value: t,
@@ -50,342 +39,172 @@ function _defineProperty(e, r, t) {
50
39
  writable: !0
51
40
  }) : e[r] = t, e;
52
41
  }
53
- // src/v2/transfer-service.ts
54
- var TransferServiceV2 = class {
55
- constructor(core) {
56
- this.core = core;
57
- _defineProperty(this, "logger", getLogger([
58
- "core",
59
- "token-standard-service",
60
- "TransferServiceV2"
61
- ]));
62
- }
63
- async buildTransferChoiceArgs(opts) {
64
- const inputHoldingCids = await this.core.getInputHoldingCidsForAccount({
65
- account: opts.sender,
66
- instrumentAdmin: opts.instrumentAdmin,
67
- instrumentId: opts.instrumentId,
68
- inputUtxos: opts.inputUtxos ?? [],
69
- amount: new Decimal$1(opts.amount),
70
- continueUntilCompletion: opts.continueUntilCompletion ?? false
71
- });
72
- return {
73
- actors: opts.actors ?? [opts.sender.owner, opts.sender.provider].flatMap((partyId) => partyId != null ? [partyId] : []),
74
- transfer: {
75
- sender: opts.sender,
76
- receiver: opts.receiver,
77
- amount: opts.amount,
78
- instrumentId: {
79
- admin: opts.instrumentAdmin,
80
- id: opts.instrumentId
81
- },
82
- requestedAt: (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
83
- executeBefore: (opts.expiryDate ?? new Date(Date.now() + 864e5)).toISOString(),
84
- inputHoldingCids,
85
- meta: { values: {
86
- [TokenStandardService.MEMO_KEY]: opts.memo || "",
87
- ...opts.meta?.values
88
- } }
89
- },
90
- extraArgs: {
91
- context: { values: {} },
92
- meta: { values: {} }
93
- }
94
- };
95
- }
96
- async createTransfer(args, registryUrl, prefetched) {
97
- const choiceArgs = await this.buildTransferChoiceArgs(args);
98
- const { factoryId, choiceContext } = prefetched ?? await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/transfer-factory", {
99
- choiceArguments: choiceArgs,
100
- excludeDebugFields: true
101
- });
102
- return this.createTransferFromContext(factoryId, choiceArgs, choiceContext);
103
- }
104
- async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
105
- this.logger.debug("Creating transfer from pre-fetched context...");
106
- choiceArgs.extraArgs.context = {
107
- ...choiceContext.choiceContextData,
108
- values: choiceContext.choiceContextData?.values ?? {}
109
- };
110
- return [{
111
- templateId: TRANSFER_FACTORY_INTERFACE_ID_V2,
112
- contractId: factoryId,
113
- choice: "TransferFactory_Transfer",
114
- choiceArgument: choiceArgs
115
- }, choiceContext.disclosedContracts];
116
- }
117
- async rejectTransferInstruction(transferInstructionCid, actors, registryUrl) {
118
- const ctx = await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/{transferInstructionId}/choice-contexts/reject", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
119
- return [{
120
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID_V2,
121
- contractId: transferInstructionCid,
122
- choice: TransferInstruction$1.TransferInstruction_Reject.choiceName,
123
- choiceArgument: {
124
- actors,
125
- extraArgs: {
126
- context: ctx.choiceContextData,
127
- meta: EMPTY_META
128
- }
129
- }
130
- }, ctx.disclosedContracts ?? []];
131
- }
132
- async withdrawTransferInstruction(transferInstructionCid, actors, registryUrl) {
133
- const ctx = await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/{transferInstructionId}/choice-contexts/withdraw", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
134
- return [{
135
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID_V2,
136
- contractId: transferInstructionCid,
137
- choice: TransferInstruction$1.TransferInstruction_Withdraw.choiceName,
138
- choiceArgument: {
139
- actors,
140
- extraArgs: {
141
- context: ctx.choiceContextData,
142
- meta: EMPTY_META
143
- }
144
- }
145
- }, ctx.disclosedContracts ?? []];
146
- }
147
- async acceptTransferInstruction(transferInstructionCid, actors, registryUrl) {
148
- const ctx = await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/{transferInstructionId}/choice-contexts/accept", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
149
- return [{
150
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID_V2,
151
- contractId: transferInstructionCid,
152
- choice: TransferInstruction$1.TransferInstruction_Accept.choiceName,
153
- choiceArgument: {
154
- actors,
155
- extraArgs: {
156
- context: ctx.choiceContextData,
157
- meta: EMPTY_META
158
- }
159
- }
160
- }, ctx.disclosedContracts ?? []];
161
- }
162
- };
163
- // src/v1/transfer-service.ts
164
- var TransferService = class {
165
- constructor(core) {
166
- this.core = core;
42
+ // src/core-service.ts
43
+ var CoreService = class CoreService {
44
+ constructor(ledgerProvider, accessTokenProvider, isMasterUser) {
45
+ this.ledgerProvider = ledgerProvider;
46
+ this.accessTokenProvider = accessTokenProvider;
47
+ this.isMasterUser = isMasterUser;
167
48
  _defineProperty(this, "logger", getLogger([
168
49
  "core",
169
50
  "token-standard-service",
170
- "TransferService"
51
+ "CoreService"
171
52
  ]));
172
53
  }
173
- async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion) {
174
- const inputHoldingCids = await this.core.getInputHoldingsCids({
175
- sender,
176
- instrumentAdmin,
177
- instrumentId,
178
- inputUtxos: inputUtxos ?? [],
179
- amount: new Decimal(amount),
180
- continueUntilCompletion: continueUntilCompletion ?? false
181
- });
182
- return {
183
- expectedAdmin: instrumentAdmin,
184
- transfer: {
185
- sender,
186
- receiver,
187
- amount,
188
- instrumentId: {
189
- admin: instrumentAdmin,
190
- id: instrumentId
191
- },
192
- requestedAt: (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
193
- executeBefore: (expiryDate ?? new Date(Date.now() + 864e5)).toISOString(),
194
- inputHoldingCids,
195
- meta: { values: {
196
- [TokenStandardService.MEMO_KEY]: memo || "",
197
- ...meta?.values
198
- } }
199
- },
200
- extraArgs: {
201
- context: { values: {} },
202
- meta: { values: {} }
203
- }
204
- };
205
- }
206
- async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
207
- return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
208
- choiceArguments: choiceArgs,
209
- excludeDebugFields
210
- });
54
+ getTokenStandardClientWithVersion(registryUrl, version) {
55
+ if (!isApiVersion(version)) throw new Error(`Unsupported token standard api version.`);
56
+ return version === "v2" ? new TokenStandardClient$1(registryUrl.href, this.logger, this.accessTokenProvider) : new TokenStandardClient(registryUrl.href, this.logger, this.accessTokenProvider);
211
57
  }
212
- async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
213
- this.logger.debug("Creating transfer from pre-fetched context...");
214
- choiceArgs.extraArgs.context = {
215
- ...choiceContext.choiceContextData,
216
- values: choiceContext.choiceContextData?.values ?? {}
217
- };
218
- return [{
219
- templateId: TRANSFER_FACTORY_INTERFACE_ID,
220
- contractId: factoryId,
221
- choice: "TransferFactory_Transfer",
222
- choiceArgument: choiceArgs
223
- }, choiceContext.disclosedContracts];
58
+ getTokenStandardClient(registryUrl) {
59
+ return new TokenStandardClient(registryUrl.href, this.logger, this.accessTokenProvider);
224
60
  }
225
- async createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext, continueUntilCompletion) {
226
- try {
227
- const choiceArgs = await this.buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion);
228
- if (prefetchedRegistryChoiceContext) return this.createTransferFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
229
- const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(registryUrl, choiceArgs);
230
- return this.createTransferFromContext(factoryId, choiceArgs, choiceContext);
231
- } catch (e) {
232
- this.logger.warn("Failed to execute transfer:", { error: e });
233
- throw e;
234
- }
61
+ getTokenStandardClientV2(registryUrl) {
62
+ return new TokenStandardClient$1(registryUrl.href, this.logger, this.accessTokenProvider);
235
63
  }
236
- async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
237
- const choiceContext = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
64
+ toBasicAccount(partyId) {
238
65
  return {
239
- choiceContextData: choiceContext.choiceContextData,
240
- disclosedContracts: choiceContext.disclosedContracts
241
- };
242
- }
243
- async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
244
- try {
245
- return [{
246
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
247
- contractId: transferInstructionCid,
248
- choice: TransferInstruction.TransferInstruction_Accept.choiceName,
249
- choiceArgument: { extraArgs: {
250
- context: choiceContext.choiceContextData,
251
- meta: { values: {} }
252
- } }
253
- }, choiceContext.disclosedContracts];
254
- } catch (e) {
255
- this.logger.warn("Failed to create accept transfer instruction:", { error: e });
256
- throw e;
257
- }
258
- }
259
- async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
260
- const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(transferInstructionCid, registryUrl);
261
- const choiceArgs = {
262
- cid: acceptTransferInstructionContext.contractId,
263
- proxyArg: {
264
- featuredAppRightCid,
265
- beneficiaries,
266
- choiceArg: acceptTransferInstructionContext.choiceArgument
267
- }
66
+ owner: partyId,
67
+ provider: null,
68
+ id: ""
268
69
  };
269
- return [{
270
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
271
- contractId: proxyCid,
272
- choice: "DelegateProxy_TransferInstruction_Accept",
273
- choiceArgument: choiceArgs
274
- }, disclosedContracts];
275
70
  }
276
- async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
277
- const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(transferInstructionCid, registryUrl);
278
- const choiceArgs = {
279
- cid: rejectTransferInstructionContext.contractId,
280
- proxyArg: {
281
- featuredAppRightCid,
282
- beneficiaries,
283
- choiceArg: rejectTransferInstructionContext.choiceArgument
284
- }
285
- };
286
- return [{
287
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
288
- contractId: proxyCid,
289
- choice: "DelegateProxy_TransferInstruction_Reject",
290
- choiceArgument: choiceArgs
291
- }, disclosedContracts];
71
+ async getInputHoldingCidsForAccount(opts) {
72
+ if (opts.inputUtxos?.length) return opts.inputUtxos;
73
+ const party = opts.partyId ?? opts.account.owner;
74
+ if (!party) throw new Error("No party to query as");
75
+ const now = /* @__PURE__ */ new Date();
76
+ const holdings = (await this.listContractsByInterface(HOLDING_INTERFACE_ID_V2, party, opts.limit, opts.offset, opts.continueUntilCompletion ?? false)).filter((h) => h.interfaceViewValue.instrumentId.admin === opts.instrumentAdmin && h.interfaceViewValue.instrumentId.id === opts.instrumentId && isSameAccount(opts.account, h.interfaceViewValue.account) && !TokenStandardService.isHoldingLocked(h, now) && !opts.excludeCids?.has(h.contractId));
77
+ return opts.amount ? CoreService.getInputHoldingsCidsForAmount(opts.amount, holdings) : holdings.map((h) => h.contractId);
292
78
  }
293
- async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
294
- const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl);
295
- if (beneficiaries.reduce((totalWeight, beneficiary) => totalWeight + beneficiary.weight, 0) > 1) throw new Error("Sum of beneficiary weights is larger than 1.");
296
- const choiceArgs = {
297
- cid: withdrawTransferInstructionContext.contractId,
298
- proxyArg: {
299
- featuredAppRightCid,
300
- beneficiaries,
301
- choiceArg: withdrawTransferInstructionContext.choiceArgument
302
- }
303
- };
304
- return [{
305
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
306
- contractId: proxyCid,
307
- choice: "DelegateProxy_TransferInstruction_Withdraw",
308
- choiceArgument: choiceArgs
309
- }, disclosedContracts];
79
+ async getInputHoldingsCids(options) {
80
+ const { sender, instrumentAdmin, instrumentId } = options;
81
+ const now = /* @__PURE__ */ new Date();
82
+ if (options.inputUtxos && options.inputUtxos.length > 0) return options.inputUtxos;
83
+ const senderHoldings = await this.listContractsByInterface(HOLDING_INTERFACE_ID, sender, void 0, void 0, options.continueUntilCompletion);
84
+ if (senderHoldings.length === 0) throw new Error("Sender has no holdings, so transfer can't be executed.");
85
+ const unlockedSenderHoldings = senderHoldings.filter((utxo) => !TokenStandardService.isHoldingLocked(utxo, now));
86
+ if (unlockedSenderHoldings.length > 100) this.logger.warn(`Sender has more than 100 unlocked utxos.`);
87
+ const unlockedHoldingsForInstrument = instrumentAdmin && instrumentId ? await CoreService.filterHoldingsByInstrument({
88
+ holdings: unlockedSenderHoldings,
89
+ instrumentAdmin,
90
+ instrumentId
91
+ }) : unlockedSenderHoldings;
92
+ if (options.amount) return CoreService.getInputHoldingsCidsForAmount(options.amount, unlockedHoldingsForInstrument);
93
+ else return unlockedHoldingsForInstrument.map((h) => h.contractId);
310
94
  }
311
- async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
312
- if (prefetchedRegistryChoiceContext) return this.createAcceptTransferInstructionFromContext(transferInstructionCid, {
313
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
314
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
95
+ static async filterHoldingsByInstrument(options) {
96
+ const { holdings, instrumentAdmin, instrumentId } = options;
97
+ return holdings.filter((utxo) => {
98
+ return utxo.interfaceViewValue.instrumentId.id === instrumentId && utxo.interfaceViewValue.instrumentId.admin === instrumentAdmin;
315
99
  });
316
- const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
317
- return this.createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext);
318
100
  }
319
- async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
320
- const choiceContext = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
321
- return {
322
- choiceContextData: choiceContext.choiceContextData,
323
- disclosedContracts: choiceContext.disclosedContracts
324
- };
101
+ static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
102
+ const exactAmount = unlockedSenderHoldings.find((holding) => new Decimal(holding.interfaceViewValue.amount).equals(amount));
103
+ if (exactAmount) return [exactAmount.contractId];
104
+ const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted((a, b) => new Decimal(a.interfaceViewValue.amount).comparedTo(new Decimal(b.interfaceViewValue.amount)));
105
+ const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
106
+ if (!largestHoldingAmount) throw new Error(`Sender doesn't have any unlocked holdings`);
107
+ let currentSum = new Decimal(largestHoldingAmount.interfaceViewValue.amount);
108
+ const cIds = [largestHoldingAmount.contractId];
109
+ for (const h of sortedUnlockedSenderHoldings) {
110
+ if (currentSum.greaterThanOrEqualTo(amount)) break;
111
+ const currentHoldingAmount = new Decimal(h.interfaceViewValue.amount);
112
+ currentSum = currentSum.plus(currentHoldingAmount);
113
+ cIds.push(h.contractId);
114
+ }
115
+ if (currentSum.lessThan(amount)) throw new Error(`Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount.minus(currentSum).toString()}`);
116
+ if (cIds.length > 100) throw new Error(`Exceeded the maximum of 100 utxos in 1 transaction`);
117
+ return cIds;
325
118
  }
326
- async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
119
+ async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
327
120
  try {
328
- return [{
329
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
330
- contractId: transferInstructionCid,
331
- choice: TransferInstruction.TransferInstruction_Reject.choiceName,
332
- choiceArgument: { extraArgs: {
333
- context: choiceContext.choiceContextData,
334
- meta: { values: {} }
335
- } }
336
- }, choiceContext.disclosedContracts];
337
- } catch (e) {
338
- this.logger.warn("Failed to create reject transfer instruction:", { error: e });
339
- throw e;
121
+ const ledgerEnd = offset ?? (await this.ledgerProvider.request({
122
+ method: "ledgerApi",
123
+ params: {
124
+ resource: "/v2/state/ledger-end",
125
+ requestMethod: "get",
126
+ query: {}
127
+ }
128
+ })).offset;
129
+ const options = {
130
+ offset: ledgerEnd,
131
+ interfaceIds: [interfaceId],
132
+ parties: [partyId],
133
+ filterByParty: true,
134
+ continueUntilCompletion: Boolean(continueUntilCompletion)
135
+ };
136
+ if (limit !== void 0) options.limit = limit;
137
+ this.logger.debug("Continue to completion: {continueUntilCompletion}", { continueUntilCompletion: Boolean(continueUntilCompletion) });
138
+ const acsResponses = await new ACSReader(this.ledgerProvider).raw.read(options);
139
+ const isActiveContractEntry = (acsResponse) => acsResponse.contractEntry != null && "JsActiveContract" in acsResponse.contractEntry && acsResponse.contractEntry.JsActiveContract != null && acsResponse.contractEntry.JsActiveContract.createdEvent != null;
140
+ return acsResponses.filter(isActiveContractEntry).map((response) => this.toPrettyContract(interfaceId, response, ledgerEnd));
141
+ } catch (err) {
142
+ this.logger.error(`Failed to list contracts of interface {interfaceId}`, {
143
+ interfaceId,
144
+ err
145
+ });
146
+ throw err;
340
147
  }
341
148
  }
342
- async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
343
- if (prefetchedRegistryChoiceContext) return this.createRejectTransferInstructionFromContext(transferInstructionCid, {
344
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
345
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
346
- });
347
- const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
348
- return this.createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext);
349
- }
350
- async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
351
- const choiceContext = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
149
+ async toPrettyTransactions(updates, partyId) {
150
+ const isOffsetCheckpointUpdate = (updateResponse) => updateResponse.update != null && "OffsetCheckpoint" in updateResponse.update;
151
+ const isTransactionUpdate = (updateResponse) => updateResponse.update != null && "Transaction" in updateResponse.update && !!updateResponse.update.Transaction?.value;
152
+ const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map((update) => update.update.OffsetCheckpoint.value.offset);
153
+ const latestCheckpointOffset = offsetCheckpoints.length > 0 ? Math.max(...offsetCheckpoints) : 0;
154
+ const transactions = await Promise.all(updates.filter(isTransactionUpdate).map(async (update) => {
155
+ const tx = update.update.Transaction.value;
156
+ return await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
157
+ }));
158
+ const transactionOffsets = transactions.map((tx) => tx.offset).filter((offset) => offset !== void 0);
352
159
  return {
353
- choiceContextData: choiceContext.choiceContextData,
354
- disclosedContracts: choiceContext.disclosedContracts
160
+ nextOffset: Math.max(latestCheckpointOffset, ...transactionOffsets.length > 0 ? transactionOffsets : [0]),
161
+ transactions: transactions.filter((tx) => tx.events.length > 0).map(renderTransaction)
355
162
  };
356
163
  }
357
- async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
358
- try {
359
- return [{
360
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
361
- contractId: transferInstructionCid,
362
- choice: TransferInstruction.TransferInstruction_Withdraw.choiceName,
363
- choiceArgument: { extraArgs: {
364
- context: choiceContext.choiceContextData,
365
- meta: { values: {} }
366
- } }
367
- }, choiceContext.disclosedContracts];
368
- } catch (e) {
369
- this.logger.warn("Failed to create withdraw transfer instruction:", { error: e });
370
- throw e;
371
- }
164
+ async toPrettyTransaction(getUpdateResponse, partyId) {
165
+ const tx = this.getTransactionFromUpdate(getUpdateResponse);
166
+ const parsedTx = await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
167
+ return renderTransaction(parsedTx);
372
168
  }
373
- async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
374
- if (prefetchedRegistryChoiceContext) return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, {
375
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
376
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
377
- });
378
- const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
379
- return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext);
169
+ async toPrettyTransferObjects(getUpdateResponse, partyId) {
170
+ const tx = this.getTransactionFromUpdate(getUpdateResponse);
171
+ return await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransferObjects();
380
172
  }
381
- async createTransferInstruction(transferInstructionCid, registryUrl, instructionChoice, prefetchedRegistryChoiceContext) {
382
- switch (instructionChoice) {
383
- case "Accept": return this.createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext);
384
- case "Reject": return this.createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext);
385
- case "Withdraw": return this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext);
386
- }
173
+ getTransactionFromUpdate(getUpdateResponse) {
174
+ const update = getUpdateResponse.update;
175
+ if (!update || !("Transaction" in update)) throw new Error("Expected transaction update");
176
+ return update.Transaction.value;
177
+ }
178
+ async toPrettyTransactionsPerParty(updates, parties) {
179
+ const all = await Promise.all(parties.map(async (partyId) => [partyId, await this.toPrettyTransactions(updates, partyId)]));
180
+ return new Map(all);
181
+ }
182
+ toPrettyContract(interfaceId, response, offset) {
183
+ const activeContract = response.contractEntry.JsActiveContract;
184
+ const { createdEvent } = activeContract;
185
+ return {
186
+ contractId: createdEvent.contractId,
187
+ activeContract,
188
+ interfaceViewValue: ensureInterfaceViewIsPresent(createdEvent, interfaceId).viewValue,
189
+ fetchedAtOffset: offset
190
+ };
191
+ }
192
+ toQualifiedMemberId(memberId) {
193
+ if (!memberId) throw new Error("memberId is required");
194
+ return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
387
195
  }
388
196
  };
197
+ // src/types.ts
198
+ const REQUESTED_AT_SKEW_MS = 6e4;
199
+ const EMPTY_META = { values: {} };
200
+ const SUPPORTED_VERSIONS = ["v1", "v2"];
201
+ const KEY_MAPPING = {
202
+ holding: "holding",
203
+ "transfer-instruction": "transferInstruction",
204
+ allocation: "allocation",
205
+ "allocation-instruction": "allocationInstruction",
206
+ "allocation-request": "allocationRequest"
207
+ };
389
208
  // src/v1/allocation-service.ts
390
209
  var AllocationService$1 = class {
391
210
  constructor(core) {
@@ -539,159 +358,230 @@ var AllocationService$1 = class {
539
358
  }, []];
540
359
  }
541
360
  };
542
- // src/core-service.ts
543
- var CoreService = class CoreService {
544
- constructor(ledgerProvider, accessTokenProvider, isMasterUser) {
545
- this.ledgerProvider = ledgerProvider;
546
- this.accessTokenProvider = accessTokenProvider;
547
- this.isMasterUser = isMasterUser;
361
+ // src/v1/transfer-service.ts
362
+ var TransferService = class {
363
+ constructor(core) {
364
+ this.core = core;
548
365
  _defineProperty(this, "logger", getLogger([
549
366
  "core",
550
367
  "token-standard-service",
551
- "CoreService"
368
+ "TransferService"
552
369
  ]));
553
370
  }
554
- getTokenStandardClientWithVersion(registryUrl, version) {
555
- if (!isApiVersion(version)) throw new Error(`Unsupported token standard api version.`);
556
- return version === "v2" ? new TokenStandardClient$1(registryUrl.href, this.logger, this.accessTokenProvider) : new TokenStandardClient(registryUrl.href, this.logger, this.accessTokenProvider);
371
+ async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion) {
372
+ const inputHoldingCids = await this.core.getInputHoldingsCids({
373
+ sender,
374
+ instrumentAdmin,
375
+ instrumentId,
376
+ inputUtxos: inputUtxos ?? [],
377
+ amount: new Decimal(amount),
378
+ continueUntilCompletion: continueUntilCompletion ?? false
379
+ });
380
+ return {
381
+ expectedAdmin: instrumentAdmin,
382
+ transfer: {
383
+ sender,
384
+ receiver,
385
+ amount,
386
+ instrumentId: {
387
+ admin: instrumentAdmin,
388
+ id: instrumentId
389
+ },
390
+ requestedAt: (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
391
+ executeBefore: (expiryDate ?? new Date(Date.now() + 864e5)).toISOString(),
392
+ inputHoldingCids,
393
+ meta: { values: {
394
+ [TokenStandardService.MEMO_KEY]: memo || "",
395
+ ...meta?.values
396
+ } }
397
+ },
398
+ extraArgs: {
399
+ context: { values: {} },
400
+ meta: { values: {} }
401
+ }
402
+ };
557
403
  }
558
- getTokenStandardClient(registryUrl) {
559
- return new TokenStandardClient(registryUrl.href, this.logger, this.accessTokenProvider);
404
+ async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
405
+ return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
406
+ choiceArguments: choiceArgs,
407
+ excludeDebugFields
408
+ });
560
409
  }
561
- getTokenStandardClientV2(registryUrl) {
562
- return new TokenStandardClient$1(registryUrl.href, this.logger, this.accessTokenProvider);
410
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
411
+ this.logger.debug("Creating transfer from pre-fetched context...");
412
+ choiceArgs.extraArgs.context = {
413
+ ...choiceContext.choiceContextData,
414
+ values: choiceContext.choiceContextData?.values ?? {}
415
+ };
416
+ return [{
417
+ templateId: TRANSFER_FACTORY_INTERFACE_ID,
418
+ contractId: factoryId,
419
+ choice: "TransferFactory_Transfer",
420
+ choiceArgument: choiceArgs
421
+ }, choiceContext.disclosedContracts];
563
422
  }
564
- toBasicAccount(partyId) {
423
+ async createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext, continueUntilCompletion) {
424
+ try {
425
+ const choiceArgs = await this.buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion);
426
+ if (prefetchedRegistryChoiceContext) return this.createTransferFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
427
+ const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(registryUrl, choiceArgs);
428
+ return this.createTransferFromContext(factoryId, choiceArgs, choiceContext);
429
+ } catch (e) {
430
+ this.logger.warn("Failed to execute transfer:", { error: e });
431
+ throw e;
432
+ }
433
+ }
434
+ async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
435
+ const choiceContext = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
565
436
  return {
566
- owner: partyId,
567
- provider: null,
568
- id: ""
437
+ choiceContextData: choiceContext.choiceContextData,
438
+ disclosedContracts: choiceContext.disclosedContracts
569
439
  };
570
440
  }
571
- async getInputHoldingCidsForAccount(opts) {
572
- if (opts.inputUtxos?.length) return opts.inputUtxos;
573
- const party = opts.partyId ?? opts.account.owner;
574
- if (!party) throw new Error("No party to query as");
575
- const now = /* @__PURE__ */ new Date();
576
- const holdings = (await this.listContractsByInterface(HOLDING_INTERFACE_ID_V2, party, opts.limit, opts.offset, opts.continueUntilCompletion ?? false)).filter((h) => h.interfaceViewValue.instrumentId.admin === opts.instrumentAdmin && h.interfaceViewValue.instrumentId.id === opts.instrumentId && isSameAccount(opts.account, h.interfaceViewValue.account) && !TokenStandardService.isHoldingLocked(h, now) && !opts.excludeCids?.has(h.contractId));
577
- return opts.amount ? CoreService.getInputHoldingsCidsForAmount(opts.amount, holdings) : holdings.map((h) => h.contractId);
441
+ async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
442
+ try {
443
+ return [{
444
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
445
+ contractId: transferInstructionCid,
446
+ choice: TransferInstruction.TransferInstruction_Accept.choiceName,
447
+ choiceArgument: { extraArgs: {
448
+ context: choiceContext.choiceContextData,
449
+ meta: { values: {} }
450
+ } }
451
+ }, choiceContext.disclosedContracts];
452
+ } catch (e) {
453
+ this.logger.warn("Failed to create accept transfer instruction:", { error: e });
454
+ throw e;
455
+ }
578
456
  }
579
- async getInputHoldingsCids(options) {
580
- const { sender, instrumentAdmin, instrumentId } = options;
581
- const now = /* @__PURE__ */ new Date();
582
- if (options.inputUtxos && options.inputUtxos.length > 0) return options.inputUtxos;
583
- const senderHoldings = await this.listContractsByInterface(HOLDING_INTERFACE_ID, sender, void 0, void 0, options.continueUntilCompletion);
584
- if (senderHoldings.length === 0) throw new Error("Sender has no holdings, so transfer can't be executed.");
585
- const unlockedSenderHoldings = senderHoldings.filter((utxo) => !TokenStandardService.isHoldingLocked(utxo, now));
586
- if (unlockedSenderHoldings.length > 100) this.logger.warn(`Sender has more than 100 unlocked utxos.`);
587
- const unlockedHoldingsForInstrument = instrumentAdmin && instrumentId ? await CoreService.filterHoldingsByInstrument({
588
- holdings: unlockedSenderHoldings,
589
- instrumentAdmin,
590
- instrumentId
591
- }) : unlockedSenderHoldings;
592
- if (options.amount) return CoreService.getInputHoldingsCidsForAmount(options.amount, unlockedHoldingsForInstrument);
593
- else return unlockedHoldingsForInstrument.map((h) => h.contractId);
457
+ async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
458
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(transferInstructionCid, registryUrl);
459
+ const choiceArgs = {
460
+ cid: acceptTransferInstructionContext.contractId,
461
+ proxyArg: {
462
+ featuredAppRightCid,
463
+ beneficiaries,
464
+ choiceArg: acceptTransferInstructionContext.choiceArgument
465
+ }
466
+ };
467
+ return [{
468
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
469
+ contractId: proxyCid,
470
+ choice: "DelegateProxy_TransferInstruction_Accept",
471
+ choiceArgument: choiceArgs
472
+ }, disclosedContracts];
594
473
  }
595
- static async filterHoldingsByInstrument(options) {
596
- const { holdings, instrumentAdmin, instrumentId } = options;
597
- return holdings.filter((utxo) => {
598
- return utxo.interfaceViewValue.instrumentId.id === instrumentId && utxo.interfaceViewValue.instrumentId.admin === instrumentAdmin;
474
+ async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
475
+ const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(transferInstructionCid, registryUrl);
476
+ const choiceArgs = {
477
+ cid: rejectTransferInstructionContext.contractId,
478
+ proxyArg: {
479
+ featuredAppRightCid,
480
+ beneficiaries,
481
+ choiceArg: rejectTransferInstructionContext.choiceArgument
482
+ }
483
+ };
484
+ return [{
485
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
486
+ contractId: proxyCid,
487
+ choice: "DelegateProxy_TransferInstruction_Reject",
488
+ choiceArgument: choiceArgs
489
+ }, disclosedContracts];
490
+ }
491
+ async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
492
+ const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl);
493
+ if (beneficiaries.reduce((totalWeight, beneficiary) => totalWeight + beneficiary.weight, 0) > 1) throw new Error("Sum of beneficiary weights is larger than 1.");
494
+ const choiceArgs = {
495
+ cid: withdrawTransferInstructionContext.contractId,
496
+ proxyArg: {
497
+ featuredAppRightCid,
498
+ beneficiaries,
499
+ choiceArg: withdrawTransferInstructionContext.choiceArgument
500
+ }
501
+ };
502
+ return [{
503
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
504
+ contractId: proxyCid,
505
+ choice: "DelegateProxy_TransferInstruction_Withdraw",
506
+ choiceArgument: choiceArgs
507
+ }, disclosedContracts];
508
+ }
509
+ async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
510
+ if (prefetchedRegistryChoiceContext) return this.createAcceptTransferInstructionFromContext(transferInstructionCid, {
511
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
512
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
599
513
  });
514
+ const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
515
+ return this.createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext);
600
516
  }
601
- static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
602
- const exactAmount = unlockedSenderHoldings.find((holding) => new Decimal(holding.interfaceViewValue.amount).equals(amount));
603
- if (exactAmount) return [exactAmount.contractId];
604
- const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted((a, b) => new Decimal(a.interfaceViewValue.amount).comparedTo(new Decimal(b.interfaceViewValue.amount)));
605
- const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
606
- if (!largestHoldingAmount) throw new Error(`Sender doesn't have any unlocked holdings`);
607
- let currentSum = new Decimal(largestHoldingAmount.interfaceViewValue.amount);
608
- const cIds = [largestHoldingAmount.contractId];
609
- for (const h of sortedUnlockedSenderHoldings) {
610
- if (currentSum.greaterThanOrEqualTo(amount)) break;
611
- const currentHoldingAmount = new Decimal(h.interfaceViewValue.amount);
612
- currentSum = currentSum.plus(currentHoldingAmount);
613
- cIds.push(h.contractId);
614
- }
615
- if (currentSum.lessThan(amount)) throw new Error(`Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount.minus(currentSum).toString()}`);
616
- if (cIds.length > 100) throw new Error(`Exceeded the maximum of 100 utxos in 1 transaction`);
617
- return cIds;
517
+ async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
518
+ const choiceContext = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
519
+ return {
520
+ choiceContextData: choiceContext.choiceContextData,
521
+ disclosedContracts: choiceContext.disclosedContracts
522
+ };
618
523
  }
619
- async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
524
+ async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
620
525
  try {
621
- const ledgerEnd = offset ?? (await this.ledgerProvider.request({
622
- method: "ledgerApi",
623
- params: {
624
- resource: "/v2/state/ledger-end",
625
- requestMethod: "get",
626
- query: {}
627
- }
628
- })).offset;
629
- const options = {
630
- offset: ledgerEnd,
631
- interfaceIds: [interfaceId],
632
- parties: [partyId],
633
- filterByParty: true,
634
- continueUntilCompletion: Boolean(continueUntilCompletion)
635
- };
636
- if (limit !== void 0) options.limit = limit;
637
- this.logger.debug("Continue to completion: {continueUntilCompletion}", { continueUntilCompletion: Boolean(continueUntilCompletion) });
638
- const acsResponses = await new ACSReader(this.ledgerProvider).raw.read(options);
639
- const isActiveContractEntry = (acsResponse) => acsResponse.contractEntry != null && "JsActiveContract" in acsResponse.contractEntry && acsResponse.contractEntry.JsActiveContract != null && acsResponse.contractEntry.JsActiveContract.createdEvent != null;
640
- return acsResponses.filter(isActiveContractEntry).map((response) => this.toPrettyContract(interfaceId, response, ledgerEnd));
641
- } catch (err) {
642
- this.logger.error(`Failed to list contracts of interface {interfaceId}`, {
643
- interfaceId,
644
- err
645
- });
646
- throw err;
526
+ return [{
527
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
528
+ contractId: transferInstructionCid,
529
+ choice: TransferInstruction.TransferInstruction_Reject.choiceName,
530
+ choiceArgument: { extraArgs: {
531
+ context: choiceContext.choiceContextData,
532
+ meta: { values: {} }
533
+ } }
534
+ }, choiceContext.disclosedContracts];
535
+ } catch (e) {
536
+ this.logger.warn("Failed to create reject transfer instruction:", { error: e });
537
+ throw e;
647
538
  }
648
539
  }
649
- async toPrettyTransactions(updates, partyId) {
650
- const isOffsetCheckpointUpdate = (updateResponse) => updateResponse.update != null && "OffsetCheckpoint" in updateResponse.update;
651
- const isTransactionUpdate = (updateResponse) => updateResponse.update != null && "Transaction" in updateResponse.update && !!updateResponse.update.Transaction?.value;
652
- const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map((update) => update.update.OffsetCheckpoint.value.offset);
653
- const latestCheckpointOffset = offsetCheckpoints.length > 0 ? Math.max(...offsetCheckpoints) : 0;
654
- const transactions = await Promise.all(updates.filter(isTransactionUpdate).map(async (update) => {
655
- const tx = update.update.Transaction.value;
656
- return await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
657
- }));
658
- const transactionOffsets = transactions.map((tx) => tx.offset).filter((offset) => offset !== void 0);
540
+ async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
541
+ if (prefetchedRegistryChoiceContext) return this.createRejectTransferInstructionFromContext(transferInstructionCid, {
542
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
543
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
544
+ });
545
+ const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
546
+ return this.createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext);
547
+ }
548
+ async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
549
+ const choiceContext = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
659
550
  return {
660
- nextOffset: Math.max(latestCheckpointOffset, ...transactionOffsets.length > 0 ? transactionOffsets : [0]),
661
- transactions: transactions.filter((tx) => tx.events.length > 0).map(renderTransaction)
551
+ choiceContextData: choiceContext.choiceContextData,
552
+ disclosedContracts: choiceContext.disclosedContracts
662
553
  };
663
554
  }
664
- async toPrettyTransaction(getUpdateResponse, partyId) {
665
- const tx = this.getTransactionFromUpdate(getUpdateResponse);
666
- const parsedTx = await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
667
- return renderTransaction(parsedTx);
668
- }
669
- async toPrettyTransferObjects(getUpdateResponse, partyId) {
670
- const tx = this.getTransactionFromUpdate(getUpdateResponse);
671
- return await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransferObjects();
672
- }
673
- getTransactionFromUpdate(getUpdateResponse) {
674
- const update = getUpdateResponse.update;
675
- if (!update || !("Transaction" in update)) throw new Error("Expected transaction update");
676
- return update.Transaction.value;
677
- }
678
- async toPrettyTransactionsPerParty(updates, parties) {
679
- const all = await Promise.all(parties.map(async (partyId) => [partyId, await this.toPrettyTransactions(updates, partyId)]));
680
- return new Map(all);
555
+ async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
556
+ try {
557
+ return [{
558
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
559
+ contractId: transferInstructionCid,
560
+ choice: TransferInstruction.TransferInstruction_Withdraw.choiceName,
561
+ choiceArgument: { extraArgs: {
562
+ context: choiceContext.choiceContextData,
563
+ meta: { values: {} }
564
+ } }
565
+ }, choiceContext.disclosedContracts];
566
+ } catch (e) {
567
+ this.logger.warn("Failed to create withdraw transfer instruction:", { error: e });
568
+ throw e;
569
+ }
681
570
  }
682
- toPrettyContract(interfaceId, response, offset) {
683
- const activeContract = response.contractEntry.JsActiveContract;
684
- const { createdEvent } = activeContract;
685
- return {
686
- contractId: createdEvent.contractId,
687
- activeContract,
688
- interfaceViewValue: ensureInterfaceViewIsPresent(createdEvent, interfaceId).viewValue,
689
- fetchedAtOffset: offset
690
- };
571
+ async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
572
+ if (prefetchedRegistryChoiceContext) return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, {
573
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
574
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
575
+ });
576
+ const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
577
+ return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext);
691
578
  }
692
- toQualifiedMemberId(memberId) {
693
- if (!memberId) throw new Error("memberId is required");
694
- return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
579
+ async createTransferInstruction(transferInstructionCid, registryUrl, instructionChoice, prefetchedRegistryChoiceContext) {
580
+ switch (instructionChoice) {
581
+ case "Accept": return this.createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext);
582
+ case "Reject": return this.createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext);
583
+ case "Withdraw": return this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext);
584
+ }
695
585
  }
696
586
  };
697
587
  // src/v2/allocation-service.ts
@@ -711,12 +601,12 @@ var AllocationService = class AllocationService {
711
601
  }
712
602
  static fundingNeeds(spec) {
713
603
  const needs = /* @__PURE__ */ new Map();
714
- const add = (id, d) => needs.set(id, (needs.get(id) ?? new Decimal$1(0)).plus(d));
604
+ const add = (id, d) => needs.set(id, (needs.get(id) ?? new Decimal(0)).plus(d));
715
605
  for (const leg of spec.transferLegSides) {
716
- const amount = new Decimal$1(leg.amount);
606
+ const amount = new Decimal(leg.amount);
717
607
  add(leg.instrumentId, leg.side === "SenderSide" ? amount : amount.negated());
718
608
  }
719
- for (const [id, amount] of Object.entries(spec.nextIterationFunding ?? {})) add(id, new Decimal$1(amount));
609
+ for (const [id, amount] of Object.entries(spec.nextIterationFunding ?? {})) add(id, new Decimal(amount));
720
610
  for (const [id, amount] of needs) if (amount.lte(0)) needs.delete(id);
721
611
  return needs;
722
612
  }
@@ -941,6 +831,116 @@ var AllocationService = class AllocationService {
941
831
  };
942
832
  }
943
833
  };
834
+ // src/v2/transfer-service.ts
835
+ var TransferServiceV2 = class {
836
+ constructor(core) {
837
+ this.core = core;
838
+ _defineProperty(this, "logger", getLogger([
839
+ "core",
840
+ "token-standard-service",
841
+ "TransferServiceV2"
842
+ ]));
843
+ }
844
+ async buildTransferChoiceArgs(opts) {
845
+ const inputHoldingCids = await this.core.getInputHoldingCidsForAccount({
846
+ account: opts.sender,
847
+ instrumentAdmin: opts.instrumentAdmin,
848
+ instrumentId: opts.instrumentId,
849
+ inputUtxos: opts.inputUtxos ?? [],
850
+ amount: new Decimal(opts.amount),
851
+ continueUntilCompletion: opts.continueUntilCompletion ?? false
852
+ });
853
+ return {
854
+ actors: opts.actors ?? [opts.sender.owner, opts.sender.provider].flatMap((partyId) => partyId != null ? [partyId] : []),
855
+ transfer: {
856
+ sender: opts.sender,
857
+ receiver: opts.receiver,
858
+ amount: opts.amount,
859
+ instrumentId: {
860
+ admin: opts.instrumentAdmin,
861
+ id: opts.instrumentId
862
+ },
863
+ requestedAt: (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
864
+ executeBefore: (opts.expiryDate ?? new Date(Date.now() + 864e5)).toISOString(),
865
+ inputHoldingCids,
866
+ meta: { values: {
867
+ [TokenStandardService.MEMO_KEY]: opts.memo || "",
868
+ ...opts.meta?.values
869
+ } }
870
+ },
871
+ extraArgs: {
872
+ context: { values: {} },
873
+ meta: { values: {} }
874
+ }
875
+ };
876
+ }
877
+ async createTransfer(args, registryUrl, prefetched) {
878
+ const choiceArgs = await this.buildTransferChoiceArgs(args);
879
+ const { factoryId, choiceContext } = prefetched ?? await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/transfer-factory", {
880
+ choiceArguments: choiceArgs,
881
+ excludeDebugFields: true
882
+ });
883
+ return this.createTransferFromContext(factoryId, choiceArgs, choiceContext);
884
+ }
885
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
886
+ this.logger.debug("Creating transfer from pre-fetched context...");
887
+ choiceArgs.extraArgs.context = {
888
+ ...choiceContext.choiceContextData,
889
+ values: choiceContext.choiceContextData?.values ?? {}
890
+ };
891
+ return [{
892
+ templateId: TRANSFER_FACTORY_INTERFACE_ID_V2,
893
+ contractId: factoryId,
894
+ choice: "TransferFactory_Transfer",
895
+ choiceArgument: choiceArgs
896
+ }, choiceContext.disclosedContracts];
897
+ }
898
+ async rejectTransferInstruction(transferInstructionCid, actors, registryUrl) {
899
+ const ctx = await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/{transferInstructionId}/choice-contexts/reject", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
900
+ return [{
901
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID_V2,
902
+ contractId: transferInstructionCid,
903
+ choice: TransferInstruction$1.TransferInstruction_Reject.choiceName,
904
+ choiceArgument: {
905
+ actors,
906
+ extraArgs: {
907
+ context: ctx.choiceContextData,
908
+ meta: EMPTY_META
909
+ }
910
+ }
911
+ }, ctx.disclosedContracts ?? []];
912
+ }
913
+ async withdrawTransferInstruction(transferInstructionCid, actors, registryUrl) {
914
+ const ctx = await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/{transferInstructionId}/choice-contexts/withdraw", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
915
+ return [{
916
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID_V2,
917
+ contractId: transferInstructionCid,
918
+ choice: TransferInstruction$1.TransferInstruction_Withdraw.choiceName,
919
+ choiceArgument: {
920
+ actors,
921
+ extraArgs: {
922
+ context: ctx.choiceContextData,
923
+ meta: EMPTY_META
924
+ }
925
+ }
926
+ }, ctx.disclosedContracts ?? []];
927
+ }
928
+ async acceptTransferInstruction(transferInstructionCid, actors, registryUrl) {
929
+ const ctx = await this.core.getTokenStandardClientV2(registryUrl).post("/registry/transfer-instruction/v2/{transferInstructionId}/choice-contexts/accept", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
930
+ return [{
931
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID_V2,
932
+ contractId: transferInstructionCid,
933
+ choice: TransferInstruction$1.TransferInstruction_Accept.choiceName,
934
+ choiceArgument: {
935
+ actors,
936
+ extraArgs: {
937
+ context: ctx.choiceContextData,
938
+ meta: EMPTY_META
939
+ }
940
+ }
941
+ }, ctx.disclosedContracts ?? []];
942
+ }
943
+ };
944
944
  // src/token-standard-service.ts
945
945
  function isApiVersion(v) {
946
946
  return SUPPORTED_VERSIONS.includes(v);