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