@canton-network/core-token-standard-service 1.7.0 → 1.9.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,1150 +1,756 @@
1
- import { TokenStandardClient, HOLDING_INTERFACE_ID, FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID, ALLOCATION_FACTORY_INTERFACE_ID, ALLOCATION_INTERFACE_ID, ALLOCATION_INSTRUCTION_INTERFACE_ID, ALLOCATION_REQUEST_INTERFACE_ID, TRANSFER_FACTORY_INTERFACE_ID, TRANSFER_INSTRUCTION_INTERFACE_ID } from '@canton-network/core-token-standard';
2
- import { EventFilterBySetup } from '@canton-network/core-ledger-client-types';
3
- import { ACSReader } from '@canton-network/core-acs-reader';
4
- import { TransactionParser, renderTransaction, ensureInterfaceViewIsPresent, TokenStandardTransactionInterfaces } from '@canton-network/core-tx-parser';
5
- import { Decimal } from 'decimal.js';
6
-
7
- var __defProp = Object.defineProperty;
8
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
10
- var REQUESTED_AT_SKEW_MS = 6e4;
11
- var EMPTY_META = { values: {} };
12
- var CoreService = class _CoreService {
13
- constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
14
- this.ledgerProvider = ledgerProvider;
15
- this.logger = logger;
16
- this.accessTokenProvider = accessTokenProvider;
17
- this.isMasterUser = isMasterUser;
18
- }
19
- getTokenStandardClient(registryUrl) {
20
- return new TokenStandardClient(
21
- registryUrl,
22
- this.logger,
23
- this.accessTokenProvider
24
- );
25
- }
26
- async getInputHoldingsCids(options) {
27
- const { sender, instrumentAdmin, instrumentId } = options;
28
- const now = /* @__PURE__ */ new Date();
29
- if (options.inputUtxos && options.inputUtxos.length > 0) {
30
- return options.inputUtxos;
31
- }
32
- const senderHoldings = await this.listContractsByInterface(
33
- HOLDING_INTERFACE_ID,
34
- sender,
35
- void 0,
36
- void 0,
37
- options.continueUntilCompletion
38
- );
39
- if (senderHoldings.length === 0) {
40
- throw new Error(
41
- "Sender has no holdings, so transfer can't be executed."
42
- );
43
- }
44
- const unlockedSenderHoldings = senderHoldings.filter((utxo) => {
45
- const lock = utxo.interfaceViewValue.lock;
46
- if (!lock) return true;
47
- const expiresAt = lock.expiresAt;
48
- if (!expiresAt) return false;
49
- const expiresAtDate = new Date(expiresAt);
50
- return expiresAtDate <= now;
51
- });
52
- if (unlockedSenderHoldings.length > 100) {
53
- this.logger.warn(`Sender has more than 100 unlocked utxos.`);
54
- }
55
- const unlockedHoldingsForInstrument = instrumentAdmin && instrumentId ? await _CoreService.filterHoldingsByInstrument({
56
- holdings: unlockedSenderHoldings,
57
- instrumentAdmin,
58
- instrumentId
59
- }) : unlockedSenderHoldings;
60
- if (options.amount) {
61
- return _CoreService.getInputHoldingsCidsForAmount(
62
- options.amount,
63
- unlockedHoldingsForInstrument
64
- );
65
- } else {
66
- return unlockedHoldingsForInstrument.map((h) => h.contractId);
67
- }
68
- }
69
- static async filterHoldingsByInstrument(options) {
70
- const { holdings, instrumentAdmin, instrumentId } = options;
71
- return holdings.filter((utxo) => {
72
- return utxo.interfaceViewValue.instrumentId.id === instrumentId && utxo.interfaceViewValue.instrumentId.admin === instrumentAdmin;
73
- });
74
- }
75
- static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
76
- const exactAmount = unlockedSenderHoldings.find(
77
- (holding) => new Decimal(holding.interfaceViewValue.amount).equals(amount)
78
- );
79
- if (exactAmount) {
80
- return [exactAmount.contractId];
81
- }
82
- const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted(
83
- (a, b) => new Decimal(a.interfaceViewValue.amount).comparedTo(
84
- new Decimal(b.interfaceViewValue.amount)
85
- )
86
- );
87
- const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
88
- if (!largestHoldingAmount) {
89
- throw new Error(`Sender doesn't have any unlocked holdings`);
90
- }
91
- let currentSum = new Decimal(
92
- largestHoldingAmount.interfaceViewValue.amount
93
- );
94
- const cIds = [largestHoldingAmount.contractId];
95
- for (const h of sortedUnlockedSenderHoldings) {
96
- if (currentSum.greaterThanOrEqualTo(amount)) {
97
- break;
98
- }
99
- const currentHoldingAmount = new Decimal(
100
- h.interfaceViewValue.amount
101
- );
102
- currentSum = currentSum.plus(currentHoldingAmount);
103
- cIds.push(h.contractId);
104
- }
105
- if (currentSum.lessThan(amount)) {
106
- throw new Error(
107
- `Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount.minus(currentSum)}`
108
- );
109
- }
110
- if (cIds.length > 100) {
111
- throw new Error(
112
- `Exceeded the maximum of 100 utxos in 1 transaction`
113
- );
114
- }
115
- return cIds;
116
- }
117
- async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
118
- try {
119
- const ledgerEnd = offset ?? (await this.ledgerProvider.request({
120
- method: "ledgerApi",
121
- params: {
122
- resource: "/v2/state/ledger-end",
123
- requestMethod: "get"
124
- }
125
- })).offset;
126
- const options = {
127
- offset: ledgerEnd,
128
- interfaceIds: [interfaceId],
129
- parties: [partyId],
130
- filterByParty: true,
131
- continueUntilCompletion: Boolean(continueUntilCompletion)
132
- };
133
- if (limit !== void 0) {
134
- options.limit = limit;
135
- }
136
- this.logger.info(
137
- `continue to completion: ${Boolean(continueUntilCompletion)}`
138
- );
139
- const reader = new ACSReader(this.ledgerProvider);
140
- const acsResponses = await reader.raw.read(
141
- options
142
- );
143
- const isActiveContractEntry = (acsResponse) => acsResponse.contractEntry != null && "JsActiveContract" in acsResponse.contractEntry && acsResponse.contractEntry.JsActiveContract != null && acsResponse.contractEntry.JsActiveContract.createdEvent != null;
144
- const results = acsResponses.filter(isActiveContractEntry).map(
145
- (response) => this.toPrettyContract(
146
- interfaceId,
147
- response,
148
- ledgerEnd
149
- )
150
- );
151
- return results;
152
- } catch (err) {
153
- this.logger.error(
154
- `Failed to list contracts of interface ${interfaceId}`,
155
- err
156
- );
157
- throw err;
158
- }
159
- }
160
- async toPrettyTransactions(updates, partyId) {
161
- const isOffsetCheckpointUpdate = (updateResponse) => updateResponse.update != null && "OffsetCheckpoint" in updateResponse.update;
162
- const isTransactionUpdate = (updateResponse) => updateResponse.update != null && "Transaction" in updateResponse.update && !!updateResponse.update.Transaction?.value;
163
- const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map(
164
- (update) => update.update.OffsetCheckpoint.value.offset
165
- );
166
- const latestCheckpointOffset = offsetCheckpoints.length > 0 ? Math.max(...offsetCheckpoints) : 0;
167
- const transactions = await Promise.all(
168
- updates.filter(isTransactionUpdate).map(async (update) => {
169
- const txUpdate = update;
170
- const tx = txUpdate.update.Transaction.value;
171
- const parser = new TransactionParser(
172
- this.ledgerProvider,
173
- tx,
174
- partyId,
175
- this.isMasterUser
176
- );
177
- return await parser.parseTransaction();
178
- })
179
- );
180
- const transactionOffsets = transactions.map((tx) => tx.offset).filter((offset) => offset !== void 0);
181
- return {
182
- // OffsetCheckpoint can be anywhere... or not at all, maybe
183
- nextOffset: Math.max(
184
- latestCheckpointOffset,
185
- ...transactionOffsets.length > 0 ? transactionOffsets : [0]
186
- ),
187
- transactions: transactions.filter((tx) => tx.events.length > 0).map(renderTransaction)
188
- };
189
- }
190
- async toPrettyTransaction(getTransactionResponse, partyId) {
191
- const tx = getTransactionResponse.transaction;
192
- const parser = new TransactionParser(
193
- this.ledgerProvider,
194
- tx,
195
- partyId,
196
- this.isMasterUser
197
- );
198
- const parsedTx = await parser.parseTransaction();
199
- return renderTransaction(parsedTx);
200
- }
201
- async toPrettyTransferObjects(getTransactionResponse, partyId) {
202
- const tx = getTransactionResponse.transaction;
203
- const parser = new TransactionParser(
204
- this.ledgerProvider,
205
- tx,
206
- partyId,
207
- this.isMasterUser
208
- );
209
- return await parser.parseTransferObjects();
210
- }
211
- async toPrettyTransactionsPerParty(updates, parties) {
212
- const all = await Promise.all(
213
- parties.map(
214
- async (partyId) => [
215
- partyId,
216
- await this.toPrettyTransactions(updates, partyId)
217
- ]
218
- )
219
- );
220
- return new Map(all);
221
- }
222
- // returns object with JsActiveContract content
223
- // and contractId and interface view value extracted from it as separate fields for convenience
224
- toPrettyContract(interfaceId, response, offset) {
225
- const activeContract = response.contractEntry.JsActiveContract;
226
- const { createdEvent } = activeContract;
227
- return {
228
- contractId: createdEvent.contractId,
229
- activeContract,
230
- interfaceViewValue: ensureInterfaceViewIsPresent(
231
- createdEvent,
232
- interfaceId
233
- ).viewValue,
234
- fetchedAtOffset: offset
235
- };
236
- }
237
- toQualifiedMemberId(memberId) {
238
- if (!memberId) throw new Error("memberId is required");
239
- return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
240
- }
1
+ import { ALLOCATION_FACTORY_INTERFACE_ID, ALLOCATION_INSTRUCTION_INTERFACE_ID, ALLOCATION_INTERFACE_ID, ALLOCATION_REQUEST_INTERFACE_ID, FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID, HOLDING_INTERFACE_ID, TRANSFER_FACTORY_INTERFACE_ID, TRANSFER_INSTRUCTION_INTERFACE_ID, TokenStandardClient } from "@canton-network/core-token-standard";
2
+ import { EventFilterBySetup } from "@canton-network/core-ledger-client-types";
3
+ import { ACSReader } from "@canton-network/core-acs-reader";
4
+ import { TokenStandardTransactionInterfaces, TransactionParser, ensureInterfaceViewIsPresent, renderTransaction } from "@canton-network/core-tx-parser";
5
+ import { Decimal } from "decimal.js";
6
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/typeof.js
7
+ function _typeof(o) {
8
+ "@babel/helpers - typeof";
9
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
10
+ return typeof o;
11
+ } : function(o) {
12
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
13
+ }, _typeof(o);
14
+ }
15
+ //#endregion
16
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPrimitive.js
17
+ function toPrimitive(t, r) {
18
+ if ("object" != _typeof(t) || !t) return t;
19
+ var e = t[Symbol.toPrimitive];
20
+ if (void 0 !== e) {
21
+ var i = e.call(t, r || "default");
22
+ if ("object" != _typeof(i)) return i;
23
+ throw new TypeError("@@toPrimitive must return a primitive value.");
24
+ }
25
+ return ("string" === r ? String : Number)(t);
26
+ }
27
+ //#endregion
28
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/toPropertyKey.js
29
+ function toPropertyKey(t) {
30
+ var i = toPrimitive(t, "string");
31
+ return "symbol" == _typeof(i) ? i : i + "";
32
+ }
33
+ //#endregion
34
+ //#region \0@oxc-project+runtime@0.142.0/helpers/esm/defineProperty.js
35
+ function _defineProperty(e, r, t) {
36
+ return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
37
+ value: t,
38
+ enumerable: !0,
39
+ configurable: !0,
40
+ writable: !0
41
+ }) : e[r] = t, e;
42
+ }
43
+ //#endregion
44
+ //#region src/token-standard-service.ts
45
+ const REQUESTED_AT_SKEW_MS = 6e4;
46
+ const EMPTY_META = { values: {} };
47
+ var CoreService = class CoreService {
48
+ constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
49
+ this.ledgerProvider = ledgerProvider;
50
+ this.logger = logger;
51
+ this.accessTokenProvider = accessTokenProvider;
52
+ this.isMasterUser = isMasterUser;
53
+ }
54
+ getTokenStandardClient(registryUrl) {
55
+ return new TokenStandardClient(registryUrl, this.logger, this.accessTokenProvider);
56
+ }
57
+ async getInputHoldingsCids(options) {
58
+ const { sender, instrumentAdmin, instrumentId } = options;
59
+ const now = /* @__PURE__ */ new Date();
60
+ if (options.inputUtxos && options.inputUtxos.length > 0) return options.inputUtxos;
61
+ const senderHoldings = await this.listContractsByInterface(HOLDING_INTERFACE_ID, sender, void 0, void 0, options.continueUntilCompletion);
62
+ if (senderHoldings.length === 0) throw new Error("Sender has no holdings, so transfer can't be executed.");
63
+ const unlockedSenderHoldings = senderHoldings.filter((utxo) => {
64
+ const lock = utxo.interfaceViewValue.lock;
65
+ if (!lock) return true;
66
+ const expiresAt = lock.expiresAt;
67
+ if (!expiresAt) return false;
68
+ return new Date(expiresAt) <= now;
69
+ });
70
+ if (unlockedSenderHoldings.length > 100) this.logger.warn(`Sender has more than 100 unlocked utxos.`);
71
+ const unlockedHoldingsForInstrument = instrumentAdmin && instrumentId ? await CoreService.filterHoldingsByInstrument({
72
+ holdings: unlockedSenderHoldings,
73
+ instrumentAdmin,
74
+ instrumentId
75
+ }) : unlockedSenderHoldings;
76
+ if (options.amount) return CoreService.getInputHoldingsCidsForAmount(options.amount, unlockedHoldingsForInstrument);
77
+ else return unlockedHoldingsForInstrument.map((h) => h.contractId);
78
+ }
79
+ static async filterHoldingsByInstrument(options) {
80
+ const { holdings, instrumentAdmin, instrumentId } = options;
81
+ return holdings.filter((utxo) => {
82
+ return utxo.interfaceViewValue.instrumentId.id === instrumentId && utxo.interfaceViewValue.instrumentId.admin === instrumentAdmin;
83
+ });
84
+ }
85
+ static async getInputHoldingsCidsForAmount(amount, unlockedSenderHoldings) {
86
+ const exactAmount = unlockedSenderHoldings.find((holding) => new Decimal(holding.interfaceViewValue.amount).equals(amount));
87
+ if (exactAmount) return [exactAmount.contractId];
88
+ const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted((a, b) => new Decimal(a.interfaceViewValue.amount).comparedTo(new Decimal(b.interfaceViewValue.amount)));
89
+ const largestHoldingAmount = sortedUnlockedSenderHoldings.pop();
90
+ if (!largestHoldingAmount) throw new Error(`Sender doesn't have any unlocked holdings`);
91
+ let currentSum = new Decimal(largestHoldingAmount.interfaceViewValue.amount);
92
+ const cIds = [largestHoldingAmount.contractId];
93
+ for (const h of sortedUnlockedSenderHoldings) {
94
+ if (currentSum.greaterThanOrEqualTo(amount)) break;
95
+ const currentHoldingAmount = new Decimal(h.interfaceViewValue.amount);
96
+ currentSum = currentSum.plus(currentHoldingAmount);
97
+ cIds.push(h.contractId);
98
+ }
99
+ if (currentSum.lessThan(amount)) throw new Error(`Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount.minus(currentSum)}`);
100
+ if (cIds.length > 100) throw new Error(`Exceeded the maximum of 100 utxos in 1 transaction`);
101
+ return cIds;
102
+ }
103
+ async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
104
+ try {
105
+ const ledgerEnd = offset ?? (await this.ledgerProvider.request({
106
+ method: "ledgerApi",
107
+ params: {
108
+ resource: "/v2/state/ledger-end",
109
+ requestMethod: "get"
110
+ }
111
+ })).offset;
112
+ const options = {
113
+ offset: ledgerEnd,
114
+ interfaceIds: [interfaceId],
115
+ parties: [partyId],
116
+ filterByParty: true,
117
+ continueUntilCompletion: Boolean(continueUntilCompletion)
118
+ };
119
+ if (limit !== void 0) options.limit = limit;
120
+ this.logger.info(`continue to completion: ${Boolean(continueUntilCompletion)}`);
121
+ const acsResponses = await new ACSReader(this.ledgerProvider).raw.read(options);
122
+ const isActiveContractEntry = (acsResponse) => acsResponse.contractEntry != null && "JsActiveContract" in acsResponse.contractEntry && acsResponse.contractEntry.JsActiveContract != null && acsResponse.contractEntry.JsActiveContract.createdEvent != null;
123
+ return acsResponses.filter(isActiveContractEntry).map((response) => this.toPrettyContract(interfaceId, response, ledgerEnd));
124
+ } catch (err) {
125
+ this.logger.error(`Failed to list contracts of interface ${interfaceId}`, err);
126
+ throw err;
127
+ }
128
+ }
129
+ async toPrettyTransactions(updates, partyId) {
130
+ const isOffsetCheckpointUpdate = (updateResponse) => updateResponse.update != null && "OffsetCheckpoint" in updateResponse.update;
131
+ const isTransactionUpdate = (updateResponse) => updateResponse.update != null && "Transaction" in updateResponse.update && !!updateResponse.update.Transaction?.value;
132
+ const offsetCheckpoints = updates.filter(isOffsetCheckpointUpdate).map((update) => update.update.OffsetCheckpoint.value.offset);
133
+ const latestCheckpointOffset = offsetCheckpoints.length > 0 ? Math.max(...offsetCheckpoints) : 0;
134
+ const transactions = await Promise.all(updates.filter(isTransactionUpdate).map(async (update) => {
135
+ const tx = update.update.Transaction.value;
136
+ return await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
137
+ }));
138
+ const transactionOffsets = transactions.map((tx) => tx.offset).filter((offset) => offset !== void 0);
139
+ return {
140
+ nextOffset: Math.max(latestCheckpointOffset, ...transactionOffsets.length > 0 ? transactionOffsets : [0]),
141
+ transactions: transactions.filter((tx) => tx.events.length > 0).map(renderTransaction)
142
+ };
143
+ }
144
+ async toPrettyTransaction(getTransactionResponse, partyId) {
145
+ const tx = getTransactionResponse.transaction;
146
+ const parsedTx = await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
147
+ return renderTransaction(parsedTx);
148
+ }
149
+ async toPrettyTransferObjects(getTransactionResponse, partyId) {
150
+ const tx = getTransactionResponse.transaction;
151
+ return await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransferObjects();
152
+ }
153
+ async toPrettyTransactionsPerParty(updates, parties) {
154
+ const all = await Promise.all(parties.map(async (partyId) => [partyId, await this.toPrettyTransactions(updates, partyId)]));
155
+ return new Map(all);
156
+ }
157
+ toPrettyContract(interfaceId, response, offset) {
158
+ const activeContract = response.contractEntry.JsActiveContract;
159
+ const { createdEvent } = activeContract;
160
+ return {
161
+ contractId: createdEvent.contractId,
162
+ activeContract,
163
+ interfaceViewValue: ensureInterfaceViewIsPresent(createdEvent, interfaceId).viewValue,
164
+ fetchedAtOffset: offset
165
+ };
166
+ }
167
+ toQualifiedMemberId(memberId) {
168
+ if (!memberId) throw new Error("memberId is required");
169
+ return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`;
170
+ }
241
171
  };
242
172
  var AllocationService = class {
243
- constructor(core, logger) {
244
- this.core = core;
245
- this.logger = logger;
246
- }
247
- async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
248
- const allocationSpecificationNormalized = {
249
- ...allocationSpecification,
250
- settlement: {
251
- ...allocationSpecification.settlement,
252
- meta: allocationSpecification.settlement.meta ?? { values: {} }
253
- },
254
- transferLeg: {
255
- ...allocationSpecification.transferLeg,
256
- meta: allocationSpecification.transferLeg.meta ?? {
257
- values: {}
258
- }
259
- }
260
- };
261
- const inputHoldingCids = await this.core.getInputHoldingsCids({
262
- sender: allocationSpecificationNormalized.transferLeg.sender,
263
- inputUtxos: inputUtxos ?? [],
264
- instrumentAdmin: allocationSpecificationNormalized.transferLeg.instrumentId.admin,
265
- instrumentId: allocationSpecificationNormalized.transferLeg.instrumentId.id
266
- });
267
- return {
268
- expectedAdmin,
269
- allocation: allocationSpecificationNormalized,
270
- requestedAt: requestedAt ?? new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),
271
- inputHoldingCids,
272
- extraArgs: {
273
- context: { values: {} },
274
- meta: { values: {} }
275
- }
276
- };
277
- }
278
- async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
279
- return this.core.getTokenStandardClient(registryUrl).post("/registry/allocation-instruction/v1/allocation-factory", {
280
- choiceArguments: choiceArgs,
281
- excludeDebugFields
282
- });
283
- }
284
- async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
285
- choiceArgs.extraArgs.context = {
286
- ...choiceContext.choiceContextData,
287
- values: choiceContext.choiceContextData?.values ?? {}
288
- };
289
- const exercise = {
290
- templateId: ALLOCATION_FACTORY_INTERFACE_ID,
291
- contractId: factoryId,
292
- choice: "AllocationFactory_Allocate",
293
- choiceArgument: choiceArgs
294
- };
295
- return [exercise, choiceContext.disclosedContracts];
296
- }
297
- async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
298
- const choiceArgs = await this.buildAllocationFactoryChoiceArgs(
299
- allocationSpecification,
300
- expectedAdmin,
301
- inputUtxos,
302
- requestedAt
303
- );
304
- if (prefetchedRegistryChoiceContext) {
305
- return this.createAllocationInstructionFromContext(
306
- prefetchedRegistryChoiceContext.factoryId,
307
- choiceArgs,
308
- prefetchedRegistryChoiceContext.choiceContext
309
- );
310
- }
311
- const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(
312
- registryUrl,
313
- choiceArgs
314
- );
315
- return this.createAllocationInstructionFromContext(
316
- factoryId,
317
- choiceArgs,
318
- choiceContext
319
- );
320
- }
321
- buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
322
- const exercise = {
323
- templateId,
324
- contractId,
325
- choice,
326
- choiceArgument: {
327
- extraArgs: {
328
- context: choiceContext.choiceContextData,
329
- meta: EMPTY_META
330
- }
331
- }
332
- };
333
- return [exercise, choiceContext.disclosedContracts ?? []];
334
- }
335
- async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
336
- return this.core.getTokenStandardClient(registryUrl).post(
337
- "/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer",
338
- {
339
- excludeDebugFields: true
340
- },
341
- {
342
- path: {
343
- allocationId
344
- }
345
- }
346
- );
347
- }
348
- createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
349
- return this.buildAllocationExerciseWithContext(
350
- ALLOCATION_INTERFACE_ID,
351
- allocationCid,
352
- "Allocation_ExecuteTransfer",
353
- choiceContext
354
- );
355
- }
356
- async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
357
- if (prefetchedRegistryChoiceContext) {
358
- return this.createExecuteTransferAllocationFromContext(
359
- allocationCid,
360
- prefetchedRegistryChoiceContext
361
- );
362
- }
363
- const choiceContext = await this.fetchExecuteTransferChoiceContext(
364
- allocationCid,
365
- registryUrl
366
- );
367
- return this.createExecuteTransferAllocationFromContext(
368
- allocationCid,
369
- choiceContext
370
- );
371
- }
372
- async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
373
- return this.core.getTokenStandardClient(registryUrl).post(
374
- "/registry/allocations/v1/{allocationId}/choice-contexts/withdraw",
375
- {
376
- excludeDebugFields: true
377
- },
378
- { path: { allocationId: allocationCid } }
379
- );
380
- }
381
- createWithdrawAllocationFromContext(allocationCid, choiceContext) {
382
- return this.buildAllocationExerciseWithContext(
383
- ALLOCATION_INTERFACE_ID,
384
- allocationCid,
385
- "Allocation_Withdraw",
386
- choiceContext
387
- );
388
- }
389
- async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
390
- if (prefetchedRegistryChoiceContext) {
391
- return this.createWithdrawAllocationFromContext(
392
- allocationCid,
393
- prefetchedRegistryChoiceContext
394
- );
395
- }
396
- const choiceContext = await this.fetchWithdrawAllocationChoiceContext(
397
- allocationCid,
398
- registryUrl
399
- );
400
- return this.createWithdrawAllocationFromContext(
401
- allocationCid,
402
- choiceContext
403
- );
404
- }
405
- async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
406
- return this.core.getTokenStandardClient(registryUrl).post(
407
- "/registry/allocations/v1/{allocationId}/choice-contexts/cancel",
408
- {
409
- excludeDebugFields: true
410
- },
411
- { path: { allocationId: allocationCid } }
412
- );
413
- }
414
- createCancelAllocationFromContext(allocationCid, choiceContext) {
415
- return this.buildAllocationExerciseWithContext(
416
- ALLOCATION_INTERFACE_ID,
417
- allocationCid,
418
- "Allocation_Cancel",
419
- choiceContext
420
- );
421
- }
422
- async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
423
- if (prefetchedRegistryChoiceContext) {
424
- return this.createCancelAllocationFromContext(
425
- allocationCid,
426
- prefetchedRegistryChoiceContext
427
- );
428
- }
429
- const choiceContext = await this.fetchCancelAllocationChoiceContext(
430
- allocationCid,
431
- registryUrl
432
- );
433
- return this.createCancelAllocationFromContext(
434
- allocationCid,
435
- choiceContext
436
- );
437
- }
438
- async createWithdrawAllocationInstruction(allocationInstructionCid) {
439
- const exercise = {
440
- templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
441
- contractId: allocationInstructionCid,
442
- choice: "AllocationInstruction_Withdraw",
443
- choiceArgument: {
444
- extraArgs: {
445
- context: { values: {} },
446
- meta: { values: {} }
447
- }
448
- }
449
- };
450
- return [exercise, []];
451
- }
452
- async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
453
- const exercise = {
454
- templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
455
- contractId: allocationInstructionCid,
456
- choice: "AllocationInstruction_Update",
457
- choiceArgument: {
458
- extraActors,
459
- extraArgs: {
460
- context: { values: extraArgsContext },
461
- meta: { values: extraArgsMeta }
462
- }
463
- }
464
- };
465
- return [exercise, []];
466
- }
467
- async createRejectAllocationRequest(allocationRequestCid, actor) {
468
- const exercise = {
469
- templateId: ALLOCATION_REQUEST_INTERFACE_ID,
470
- contractId: allocationRequestCid,
471
- choice: "AllocationRequest_Reject",
472
- choiceArgument: {
473
- actor,
474
- extraArgs: {
475
- context: { values: {} },
476
- meta: { values: {} }
477
- }
478
- }
479
- };
480
- return [exercise, []];
481
- }
482
- async createWithdrawAllocationRequest(allocationRequestCid) {
483
- const exercise = {
484
- templateId: ALLOCATION_REQUEST_INTERFACE_ID,
485
- contractId: allocationRequestCid,
486
- choice: "AllocationRequest_Withdraw",
487
- choiceArgument: {
488
- extraArgs: {
489
- context: { values: {} },
490
- meta: { values: {} }
491
- }
492
- }
493
- };
494
- return [exercise, []];
495
- }
173
+ constructor(core, logger) {
174
+ this.core = core;
175
+ this.logger = logger;
176
+ }
177
+ async buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt) {
178
+ const allocationSpecificationNormalized = {
179
+ ...allocationSpecification,
180
+ settlement: {
181
+ ...allocationSpecification.settlement,
182
+ meta: allocationSpecification.settlement.meta ?? { values: {} }
183
+ },
184
+ transferLeg: {
185
+ ...allocationSpecification.transferLeg,
186
+ meta: allocationSpecification.transferLeg.meta ?? { values: {} }
187
+ }
188
+ };
189
+ const inputHoldingCids = await this.core.getInputHoldingsCids({
190
+ sender: allocationSpecificationNormalized.transferLeg.sender,
191
+ inputUtxos: inputUtxos ?? [],
192
+ instrumentAdmin: allocationSpecificationNormalized.transferLeg.instrumentId.admin,
193
+ instrumentId: allocationSpecificationNormalized.transferLeg.instrumentId.id
194
+ });
195
+ return {
196
+ expectedAdmin,
197
+ allocation: allocationSpecificationNormalized,
198
+ requestedAt: requestedAt ?? (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
199
+ inputHoldingCids,
200
+ extraArgs: {
201
+ context: { values: {} },
202
+ meta: { values: {} }
203
+ }
204
+ };
205
+ }
206
+ async fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
207
+ return this.core.getTokenStandardClient(registryUrl).post("/registry/allocation-instruction/v1/allocation-factory", {
208
+ choiceArguments: choiceArgs,
209
+ excludeDebugFields
210
+ });
211
+ }
212
+ async createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext) {
213
+ choiceArgs.extraArgs.context = {
214
+ ...choiceContext.choiceContextData,
215
+ values: choiceContext.choiceContextData?.values ?? {}
216
+ };
217
+ return [{
218
+ templateId: ALLOCATION_FACTORY_INTERFACE_ID,
219
+ contractId: factoryId,
220
+ choice: "AllocationFactory_Allocate",
221
+ choiceArgument: choiceArgs
222
+ }, choiceContext.disclosedContracts];
223
+ }
224
+ async createAllocationInstruction(allocationSpecification, expectedAdmin, registryUrl, inputUtxos, requestedAt, prefetchedRegistryChoiceContext) {
225
+ const choiceArgs = await this.buildAllocationFactoryChoiceArgs(allocationSpecification, expectedAdmin, inputUtxos, requestedAt);
226
+ if (prefetchedRegistryChoiceContext) return this.createAllocationInstructionFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
227
+ const { factoryId, choiceContext } = await this.fetchAllocationFactoryChoiceContext(registryUrl, choiceArgs);
228
+ return this.createAllocationInstructionFromContext(factoryId, choiceArgs, choiceContext);
229
+ }
230
+ buildAllocationExerciseWithContext(templateId, contractId, choice, choiceContext) {
231
+ return [{
232
+ templateId,
233
+ contractId,
234
+ choice,
235
+ choiceArgument: { extraArgs: {
236
+ context: choiceContext.choiceContextData,
237
+ meta: EMPTY_META
238
+ } }
239
+ }, choiceContext.disclosedContracts ?? []];
240
+ }
241
+ async fetchExecuteTransferChoiceContext(allocationId, registryUrl) {
242
+ return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer", { excludeDebugFields: true }, { path: { allocationId } });
243
+ }
244
+ createExecuteTransferAllocationFromContext(allocationCid, choiceContext) {
245
+ return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_ExecuteTransfer", choiceContext);
246
+ }
247
+ async createExecuteTransferAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
248
+ if (prefetchedRegistryChoiceContext) return this.createExecuteTransferAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
249
+ const choiceContext = await this.fetchExecuteTransferChoiceContext(allocationCid, registryUrl);
250
+ return this.createExecuteTransferAllocationFromContext(allocationCid, choiceContext);
251
+ }
252
+ async fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl) {
253
+ return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/withdraw", { excludeDebugFields: true }, { path: { allocationId: allocationCid } });
254
+ }
255
+ createWithdrawAllocationFromContext(allocationCid, choiceContext) {
256
+ return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_Withdraw", choiceContext);
257
+ }
258
+ async createWithdrawAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
259
+ if (prefetchedRegistryChoiceContext) return this.createWithdrawAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
260
+ const choiceContext = await this.fetchWithdrawAllocationChoiceContext(allocationCid, registryUrl);
261
+ return this.createWithdrawAllocationFromContext(allocationCid, choiceContext);
262
+ }
263
+ async fetchCancelAllocationChoiceContext(allocationCid, registryUrl) {
264
+ return this.core.getTokenStandardClient(registryUrl).post("/registry/allocations/v1/{allocationId}/choice-contexts/cancel", { excludeDebugFields: true }, { path: { allocationId: allocationCid } });
265
+ }
266
+ createCancelAllocationFromContext(allocationCid, choiceContext) {
267
+ return this.buildAllocationExerciseWithContext(ALLOCATION_INTERFACE_ID, allocationCid, "Allocation_Cancel", choiceContext);
268
+ }
269
+ async createCancelAllocation(allocationCid, registryUrl, prefetchedRegistryChoiceContext) {
270
+ if (prefetchedRegistryChoiceContext) return this.createCancelAllocationFromContext(allocationCid, prefetchedRegistryChoiceContext);
271
+ const choiceContext = await this.fetchCancelAllocationChoiceContext(allocationCid, registryUrl);
272
+ return this.createCancelAllocationFromContext(allocationCid, choiceContext);
273
+ }
274
+ async createWithdrawAllocationInstruction(allocationInstructionCid) {
275
+ return [{
276
+ templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
277
+ contractId: allocationInstructionCid,
278
+ choice: "AllocationInstruction_Withdraw",
279
+ choiceArgument: { extraArgs: {
280
+ context: { values: {} },
281
+ meta: { values: {} }
282
+ } }
283
+ }, []];
284
+ }
285
+ async createUpdateAllocationInstruction(allocationInstructionCid, extraActors = [], extraArgsContext = {}, extraArgsMeta = {}) {
286
+ return [{
287
+ templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,
288
+ contractId: allocationInstructionCid,
289
+ choice: "AllocationInstruction_Update",
290
+ choiceArgument: {
291
+ extraActors,
292
+ extraArgs: {
293
+ context: { values: extraArgsContext },
294
+ meta: { values: extraArgsMeta }
295
+ }
296
+ }
297
+ }, []];
298
+ }
299
+ async createRejectAllocationRequest(allocationRequestCid, actor) {
300
+ return [{
301
+ templateId: ALLOCATION_REQUEST_INTERFACE_ID,
302
+ contractId: allocationRequestCid,
303
+ choice: "AllocationRequest_Reject",
304
+ choiceArgument: {
305
+ actor,
306
+ extraArgs: {
307
+ context: { values: {} },
308
+ meta: { values: {} }
309
+ }
310
+ }
311
+ }, []];
312
+ }
313
+ async createWithdrawAllocationRequest(allocationRequestCid) {
314
+ return [{
315
+ templateId: ALLOCATION_REQUEST_INTERFACE_ID,
316
+ contractId: allocationRequestCid,
317
+ choice: "AllocationRequest_Withdraw",
318
+ choiceArgument: { extraArgs: {
319
+ context: { values: {} },
320
+ meta: { values: {} }
321
+ } }
322
+ }, []];
323
+ }
496
324
  };
497
325
  var TransferService = class {
498
- constructor(core, logger) {
499
- this.core = core;
500
- this.logger = logger;
501
- }
502
- async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion) {
503
- const inputHoldingCids = await this.core.getInputHoldingsCids(
504
- {
505
- sender,
506
- instrumentAdmin,
507
- instrumentId,
508
- inputUtxos: inputUtxos ?? [],
509
- amount: new Decimal(amount),
510
- continueUntilCompletion: continueUntilCompletion ?? false
511
- }
512
- );
513
- return {
514
- expectedAdmin: instrumentAdmin,
515
- transfer: {
516
- sender,
517
- receiver,
518
- amount,
519
- instrumentId: { admin: instrumentAdmin, id: instrumentId },
520
- requestedAt: new Date(
521
- Date.now() - REQUESTED_AT_SKEW_MS
522
- ).toISOString(),
523
- executeBefore: (expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1e3)).toISOString(),
524
- inputHoldingCids,
525
- meta: {
526
- values: {
527
- [TokenStandardService.MEMO_KEY]: memo || "",
528
- ...meta?.values
529
- }
530
- }
531
- },
532
- extraArgs: {
533
- context: { values: {} },
534
- meta: { values: {} }
535
- }
536
- };
537
- }
538
- async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
539
- return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
540
- choiceArguments: choiceArgs,
541
- excludeDebugFields
542
- });
543
- }
544
- async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
545
- this.logger.debug("Creating transfer from pre-fetched context...");
546
- choiceArgs.extraArgs.context = {
547
- ...choiceContext.choiceContextData,
548
- values: choiceContext.choiceContextData?.values ?? {}
549
- };
550
- const exercise = {
551
- templateId: TRANSFER_FACTORY_INTERFACE_ID,
552
- contractId: factoryId,
553
- choice: "TransferFactory_Transfer",
554
- choiceArgument: choiceArgs
555
- };
556
- return [exercise, choiceContext.disclosedContracts];
557
- }
558
- // TODO: use named parameters
559
- async createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext, continueUntilCompletion) {
560
- try {
561
- const choiceArgs = await this.buildTransferChoiceArgs(
562
- sender,
563
- receiver,
564
- amount,
565
- instrumentAdmin,
566
- instrumentId,
567
- inputUtxos,
568
- memo,
569
- expiryDate,
570
- meta,
571
- continueUntilCompletion
572
- );
573
- if (prefetchedRegistryChoiceContext) {
574
- return this.createTransferFromContext(
575
- prefetchedRegistryChoiceContext.factoryId,
576
- choiceArgs,
577
- prefetchedRegistryChoiceContext.choiceContext
578
- );
579
- }
580
- const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(
581
- registryUrl,
582
- choiceArgs
583
- );
584
- return this.createTransferFromContext(
585
- factoryId,
586
- choiceArgs,
587
- choiceContext
588
- );
589
- } catch (e) {
590
- this.logger.error("Failed to execute transfer:", e);
591
- throw e;
592
- }
593
- }
594
- async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
595
- const client = this.core.getTokenStandardClient(registryUrl);
596
- const choiceContext = await client.post(
597
- "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept",
598
- {
599
- excludeDebugFields: true
600
- },
601
- {
602
- path: {
603
- transferInstructionId: transferInstructionCid
604
- }
605
- }
606
- );
607
- return {
608
- choiceContextData: choiceContext.choiceContextData,
609
- disclosedContracts: choiceContext.disclosedContracts
610
- };
611
- }
612
- async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
613
- try {
614
- const exercise = {
615
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
616
- contractId: transferInstructionCid,
617
- choice: "TransferInstruction_Accept",
618
- choiceArgument: {
619
- extraArgs: {
620
- context: choiceContext.choiceContextData,
621
- meta: { values: {} }
622
- }
623
- }
624
- };
625
- return [exercise, choiceContext.disclosedContracts];
626
- } catch (e) {
627
- this.logger.error(
628
- "Failed to create accept transfer instruction:",
629
- e
630
- );
631
- throw e;
632
- }
633
- }
634
- async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
635
- const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(
636
- transferInstructionCid,
637
- registryUrl.href
638
- );
639
- const choiceArgs = {
640
- cid: acceptTransferInstructionContext.contractId,
641
- proxyArg: {
642
- featuredAppRightCid,
643
- beneficiaries,
644
- choiceArg: acceptTransferInstructionContext.choiceArgument
645
- }
646
- };
647
- return [
648
- {
649
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
650
- contractId: proxyCid,
651
- choice: "DelegateProxy_TransferInstruction_Accept",
652
- choiceArgument: choiceArgs
653
- },
654
- disclosedContracts
655
- ];
656
- }
657
- async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
658
- const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(
659
- transferInstructionCid,
660
- registryUrl.href
661
- );
662
- const choiceArgs = {
663
- cid: rejectTransferInstructionContext.contractId,
664
- proxyArg: {
665
- featuredAppRightCid,
666
- beneficiaries,
667
- choiceArg: rejectTransferInstructionContext.choiceArgument
668
- }
669
- };
670
- return [
671
- {
672
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
673
- contractId: proxyCid,
674
- choice: "DelegateProxy_TransferInstruction_Reject",
675
- choiceArgument: choiceArgs
676
- },
677
- disclosedContracts
678
- ];
679
- }
680
- async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
681
- const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(
682
- transferInstructionCid,
683
- registryUrl.href
684
- );
685
- const sumOfWeights = beneficiaries.reduce(
686
- (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
687
- 0
688
- );
689
- if (sumOfWeights > 1) {
690
- throw new Error("Sum of beneficiary weights is larger than 1.");
691
- }
692
- const choiceArgs = {
693
- cid: withdrawTransferInstructionContext.contractId,
694
- proxyArg: {
695
- featuredAppRightCid,
696
- beneficiaries,
697
- choiceArg: withdrawTransferInstructionContext.choiceArgument
698
- }
699
- };
700
- return [
701
- {
702
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
703
- contractId: proxyCid,
704
- choice: "DelegateProxy_TransferInstruction_Withdraw",
705
- choiceArgument: choiceArgs
706
- },
707
- disclosedContracts
708
- ];
709
- }
710
- async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
711
- if (prefetchedRegistryChoiceContext) {
712
- return this.createAcceptTransferInstructionFromContext(
713
- transferInstructionCid,
714
- {
715
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
716
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
717
- }
718
- );
719
- }
720
- const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(
721
- transferInstructionCid,
722
- registryUrl
723
- );
724
- return this.createAcceptTransferInstructionFromContext(
725
- transferInstructionCid,
726
- choiceContext
727
- );
728
- }
729
- async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
730
- const client = this.core.getTokenStandardClient(registryUrl);
731
- const choiceContext = await client.post(
732
- "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject",
733
- {
734
- excludeDebugFields: true
735
- },
736
- {
737
- path: {
738
- transferInstructionId: transferInstructionCid
739
- }
740
- }
741
- );
742
- return {
743
- choiceContextData: choiceContext.choiceContextData,
744
- disclosedContracts: choiceContext.disclosedContracts
745
- };
746
- }
747
- async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
748
- try {
749
- const exercise = {
750
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
751
- contractId: transferInstructionCid,
752
- choice: "TransferInstruction_Reject",
753
- choiceArgument: {
754
- extraArgs: {
755
- context: choiceContext.choiceContextData,
756
- meta: { values: {} }
757
- }
758
- }
759
- };
760
- return [exercise, choiceContext.disclosedContracts];
761
- } catch (e) {
762
- this.logger.error(
763
- "Failed to create reject transfer instruction:",
764
- e
765
- );
766
- throw e;
767
- }
768
- }
769
- async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
770
- if (prefetchedRegistryChoiceContext) {
771
- return this.createRejectTransferInstructionFromContext(
772
- transferInstructionCid,
773
- {
774
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
775
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
776
- }
777
- );
778
- }
779
- const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(
780
- transferInstructionCid,
781
- registryUrl
782
- );
783
- return this.createRejectTransferInstructionFromContext(
784
- transferInstructionCid,
785
- choiceContext
786
- );
787
- }
788
- async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
789
- const client = this.core.getTokenStandardClient(registryUrl);
790
- const choiceContext = await client.post(
791
- "/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw",
792
- {
793
- excludeDebugFields: true
794
- },
795
- {
796
- path: {
797
- transferInstructionId: transferInstructionCid
798
- }
799
- }
800
- );
801
- return {
802
- choiceContextData: choiceContext.choiceContextData,
803
- disclosedContracts: choiceContext.disclosedContracts
804
- };
805
- }
806
- async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
807
- try {
808
- const exercise = {
809
- templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
810
- contractId: transferInstructionCid,
811
- choice: "TransferInstruction_Withdraw",
812
- choiceArgument: {
813
- extraArgs: {
814
- context: choiceContext.choiceContextData,
815
- meta: { values: {} }
816
- }
817
- }
818
- };
819
- return [exercise, choiceContext.disclosedContracts];
820
- } catch (e) {
821
- this.logger.error(
822
- "Failed to create withdraw transfer instruction:",
823
- e
824
- );
825
- throw e;
826
- }
827
- }
828
- async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
829
- if (prefetchedRegistryChoiceContext) {
830
- return this.createWithdrawTransferInstructionFromContext(
831
- transferInstructionCid,
832
- {
833
- choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
834
- disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
835
- }
836
- );
837
- }
838
- const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(
839
- transferInstructionCid,
840
- registryUrl
841
- );
842
- return this.createWithdrawTransferInstructionFromContext(
843
- transferInstructionCid,
844
- choiceContext
845
- );
846
- }
847
- async createTransferInstruction(transferInstructionCid, registryUrl, instructionChoice, prefetchedRegistryChoiceContext) {
848
- switch (instructionChoice) {
849
- case "Accept":
850
- return this.createAcceptTransferInstruction(
851
- transferInstructionCid,
852
- registryUrl,
853
- prefetchedRegistryChoiceContext
854
- );
855
- case "Reject":
856
- return this.createRejectTransferInstruction(
857
- transferInstructionCid,
858
- registryUrl,
859
- prefetchedRegistryChoiceContext
860
- );
861
- case "Withdraw":
862
- return this.createWithdrawTransferInstruction(
863
- transferInstructionCid,
864
- registryUrl,
865
- prefetchedRegistryChoiceContext
866
- );
867
- }
868
- }
326
+ constructor(core, logger) {
327
+ this.core = core;
328
+ this.logger = logger;
329
+ }
330
+ async buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion) {
331
+ const inputHoldingCids = await this.core.getInputHoldingsCids({
332
+ sender,
333
+ instrumentAdmin,
334
+ instrumentId,
335
+ inputUtxos: inputUtxos ?? [],
336
+ amount: new Decimal(amount),
337
+ continueUntilCompletion: continueUntilCompletion ?? false
338
+ });
339
+ return {
340
+ expectedAdmin: instrumentAdmin,
341
+ transfer: {
342
+ sender,
343
+ receiver,
344
+ amount,
345
+ instrumentId: {
346
+ admin: instrumentAdmin,
347
+ id: instrumentId
348
+ },
349
+ requestedAt: (/* @__PURE__ */ new Date(Date.now() - REQUESTED_AT_SKEW_MS)).toISOString(),
350
+ executeBefore: (expiryDate ?? new Date(Date.now() + 864e5)).toISOString(),
351
+ inputHoldingCids,
352
+ meta: { values: {
353
+ [TokenStandardService.MEMO_KEY]: memo || "",
354
+ ...meta?.values
355
+ } }
356
+ },
357
+ extraArgs: {
358
+ context: { values: {} },
359
+ meta: { values: {} }
360
+ }
361
+ };
362
+ }
363
+ async fetchTransferFactoryChoiceContext(registryUrl, choiceArgs, excludeDebugFields = true) {
364
+ return await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/transfer-factory", {
365
+ choiceArguments: choiceArgs,
366
+ excludeDebugFields
367
+ });
368
+ }
369
+ async createTransferFromContext(factoryId, choiceArgs, choiceContext) {
370
+ this.logger.debug("Creating transfer from pre-fetched context...");
371
+ choiceArgs.extraArgs.context = {
372
+ ...choiceContext.choiceContextData,
373
+ values: choiceContext.choiceContextData?.values ?? {}
374
+ };
375
+ return [{
376
+ templateId: TRANSFER_FACTORY_INTERFACE_ID,
377
+ contractId: factoryId,
378
+ choice: "TransferFactory_Transfer",
379
+ choiceArgument: choiceArgs
380
+ }, choiceContext.disclosedContracts];
381
+ }
382
+ async createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta, prefetchedRegistryChoiceContext, continueUntilCompletion) {
383
+ try {
384
+ const choiceArgs = await this.buildTransferChoiceArgs(sender, receiver, amount, instrumentAdmin, instrumentId, inputUtxos, memo, expiryDate, meta, continueUntilCompletion);
385
+ if (prefetchedRegistryChoiceContext) return this.createTransferFromContext(prefetchedRegistryChoiceContext.factoryId, choiceArgs, prefetchedRegistryChoiceContext.choiceContext);
386
+ const { factoryId, choiceContext } = await this.fetchTransferFactoryChoiceContext(registryUrl, choiceArgs);
387
+ return this.createTransferFromContext(factoryId, choiceArgs, choiceContext);
388
+ } catch (e) {
389
+ this.logger.error("Failed to execute transfer:", e);
390
+ throw e;
391
+ }
392
+ }
393
+ async fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
394
+ const choiceContext = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
395
+ return {
396
+ choiceContextData: choiceContext.choiceContextData,
397
+ disclosedContracts: choiceContext.disclosedContracts
398
+ };
399
+ }
400
+ async createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext) {
401
+ try {
402
+ return [{
403
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
404
+ contractId: transferInstructionCid,
405
+ choice: "TransferInstruction_Accept",
406
+ choiceArgument: { extraArgs: {
407
+ context: choiceContext.choiceContextData,
408
+ meta: { values: {} }
409
+ } }
410
+ }, choiceContext.disclosedContracts];
411
+ } catch (e) {
412
+ this.logger.error("Failed to create accept transfer instruction:", e);
413
+ throw e;
414
+ }
415
+ }
416
+ async exerciseDelegateProxyTransferInstructionAccept(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
417
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.createAcceptTransferInstruction(transferInstructionCid, registryUrl.href);
418
+ const choiceArgs = {
419
+ cid: acceptTransferInstructionContext.contractId,
420
+ proxyArg: {
421
+ featuredAppRightCid,
422
+ beneficiaries,
423
+ choiceArg: acceptTransferInstructionContext.choiceArgument
424
+ }
425
+ };
426
+ return [{
427
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
428
+ contractId: proxyCid,
429
+ choice: "DelegateProxy_TransferInstruction_Accept",
430
+ choiceArgument: choiceArgs
431
+ }, disclosedContracts];
432
+ }
433
+ async exerciseDelegateProxyTransferInstructionReject(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
434
+ const [rejectTransferInstructionContext, disclosedContracts] = await this.createRejectTransferInstruction(transferInstructionCid, registryUrl.href);
435
+ const choiceArgs = {
436
+ cid: rejectTransferInstructionContext.contractId,
437
+ proxyArg: {
438
+ featuredAppRightCid,
439
+ beneficiaries,
440
+ choiceArg: rejectTransferInstructionContext.choiceArgument
441
+ }
442
+ };
443
+ return [{
444
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
445
+ contractId: proxyCid,
446
+ choice: "DelegateProxy_TransferInstruction_Reject",
447
+ choiceArgument: choiceArgs
448
+ }, disclosedContracts];
449
+ }
450
+ async exerciseDelegateProxyTransferInstructioWithdraw(proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid, beneficiaries) {
451
+ const [withdrawTransferInstructionContext, disclosedContracts] = await this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl.href);
452
+ if (beneficiaries.reduce((totalWeight, beneficiary) => totalWeight + beneficiary.weight, 0) > 1) throw new Error("Sum of beneficiary weights is larger than 1.");
453
+ const choiceArgs = {
454
+ cid: withdrawTransferInstructionContext.contractId,
455
+ proxyArg: {
456
+ featuredAppRightCid,
457
+ beneficiaries,
458
+ choiceArg: withdrawTransferInstructionContext.choiceArgument
459
+ }
460
+ };
461
+ return [{
462
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
463
+ contractId: proxyCid,
464
+ choice: "DelegateProxy_TransferInstruction_Withdraw",
465
+ choiceArgument: choiceArgs
466
+ }, disclosedContracts];
467
+ }
468
+ async createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
469
+ if (prefetchedRegistryChoiceContext) return this.createAcceptTransferInstructionFromContext(transferInstructionCid, {
470
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
471
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
472
+ });
473
+ const choiceContext = await this.fetchAcceptTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
474
+ return this.createAcceptTransferInstructionFromContext(transferInstructionCid, choiceContext);
475
+ }
476
+ async fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
477
+ const choiceContext = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
478
+ return {
479
+ choiceContextData: choiceContext.choiceContextData,
480
+ disclosedContracts: choiceContext.disclosedContracts
481
+ };
482
+ }
483
+ async createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext) {
484
+ try {
485
+ return [{
486
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
487
+ contractId: transferInstructionCid,
488
+ choice: "TransferInstruction_Reject",
489
+ choiceArgument: { extraArgs: {
490
+ context: choiceContext.choiceContextData,
491
+ meta: { values: {} }
492
+ } }
493
+ }, choiceContext.disclosedContracts];
494
+ } catch (e) {
495
+ this.logger.error("Failed to create reject transfer instruction:", e);
496
+ throw e;
497
+ }
498
+ }
499
+ async createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
500
+ if (prefetchedRegistryChoiceContext) return this.createRejectTransferInstructionFromContext(transferInstructionCid, {
501
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
502
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
503
+ });
504
+ const choiceContext = await this.fetchRejectTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
505
+ return this.createRejectTransferInstructionFromContext(transferInstructionCid, choiceContext);
506
+ }
507
+ async fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl) {
508
+ const choiceContext = await this.core.getTokenStandardClient(registryUrl).post("/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw", { excludeDebugFields: true }, { path: { transferInstructionId: transferInstructionCid } });
509
+ return {
510
+ choiceContextData: choiceContext.choiceContextData,
511
+ disclosedContracts: choiceContext.disclosedContracts
512
+ };
513
+ }
514
+ async createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext) {
515
+ try {
516
+ return [{
517
+ templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,
518
+ contractId: transferInstructionCid,
519
+ choice: "TransferInstruction_Withdraw",
520
+ choiceArgument: { extraArgs: {
521
+ context: choiceContext.choiceContextData,
522
+ meta: { values: {} }
523
+ } }
524
+ }, choiceContext.disclosedContracts];
525
+ } catch (e) {
526
+ this.logger.error("Failed to create withdraw transfer instruction:", e);
527
+ throw e;
528
+ }
529
+ }
530
+ async createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext) {
531
+ if (prefetchedRegistryChoiceContext) return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, {
532
+ choiceContextData: prefetchedRegistryChoiceContext.choiceContextData,
533
+ disclosedContracts: prefetchedRegistryChoiceContext.disclosedContracts
534
+ });
535
+ const choiceContext = await this.fetchWithdrawTransferInstructionChoiceContext(transferInstructionCid, registryUrl);
536
+ return this.createWithdrawTransferInstructionFromContext(transferInstructionCid, choiceContext);
537
+ }
538
+ async createTransferInstruction(transferInstructionCid, registryUrl, instructionChoice, prefetchedRegistryChoiceContext) {
539
+ switch (instructionChoice) {
540
+ case "Accept": return this.createAcceptTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext);
541
+ case "Reject": return this.createRejectTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext);
542
+ case "Withdraw": return this.createWithdrawTransferInstruction(transferInstructionCid, registryUrl, prefetchedRegistryChoiceContext);
543
+ }
544
+ }
869
545
  };
870
546
  var TokenStandardService = class {
871
- constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
872
- this.ledgerProvider = ledgerProvider;
873
- this.logger = logger;
874
- this.accessTokenProvider = accessTokenProvider;
875
- this.isMasterUser = isMasterUser;
876
- __publicField(this, "core");
877
- __publicField(this, "allocation");
878
- __publicField(this, "transfer");
879
- this.core = new CoreService(
880
- ledgerProvider,
881
- logger,
882
- accessTokenProvider,
883
- isMasterUser
884
- );
885
- this.allocation = new AllocationService(this.core, this.logger);
886
- this.transfer = new TransferService(this.core, this.logger);
887
- }
888
- async getInstrumentById(registryUrl, instrumentId) {
889
- try {
890
- const params = {
891
- path: {
892
- instrumentId
893
- }
894
- };
895
- const client = this.core.getTokenStandardClient(registryUrl);
896
- return client.get(
897
- "/registry/metadata/v1/instruments/{instrumentId}",
898
- params
899
- );
900
- } catch (e) {
901
- this.logger.error(e);
902
- throw new Error(
903
- `Instrument id ${instrumentId} does not exist for this instrument admin.`,
904
- { cause: e }
905
- );
906
- }
907
- }
908
- async getInstrumentAdmin(registryUrl) {
909
- const client = this.core.getTokenStandardClient(registryUrl);
910
- const info = await client.get("/registry/metadata/v1/info");
911
- return info.adminId;
912
- }
913
- async listInstruments(registryUrl, pageSize, pageToken) {
914
- const client = this.core.getTokenStandardClient(registryUrl);
915
- return client.get("/registry/metadata/v1/instruments", {
916
- query: {
917
- ...pageSize && { pageSize },
918
- ...pageToken && { pageToken }
919
- }
920
- });
921
- }
922
- async instrumentsToAsset(registryUrl) {
923
- const instrumentsResponse = await this.listInstruments(registryUrl);
924
- const instrumentAdmin = await this.getInstrumentAdmin(registryUrl);
925
- return instrumentsResponse.instruments.map((instrument) => ({
926
- id: instrument.id,
927
- displayName: instrument.name,
928
- symbol: instrument.symbol,
929
- registryUrl,
930
- admin: instrumentAdmin
931
- }));
932
- }
933
- async registriesToAssets(registryUrls) {
934
- const allInstruments = [];
935
- for (const registryUrl of registryUrls) {
936
- const instruments = await this.instrumentsToAsset(registryUrl);
937
- allInstruments.push(...instruments);
938
- }
939
- return allInstruments;
940
- }
941
- // <T> is shape of viewValue related to queried interface.
942
- // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen
943
- async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
944
- return this.core.listContractsByInterface(
945
- interfaceId,
946
- partyId,
947
- limit,
948
- offset,
949
- continueUntilCompletion
950
- );
951
- }
952
- async listHoldingTransactions(partyId, afterOffset, beforeOffset) {
953
- try {
954
- this.logger.debug("Set or query offset");
955
- const afterOffsetOrLatest = afterOffset ?? (await this.ledgerProvider.request(
956
- {
957
- method: "ledgerApi",
958
- params: {
959
- resource: "/v2/state/latest-pruned-offsets",
960
- requestMethod: "get"
961
- }
962
- }
963
- )).participantPrunedUpToInclusive;
964
- const beforeOffsetOrLatest = beforeOffset ?? (await this.ledgerProvider.request({
965
- method: "ledgerApi",
966
- params: {
967
- resource: "/v2/state/ledger-end",
968
- requestMethod: "get"
969
- }
970
- })).offset;
971
- this.logger.debug(afterOffsetOrLatest, "Using offset");
972
- const updatesResponse = await this.ledgerProvider.request({
973
- method: "ledgerApi",
974
- params: {
975
- resource: "/v2/updates/flats",
976
- requestMethod: "post",
977
- query: {},
978
- body: {
979
- updateFormat: {
980
- includeTransactions: {
981
- eventFormat: EventFilterBySetup({
982
- interfaceIds: TokenStandardTransactionInterfaces,
983
- isMasterUser: this.isMasterUser,
984
- partyId,
985
- includeWildcard: true
986
- }),
987
- transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
988
- }
989
- },
990
- beginExclusive: afterOffsetOrLatest,
991
- endInclusive: beforeOffsetOrLatest,
992
- verbose: false
993
- }
994
- }
995
- });
996
- return this.core.toPrettyTransactions(
997
- updatesResponse,
998
- partyId
999
- // this.ledgerProvider
1000
- );
1001
- } catch (err) {
1002
- this.logger.error("Failed to list holding transactions.", err);
1003
- throw err;
1004
- }
1005
- }
1006
- async getTransactionById(updateId, partyId) {
1007
- const transactionFormat = {
1008
- eventFormat: EventFilterBySetup({
1009
- interfaceIds: TokenStandardTransactionInterfaces,
1010
- isMasterUser: this.isMasterUser,
1011
- partyId,
1012
- includeWildcard: true
1013
- }),
1014
- transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
1015
- };
1016
- const getTransactionResponse = await this.ledgerProvider.request(
1017
- {
1018
- method: "ledgerApi",
1019
- params: {
1020
- resource: "/v2/updates/transaction-by-id",
1021
- requestMethod: "post",
1022
- body: {
1023
- updateId,
1024
- transactionFormat
1025
- }
1026
- }
1027
- }
1028
- );
1029
- return this.core.toPrettyTransaction(getTransactionResponse, partyId);
1030
- }
1031
- async getTransferObjectsById(updateId, partyId) {
1032
- const transactionFormat = {
1033
- eventFormat: EventFilterBySetup({
1034
- interfaceIds: TokenStandardTransactionInterfaces,
1035
- isMasterUser: this.isMasterUser,
1036
- partyId,
1037
- includeWildcard: true
1038
- }),
1039
- transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
1040
- };
1041
- const getTransactionResponse = await this.ledgerProvider.request(
1042
- {
1043
- method: "ledgerApi",
1044
- params: {
1045
- resource: "/v2/updates/transaction-by-id",
1046
- requestMethod: "post",
1047
- body: {
1048
- updateId,
1049
- transactionFormat
1050
- }
1051
- }
1052
- }
1053
- );
1054
- return this.core.toPrettyTransferObjects(
1055
- getTransactionResponse,
1056
- partyId
1057
- );
1058
- }
1059
- async getInputHoldingsCids(sender, inputUtxos, amount) {
1060
- if (amount) {
1061
- return this.core.getInputHoldingsCids({
1062
- sender,
1063
- inputUtxos: inputUtxos ?? [],
1064
- amount
1065
- });
1066
- } else {
1067
- return this.core.getInputHoldingsCids({
1068
- sender,
1069
- inputUtxos: inputUtxos ?? []
1070
- });
1071
- }
1072
- }
1073
- async createDelegateProxyTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, featuredAppRightCid, proxyCid, beneficiaries, inputUtxos, memo, expiryDate, meta) {
1074
- const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(
1075
- sender,
1076
- receiver,
1077
- amount,
1078
- instrumentAdmin,
1079
- instrumentId,
1080
- registryUrl,
1081
- inputUtxos,
1082
- memo,
1083
- expiryDate,
1084
- meta
1085
- );
1086
- const sumOfWeights = beneficiaries.reduce(
1087
- (totalWeight, beneficiary) => totalWeight + beneficiary.weight,
1088
- 0
1089
- );
1090
- if (sumOfWeights > 1) {
1091
- throw new Error("Sum of beneficiary weights is larger than 1.");
1092
- }
1093
- const choiceArgs = {
1094
- cid: transferCommand.contractId,
1095
- proxyArg: {
1096
- featuredAppRightCid,
1097
- beneficiaries,
1098
- choiceArg: transferCommand.choiceArgument
1099
- }
1100
- };
1101
- const exercise = {
1102
- templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
1103
- contractId: proxyCid,
1104
- choice: "DelegateProxy_TransferFactory_Transfer",
1105
- choiceArgument: choiceArgs
1106
- };
1107
- return [exercise, disclosedContracts];
1108
- }
1109
- async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
1110
- const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(
1111
- transferInstructionCid,
1112
- registryUrl
1113
- );
1114
- const choiceArgs = {
1115
- cid: acceptTransferInstructionContext.contractId,
1116
- proxyArg: {
1117
- featuredAppRightCid,
1118
- beneficiaries: [
1119
- {
1120
- beneficiary: exchangeParty,
1121
- weight: 1
1122
- }
1123
- ],
1124
- choiceArg: acceptTransferInstructionContext.choiceArgument
1125
- }
1126
- };
1127
- return [
1128
- {
1129
- templateId: "#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy",
1130
- contractId: proxyCid,
1131
- choice: "DelegateProxy_TransferInstruction_Accept",
1132
- choiceArgument: choiceArgs
1133
- },
1134
- disclosedContracts
1135
- ];
1136
- }
1137
- static isHoldingLocked(holding, currentTime = /* @__PURE__ */ new Date()) {
1138
- const lock = holding.lock;
1139
- if (!lock) return false;
1140
- const expiresAt = lock.expiresAt;
1141
- if (!expiresAt) return true;
1142
- const expiresAtDate = new Date(expiresAt);
1143
- return currentTime < expiresAtDate;
1144
- }
547
+ constructor(ledgerProvider, logger, accessTokenProvider, isMasterUser) {
548
+ this.ledgerProvider = ledgerProvider;
549
+ this.logger = logger;
550
+ this.accessTokenProvider = accessTokenProvider;
551
+ this.isMasterUser = isMasterUser;
552
+ _defineProperty(this, "core", void 0);
553
+ _defineProperty(this, "allocation", void 0);
554
+ _defineProperty(this, "transfer", void 0);
555
+ this.core = new CoreService(ledgerProvider, logger, accessTokenProvider, isMasterUser);
556
+ this.allocation = new AllocationService(this.core, this.logger);
557
+ this.transfer = new TransferService(this.core, this.logger);
558
+ }
559
+ async getInstrumentById(registryUrl, instrumentId) {
560
+ try {
561
+ const params = { path: { instrumentId } };
562
+ return this.core.getTokenStandardClient(registryUrl).get("/registry/metadata/v1/instruments/{instrumentId}", params);
563
+ } catch (e) {
564
+ this.logger.error(e);
565
+ throw new Error(`Instrument id ${instrumentId} does not exist for this instrument admin.`, { cause: e });
566
+ }
567
+ }
568
+ async getInstrumentAdmin(registryUrl) {
569
+ return (await this.core.getTokenStandardClient(registryUrl).get("/registry/metadata/v1/info")).adminId;
570
+ }
571
+ async listInstruments(registryUrl, pageSize, pageToken) {
572
+ return this.core.getTokenStandardClient(registryUrl).get("/registry/metadata/v1/instruments", { query: {
573
+ ...pageSize && { pageSize },
574
+ ...pageToken && { pageToken }
575
+ } });
576
+ }
577
+ async instrumentsToAsset(registryUrl) {
578
+ let instrumentsResponse = await this.listInstruments(registryUrl);
579
+ const instruments = [...instrumentsResponse.instruments];
580
+ while (instrumentsResponse.nextPageToken) {
581
+ instrumentsResponse = await this.listInstruments(registryUrl, void 0, instrumentsResponse.nextPageToken);
582
+ instruments.push(...instrumentsResponse.instruments);
583
+ }
584
+ const instrumentAdmin = await this.getInstrumentAdmin(registryUrl);
585
+ return instruments.map((instrument) => ({
586
+ id: instrument.id,
587
+ displayName: instrument.name,
588
+ symbol: instrument.symbol,
589
+ registryUrl,
590
+ admin: instrumentAdmin
591
+ }));
592
+ }
593
+ async registriesToAssets(registryUrls) {
594
+ const allInstruments = [];
595
+ for (const registryUrl of registryUrls) {
596
+ const instruments = await this.instrumentsToAsset(registryUrl);
597
+ allInstruments.push(...instruments);
598
+ }
599
+ return allInstruments;
600
+ }
601
+ async listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion) {
602
+ return this.core.listContractsByInterface(interfaceId, partyId, limit, offset, continueUntilCompletion);
603
+ }
604
+ async listHoldingTransactions(partyId, afterOffset, beforeOffset) {
605
+ try {
606
+ this.logger.debug("Set or query offset");
607
+ const afterOffsetOrLatest = afterOffset ?? (await this.ledgerProvider.request({
608
+ method: "ledgerApi",
609
+ params: {
610
+ resource: "/v2/state/latest-pruned-offsets",
611
+ requestMethod: "get"
612
+ }
613
+ })).participantPrunedUpToInclusive;
614
+ const beforeOffsetOrLatest = beforeOffset ?? (await this.ledgerProvider.request({
615
+ method: "ledgerApi",
616
+ params: {
617
+ resource: "/v2/state/ledger-end",
618
+ requestMethod: "get"
619
+ }
620
+ })).offset;
621
+ this.logger.debug(afterOffsetOrLatest, "Using offset");
622
+ const updatesResponse = await this.ledgerProvider.request({
623
+ method: "ledgerApi",
624
+ params: {
625
+ resource: "/v2/updates/flats",
626
+ requestMethod: "post",
627
+ query: {},
628
+ body: {
629
+ updateFormat: { includeTransactions: {
630
+ eventFormat: EventFilterBySetup({
631
+ interfaceIds: TokenStandardTransactionInterfaces,
632
+ isMasterUser: this.isMasterUser,
633
+ partyId,
634
+ includeWildcard: true
635
+ }),
636
+ transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
637
+ } },
638
+ beginExclusive: afterOffsetOrLatest,
639
+ endInclusive: beforeOffsetOrLatest,
640
+ verbose: false
641
+ }
642
+ }
643
+ });
644
+ return this.core.toPrettyTransactions(updatesResponse, partyId);
645
+ } catch (err) {
646
+ this.logger.error("Failed to list holding transactions.", err);
647
+ throw err;
648
+ }
649
+ }
650
+ async getTransactionById(updateId, partyId) {
651
+ const transactionFormat = {
652
+ eventFormat: EventFilterBySetup({
653
+ interfaceIds: TokenStandardTransactionInterfaces,
654
+ isMasterUser: this.isMasterUser,
655
+ partyId,
656
+ includeWildcard: true
657
+ }),
658
+ transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
659
+ };
660
+ const getTransactionResponse = await this.ledgerProvider.request({
661
+ method: "ledgerApi",
662
+ params: {
663
+ resource: "/v2/updates/transaction-by-id",
664
+ requestMethod: "post",
665
+ body: {
666
+ updateId,
667
+ transactionFormat
668
+ }
669
+ }
670
+ });
671
+ return this.core.toPrettyTransaction(getTransactionResponse, partyId);
672
+ }
673
+ async getTransferObjectsById(updateId, partyId) {
674
+ const transactionFormat = {
675
+ eventFormat: EventFilterBySetup({
676
+ interfaceIds: TokenStandardTransactionInterfaces,
677
+ isMasterUser: this.isMasterUser,
678
+ partyId,
679
+ includeWildcard: true
680
+ }),
681
+ transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
682
+ };
683
+ const getTransactionResponse = await this.ledgerProvider.request({
684
+ method: "ledgerApi",
685
+ params: {
686
+ resource: "/v2/updates/transaction-by-id",
687
+ requestMethod: "post",
688
+ body: {
689
+ updateId,
690
+ transactionFormat
691
+ }
692
+ }
693
+ });
694
+ return this.core.toPrettyTransferObjects(getTransactionResponse, partyId);
695
+ }
696
+ async getInputHoldingsCids(sender, inputUtxos, amount) {
697
+ if (amount) return this.core.getInputHoldingsCids({
698
+ sender,
699
+ inputUtxos: inputUtxos ?? [],
700
+ amount
701
+ });
702
+ else return this.core.getInputHoldingsCids({
703
+ sender,
704
+ inputUtxos: inputUtxos ?? []
705
+ });
706
+ }
707
+ async createDelegateProxyTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, featuredAppRightCid, proxyCid, beneficiaries, inputUtxos, memo, expiryDate, meta) {
708
+ const [transferCommand, disclosedContracts] = await this.transfer.createTransfer(sender, receiver, amount, instrumentAdmin, instrumentId, registryUrl, inputUtxos, memo, expiryDate, meta);
709
+ if (beneficiaries.reduce((totalWeight, beneficiary) => totalWeight + beneficiary.weight, 0) > 1) throw new Error("Sum of beneficiary weights is larger than 1.");
710
+ const choiceArgs = {
711
+ cid: transferCommand.contractId,
712
+ proxyArg: {
713
+ featuredAppRightCid,
714
+ beneficiaries,
715
+ choiceArg: transferCommand.choiceArgument
716
+ }
717
+ };
718
+ return [{
719
+ templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,
720
+ contractId: proxyCid,
721
+ choice: "DelegateProxy_TransferFactory_Transfer",
722
+ choiceArgument: choiceArgs
723
+ }, disclosedContracts];
724
+ }
725
+ async exerciseDelegateProxyTransferInstructionAccept(exchangeParty, proxyCid, transferInstructionCid, registryUrl, featuredAppRightCid) {
726
+ const [acceptTransferInstructionContext, disclosedContracts] = await this.transfer.createAcceptTransferInstruction(transferInstructionCid, registryUrl);
727
+ return [{
728
+ templateId: "#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy",
729
+ contractId: proxyCid,
730
+ choice: "DelegateProxy_TransferInstruction_Accept",
731
+ choiceArgument: {
732
+ cid: acceptTransferInstructionContext.contractId,
733
+ proxyArg: {
734
+ featuredAppRightCid,
735
+ beneficiaries: [{
736
+ beneficiary: exchangeParty,
737
+ weight: 1
738
+ }],
739
+ choiceArg: acceptTransferInstructionContext.choiceArgument
740
+ }
741
+ }
742
+ }, disclosedContracts];
743
+ }
744
+ static isHoldingLocked(holding, currentTime = /* @__PURE__ */ new Date()) {
745
+ const lock = holding.lock;
746
+ if (!lock) return false;
747
+ const expiresAt = lock.expiresAt;
748
+ if (!expiresAt) return true;
749
+ return currentTime < new Date(expiresAt);
750
+ }
1145
751
  };
1146
- __publicField(TokenStandardService, "MEMO_KEY", "splice.lfdecentralizedtrust.org/reason");
1147
-
752
+ _defineProperty(TokenStandardService, "MEMO_KEY", "splice.lfdecentralizedtrust.org/reason");
753
+ //#endregion
1148
754
  export { CoreService, TokenStandardService };
1149
- //# sourceMappingURL=index.js.map
755
+
1150
756
  //# sourceMappingURL=index.js.map