@canton-network/core-token-standard-service 1.11.0 → 1.12.1

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
@@ -60,13 +60,7 @@ var CoreService = class CoreService {
60
60
  if (options.inputUtxos && options.inputUtxos.length > 0) return options.inputUtxos;
61
61
  const senderHoldings = await this.listContractsByInterface(HOLDING_INTERFACE_ID, sender, void 0, void 0, options.continueUntilCompletion);
62
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
- });
63
+ const unlockedSenderHoldings = senderHoldings.filter((utxo) => !TokenStandardService.isHoldingLocked(utxo, now));
70
64
  if (unlockedSenderHoldings.length > 100) this.logger.warn(`Sender has more than 100 unlocked utxos.`);
71
65
  const unlockedHoldingsForInstrument = instrumentAdmin && instrumentId ? await CoreService.filterHoldingsByInstrument({
72
66
  holdings: unlockedSenderHoldings,
@@ -106,7 +100,8 @@ var CoreService = class CoreService {
106
100
  method: "ledgerApi",
107
101
  params: {
108
102
  resource: "/v2/state/ledger-end",
109
- requestMethod: "get"
103
+ requestMethod: "get",
104
+ query: {}
110
105
  }
111
106
  })).offset;
112
107
  const options = {
@@ -141,15 +136,20 @@ var CoreService = class CoreService {
141
136
  transactions: transactions.filter((tx) => tx.events.length > 0).map(renderTransaction)
142
137
  };
143
138
  }
144
- async toPrettyTransaction(getTransactionResponse, partyId) {
145
- const tx = getTransactionResponse.transaction;
139
+ async toPrettyTransaction(getUpdateResponse, partyId) {
140
+ const tx = this.getTransactionFromUpdate(getUpdateResponse);
146
141
  const parsedTx = await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransaction();
147
142
  return renderTransaction(parsedTx);
148
143
  }
149
- async toPrettyTransferObjects(getTransactionResponse, partyId) {
150
- const tx = getTransactionResponse.transaction;
144
+ async toPrettyTransferObjects(getUpdateResponse, partyId) {
145
+ const tx = this.getTransactionFromUpdate(getUpdateResponse);
151
146
  return await new TransactionParser(this.ledgerProvider, tx, partyId, this.isMasterUser).parseTransferObjects();
152
147
  }
148
+ getTransactionFromUpdate(getUpdateResponse) {
149
+ const update = getUpdateResponse.update;
150
+ if (!update || !("Transaction" in update)) throw new Error("Expected transaction update");
151
+ return update.Transaction.value;
152
+ }
153
153
  async toPrettyTransactionsPerParty(updates, parties) {
154
154
  const all = await Promise.all(parties.map(async (partyId) => [partyId, await this.toPrettyTransactions(updates, partyId)]));
155
155
  return new Map(all);
@@ -615,14 +615,15 @@ var TokenStandardService = class {
615
615
  method: "ledgerApi",
616
616
  params: {
617
617
  resource: "/v2/state/ledger-end",
618
- requestMethod: "get"
618
+ requestMethod: "get",
619
+ query: {}
619
620
  }
620
621
  })).offset;
621
622
  this.logger.debug(afterOffsetOrLatest, "Using offset");
622
623
  const updatesResponse = await this.ledgerProvider.request({
623
624
  method: "ledgerApi",
624
625
  params: {
625
- resource: "/v2/updates/flats",
626
+ resource: "/v2/updates",
626
627
  requestMethod: "post",
627
628
  query: {},
628
629
  body: {
@@ -636,8 +637,7 @@ var TokenStandardService = class {
636
637
  transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
637
638
  } },
638
639
  beginExclusive: afterOffsetOrLatest,
639
- endInclusive: beforeOffsetOrLatest,
640
- verbose: false
640
+ endInclusive: beforeOffsetOrLatest
641
641
  }
642
642
  }
643
643
  });
@@ -648,7 +648,7 @@ var TokenStandardService = class {
648
648
  }
649
649
  }
650
650
  async getTransactionById(updateId, partyId) {
651
- const transactionFormat = {
651
+ const updateFormat = { includeTransactions: {
652
652
  eventFormat: EventFilterBySetup({
653
653
  interfaceIds: TokenStandardTransactionInterfaces,
654
654
  isMasterUser: this.isMasterUser,
@@ -656,22 +656,22 @@ var TokenStandardService = class {
656
656
  includeWildcard: true
657
657
  }),
658
658
  transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
659
- };
660
- const getTransactionResponse = await this.ledgerProvider.request({
659
+ } };
660
+ const getUpdateResponse = await this.ledgerProvider.request({
661
661
  method: "ledgerApi",
662
662
  params: {
663
- resource: "/v2/updates/transaction-by-id",
663
+ resource: "/v2/updates/update-by-id",
664
664
  requestMethod: "post",
665
665
  body: {
666
666
  updateId,
667
- transactionFormat
667
+ updateFormat
668
668
  }
669
669
  }
670
670
  });
671
- return this.core.toPrettyTransaction(getTransactionResponse, partyId);
671
+ return this.core.toPrettyTransaction(getUpdateResponse, partyId);
672
672
  }
673
673
  async getTransferObjectsById(updateId, partyId) {
674
- const transactionFormat = {
674
+ const updateFormat = { includeTransactions: {
675
675
  eventFormat: EventFilterBySetup({
676
676
  interfaceIds: TokenStandardTransactionInterfaces,
677
677
  isMasterUser: this.isMasterUser,
@@ -679,19 +679,19 @@ var TokenStandardService = class {
679
679
  includeWildcard: true
680
680
  }),
681
681
  transactionShape: "TRANSACTION_SHAPE_LEDGER_EFFECTS"
682
- };
683
- const getTransactionResponse = await this.ledgerProvider.request({
682
+ } };
683
+ const getUpdateResponse = await this.ledgerProvider.request({
684
684
  method: "ledgerApi",
685
685
  params: {
686
- resource: "/v2/updates/transaction-by-id",
686
+ resource: "/v2/updates/update-by-id",
687
687
  requestMethod: "post",
688
688
  body: {
689
689
  updateId,
690
- transactionFormat
690
+ updateFormat
691
691
  }
692
692
  }
693
693
  });
694
- return this.core.toPrettyTransferObjects(getTransactionResponse, partyId);
694
+ return this.core.toPrettyTransferObjects(getUpdateResponse, partyId);
695
695
  }
696
696
  async getInputHoldingsCids(sender, inputUtxos, amount) {
697
697
  if (amount) return this.core.getInputHoldingsCids({
@@ -742,11 +742,22 @@ var TokenStandardService = class {
742
742
  }, disclosedContracts];
743
743
  }
744
744
  static isHoldingLocked(holding, currentTime = /* @__PURE__ */ new Date()) {
745
- const lock = holding.lock;
745
+ const lock = holding.interfaceViewValue.lock;
746
746
  if (!lock) return false;
747
- const expiresAt = lock.expiresAt;
748
- if (!expiresAt) return true;
749
- return currentTime < new Date(expiresAt);
747
+ let expiresAtAbsolute = null;
748
+ let expiresAtRelative = null;
749
+ if (lock.expiresAfter) {
750
+ const createdAt = new Date(holding.activeContract.createdEvent.createdAt);
751
+ const msToAdd = parseInt(lock.expiresAfter.microseconds) / 1e3;
752
+ expiresAtRelative = new Date(createdAt.getTime() + msToAdd);
753
+ }
754
+ if (lock.expiresAt) expiresAtAbsolute = new Date(lock.expiresAt);
755
+ let expiresAt;
756
+ if (expiresAtRelative && expiresAtAbsolute) expiresAt = expiresAtRelative < expiresAtAbsolute ? expiresAtRelative : expiresAtAbsolute;
757
+ else if (expiresAtRelative) expiresAt = expiresAtRelative;
758
+ else if (expiresAtAbsolute) expiresAt = expiresAtAbsolute;
759
+ else return true;
760
+ return currentTime < expiresAt;
750
761
  }
751
762
  };
752
763
  _defineProperty(TokenStandardService, "MEMO_KEY", "splice.lfdecentralizedtrust.org/reason");
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["txUpdate"],"sources":["../src/token-standard-service.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n TokenStandardClient,\n TRANSFER_FACTORY_INTERFACE_ID,\n HOLDING_INTERFACE_ID,\n ALLOCATION_FACTORY_INTERFACE_ID,\n ALLOCATION_INTERFACE_ID,\n ALLOCATION_REQUEST_INTERFACE_ID,\n ALLOCATION_INSTRUCTION_INTERFACE_ID,\n TRANSFER_INSTRUCTION_INTERFACE_ID,\n HoldingView,\n AllocationFactory_Allocate,\n AllocationSpecification,\n Transfer,\n transferInstructionRegistryTypes,\n allocationInstructionRegistryTypes,\n ExtraArgs,\n Metadata,\n FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,\n Holding,\n Beneficiaries,\n} from '@canton-network/core-token-standard'\nimport {\n EventFilterBySetup,\n type LedgerCommonSchemas,\n} from '@canton-network/core-ledger-client-types'\nimport { ContractId, Logger, PartyId } from '@canton-network/core-types'\nimport { ACSReader, AcsOptions } from '@canton-network/core-acs-reader'\nimport {\n TokenStandardTransactionInterfaces,\n ensureInterfaceViewIsPresent,\n TransactionParser,\n PrettyContract,\n renderTransaction,\n ViewValue,\n Holding as TxParseHolding,\n PrettyTransactions,\n Transaction,\n TransferObject,\n} from '@canton-network/core-tx-parser'\nimport { AccessTokenProvider } from '@canton-network/core-wallet-auth'\nimport {\n AbstractLedgerProvider,\n Ops,\n} from '@canton-network/core-provider-ledger'\nimport { Decimal } from 'decimal.js'\n\nconst REQUESTED_AT_SKEW_MS = 60_000\n\nexport type ExerciseCommand = LedgerCommonSchemas['ExerciseCommand']\nexport type DisclosedContract = LedgerCommonSchemas['DisclosedContract']\nconst EMPTY_META: Metadata = { values: {} }\n\ntype JsGetActiveContractsResponse =\n LedgerCommonSchemas['JsGetActiveContractsResponse']\ntype JsGetUpdatesResponse =\n Ops.PostV2UpdatesFlats['ledgerApi']['result'][number]\ntype JsGetTransactionResponse = LedgerCommonSchemas['JsGetTransactionResponse']\ntype OffsetCheckpoint2 = LedgerCommonSchemas['OffsetCheckpoint2']\ntype JsTransaction = LedgerCommonSchemas['JsTransaction']\ntype TransactionFormat = LedgerCommonSchemas['TransactionFormat']\n\ntype JsActiveContract = LedgerCommonSchemas['JsActiveContract']\n\ntype OffsetCheckpointUpdate = {\n update: { OffsetCheckpoint: OffsetCheckpoint2 }\n}\ntype TransactionUpdate = {\n update: { Transaction: { value: JsTransaction } }\n}\n\ntype JsActiveContractEntryResponse = JsGetActiveContractsResponse & {\n contractEntry: {\n JsActiveContract: {\n createdEvent: LedgerCommonSchemas['CreatedEvent']\n }\n }\n}\n\ntype CreateTransferChoiceArgs = {\n expectedAdmin: PartyId\n transfer: Transfer\n extraArgs: ExtraArgs\n}\n\nexport class CoreService {\n constructor(\n private ledgerProvider: AbstractLedgerProvider,\n private readonly logger: Logger,\n private accessTokenProvider: AccessTokenProvider,\n private readonly isMasterUser: boolean\n ) {}\n\n getTokenStandardClient(registryUrl: string): TokenStandardClient {\n return new TokenStandardClient(\n registryUrl,\n this.logger,\n this.accessTokenProvider\n )\n }\n\n async getInputHoldingsCids(options: {\n sender: PartyId\n instrumentAdmin?: string\n instrumentId?: string\n inputUtxos?: string[]\n amount?: Decimal\n continueUntilCompletion?: boolean\n }) {\n const { sender, instrumentAdmin, instrumentId } = options\n const now = new Date()\n if (options.inputUtxos && options.inputUtxos.length > 0) {\n return options.inputUtxos\n }\n const senderHoldings = await this.listContractsByInterface<HoldingView>(\n HOLDING_INTERFACE_ID,\n sender,\n undefined,\n undefined,\n options.continueUntilCompletion\n )\n if (senderHoldings.length === 0) {\n throw new Error(\n \"Sender has no holdings, so transfer can't be executed.\"\n )\n }\n\n const unlockedSenderHoldings = senderHoldings.filter((utxo) => {\n //filter out locked holdings\n const lock = utxo.interfaceViewValue.lock\n if (!lock) return true\n\n const expiresAt = lock.expiresAt\n if (!expiresAt) return false\n\n const expiresAtDate = new Date(expiresAt)\n return expiresAtDate <= now\n })\n\n if (unlockedSenderHoldings.length > 100) {\n this.logger.warn(`Sender has more than 100 unlocked utxos.`)\n }\n\n const unlockedHoldingsForInstrument =\n instrumentAdmin && instrumentId\n ? await CoreService.filterHoldingsByInstrument({\n holdings: unlockedSenderHoldings,\n instrumentAdmin,\n instrumentId,\n })\n : unlockedSenderHoldings\n\n if (options.amount) {\n return CoreService.getInputHoldingsCidsForAmount(\n options.amount,\n unlockedHoldingsForInstrument\n )\n } else {\n return unlockedHoldingsForInstrument.map((h) => h.contractId)\n }\n }\n\n static async filterHoldingsByInstrument(options: {\n holdings: PrettyContract<HoldingView>[]\n instrumentAdmin: string\n instrumentId: string\n }) {\n const { holdings, instrumentAdmin, instrumentId } = options\n return holdings.filter((utxo) => {\n return (\n utxo.interfaceViewValue.instrumentId.id === instrumentId &&\n utxo.interfaceViewValue.instrumentId.admin === instrumentAdmin\n )\n })\n }\n\n static async getInputHoldingsCidsForAmount(\n amount: Decimal,\n unlockedSenderHoldings: PrettyContract<HoldingView>[]\n ) {\n //find holding that is the exact amount if possible\n const exactAmount = unlockedSenderHoldings.find((holding) =>\n new Decimal(holding.interfaceViewValue.amount).equals(amount)\n )\n\n if (exactAmount) {\n return [exactAmount.contractId]\n }\n\n //sort holdings from smallest to largest\n const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted(\n (a, b) =>\n new Decimal(a.interfaceViewValue.amount).comparedTo(\n new Decimal(b.interfaceViewValue.amount)\n )\n )\n\n const largestHoldingAmount = sortedUnlockedSenderHoldings.pop()\n\n if (!largestHoldingAmount) {\n throw new Error(`Sender doesn't have any unlocked holdings`)\n }\n\n let currentSum = new Decimal(\n largestHoldingAmount.interfaceViewValue.amount\n )\n const cIds = [largestHoldingAmount.contractId]\n\n for (const h of sortedUnlockedSenderHoldings) {\n if (currentSum.greaterThanOrEqualTo(amount)) {\n break\n }\n\n const currentHoldingAmount = new Decimal(\n h.interfaceViewValue.amount\n )\n\n currentSum = currentSum.plus(currentHoldingAmount)\n cIds.push(h.contractId)\n }\n\n if (currentSum.lessThan(amount)) {\n throw new Error(\n `Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount.minus(currentSum)}`\n )\n }\n\n if (cIds.length > 100) {\n throw new Error(\n `Exceeded the maximum of 100 utxos in 1 transaction`\n )\n }\n\n return cIds\n }\n\n async listContractsByInterface<T = ViewValue>(\n interfaceId: string,\n partyId?: PartyId,\n limit?: number,\n offset?: number,\n continueUntilCompletion?: boolean\n ): Promise<PrettyContract<T>[]> {\n try {\n const ledgerEnd =\n offset ??\n (\n await this.ledgerProvider.request<Ops.GetV2StateLedgerEnd>({\n method: 'ledgerApi',\n params: {\n resource: '/v2/state/ledger-end',\n requestMethod: 'get',\n },\n })\n ).offset!\n\n const options: AcsOptions = {\n offset: ledgerEnd,\n interfaceIds: [interfaceId],\n parties: [partyId!],\n filterByParty: true,\n continueUntilCompletion: Boolean(continueUntilCompletion),\n }\n\n if (limit !== undefined) {\n options.limit = limit\n }\n\n //TODO: based on the. provider design we can't pass in the continue to completion, so right now it's defaulted to true in the ledger provider. we need to figure out how to add an ACS functionality and ensure better composability\n this.logger.info(\n `continue to completion: ${Boolean(continueUntilCompletion)}`\n )\n\n const reader = new ACSReader(this.ledgerProvider)\n\n const acsResponses: JsGetActiveContractsResponse[] =\n (await reader.raw.read(\n options\n ))! as JsGetActiveContractsResponse[]\n\n /* This filters out responses with entries of:\n - JsEmpty\n - JsIncompleteAssigned\n - JsIncompleteUnassigned\n while leaving JsActiveContract.\n It works fine only with single synchronizer\n TODO (#353) add support for multiple synchronizers\n */\n const isActiveContractEntry = (\n acsResponse: JsGetActiveContractsResponse\n ): acsResponse is JsActiveContractEntryResponse =>\n acsResponse.contractEntry != null &&\n 'JsActiveContract' in acsResponse.contractEntry &&\n acsResponse.contractEntry.JsActiveContract != null &&\n acsResponse.contractEntry.JsActiveContract.createdEvent != null\n\n const results: PrettyContract<T>[] = acsResponses\n .filter(isActiveContractEntry)\n .map((response) =>\n this.toPrettyContract<T>(\n interfaceId,\n response as JsActiveContractEntryResponse,\n ledgerEnd\n )\n )\n return results\n } catch (err) {\n this.logger.error(\n `Failed to list contracts of interface ${interfaceId}`,\n err\n )\n throw err\n }\n }\n\n async toPrettyTransactions(\n updates: JsGetUpdatesResponse[],\n partyId: PartyId\n ): Promise<PrettyTransactions> {\n // Runtime filters that also let TS know which of OneOfs types to check against\n const isOffsetCheckpointUpdate = (\n updateResponse: JsGetUpdatesResponse\n ): updateResponse is OffsetCheckpointUpdate =>\n updateResponse.update != null &&\n 'OffsetCheckpoint' in updateResponse.update\n\n const isTransactionUpdate = (\n updateResponse: JsGetUpdatesResponse\n ): updateResponse is TransactionUpdate =>\n updateResponse.update != null &&\n 'Transaction' in updateResponse.update &&\n !!updateResponse.update.Transaction?.value\n\n const offsetCheckpoints: number[] = updates\n .filter(isOffsetCheckpointUpdate)\n .map(\n (update) =>\n (update.update as OffsetCheckpointUpdate['update'])\n .OffsetCheckpoint.value.offset\n )\n const latestCheckpointOffset =\n offsetCheckpoints.length > 0 ? Math.max(...offsetCheckpoints) : 0\n\n const transactions: Transaction[] = await Promise.all(\n updates\n // exclude OffsetCheckpoint, Reassignment, TopologyTransaction\n .filter(isTransactionUpdate)\n .map(async (update) => {\n const txUpdate = update as TransactionUpdate\n const tx = txUpdate.update.Transaction\n .value as JsTransaction\n const parser = new TransactionParser(\n this.ledgerProvider,\n tx,\n partyId,\n this.isMasterUser\n )\n\n return await parser.parseTransaction()\n })\n )\n\n const transactionOffsets = transactions\n .map((tx) => tx.offset)\n .filter((offset): offset is number => offset !== undefined)\n\n return {\n // OffsetCheckpoint can be anywhere... or not at all, maybe\n nextOffset: Math.max(\n latestCheckpointOffset,\n ...(transactionOffsets.length > 0 ? transactionOffsets : [0])\n ),\n transactions: transactions\n .filter((tx) => tx.events.length > 0)\n .map(renderTransaction),\n }\n }\n\n async toPrettyTransaction(\n getTransactionResponse: JsGetTransactionResponse,\n partyId: PartyId\n ): Promise<Transaction> {\n const tx = getTransactionResponse.transaction\n const parser = new TransactionParser(\n this.ledgerProvider,\n tx,\n partyId,\n this.isMasterUser\n )\n const parsedTx = await parser.parseTransaction()\n return renderTransaction(parsedTx)\n }\n\n async toPrettyTransferObjects(\n getTransactionResponse: JsGetTransactionResponse,\n partyId: PartyId\n ): Promise<TransferObject[]> {\n const tx = getTransactionResponse.transaction\n const parser = new TransactionParser(\n this.ledgerProvider,\n tx,\n partyId,\n this.isMasterUser\n )\n return await parser.parseTransferObjects()\n }\n\n async toPrettyTransactionsPerParty(\n updates: JsGetUpdatesResponse[],\n parties: PartyId[]\n ): Promise<Map<PartyId, PrettyTransactions>> {\n const all = await Promise.all(\n parties.map(\n async (partyId): Promise<[PartyId, PrettyTransactions]> => [\n partyId,\n await this.toPrettyTransactions(updates, partyId),\n ]\n )\n )\n return new Map(all)\n }\n\n // returns object with JsActiveContract content\n // and contractId and interface view value extracted from it as separate fields for convenience\n toPrettyContract<T>(\n interfaceId: string,\n response: JsActiveContractEntryResponse,\n offset?: number\n ): PrettyContract<T> {\n const activeContract = response.contractEntry\n .JsActiveContract as JsActiveContract\n const { createdEvent } = activeContract\n return {\n contractId: createdEvent.contractId,\n activeContract,\n interfaceViewValue: ensureInterfaceViewIsPresent(\n createdEvent,\n interfaceId\n ).viewValue as T,\n fetchedAtOffset: offset,\n }\n }\n\n toQualifiedMemberId(memberId: string) {\n if (!memberId) throw new Error('memberId is required')\n\n return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`\n }\n}\n\nclass AllocationService {\n constructor(\n private core: CoreService,\n private readonly logger: Logger\n ) {}\n\n public async buildAllocationFactoryChoiceArgs(\n allocationSpecification: AllocationSpecification,\n expectedAdmin: PartyId,\n inputUtxos?: string[],\n requestedAt?: string\n ): Promise<AllocationFactory_Allocate> {\n const allocationSpecificationNormalized: AllocationSpecification = {\n ...allocationSpecification,\n settlement: {\n ...allocationSpecification.settlement,\n meta: allocationSpecification.settlement.meta ?? { values: {} },\n },\n transferLeg: {\n ...allocationSpecification.transferLeg,\n meta: allocationSpecification.transferLeg.meta ?? {\n values: {},\n },\n },\n }\n\n const inputHoldingCids = await this.core.getInputHoldingsCids({\n sender: allocationSpecificationNormalized.transferLeg.sender,\n inputUtxos: inputUtxos ?? [],\n instrumentAdmin:\n allocationSpecificationNormalized.transferLeg.instrumentId\n .admin,\n instrumentId:\n allocationSpecificationNormalized.transferLeg.instrumentId.id,\n })\n\n return {\n expectedAdmin,\n allocation: allocationSpecificationNormalized,\n requestedAt:\n requestedAt ??\n new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),\n inputHoldingCids:\n inputHoldingCids as unknown as ContractId<Holding>[],\n extraArgs: {\n context: { values: {} },\n meta: { values: {} },\n },\n }\n }\n\n async fetchAllocationFactoryChoiceContext(\n registryUrl: string,\n choiceArgs: AllocationFactory_Allocate,\n excludeDebugFields: boolean = true\n ): Promise<\n allocationInstructionRegistryTypes['schemas']['FactoryWithChoiceContext']\n > {\n return this.core\n .getTokenStandardClient(registryUrl)\n .post('/registry/allocation-instruction/v1/allocation-factory', {\n choiceArguments: choiceArgs as unknown as Record<string, never>,\n excludeDebugFields,\n })\n }\n\n async createAllocationInstructionFromContext(\n factoryId: string,\n choiceArgs: AllocationFactory_Allocate,\n choiceContext: allocationInstructionRegistryTypes['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n choiceArgs.extraArgs.context = {\n ...choiceContext.choiceContextData,\n values: choiceContext.choiceContextData?.values ?? {},\n }\n const exercise: ExerciseCommand = {\n templateId: ALLOCATION_FACTORY_INTERFACE_ID,\n contractId: factoryId,\n choice: 'AllocationFactory_Allocate',\n choiceArgument: choiceArgs,\n }\n return [exercise, choiceContext.disclosedContracts]\n }\n\n async createAllocationInstruction(\n allocationSpecification: AllocationSpecification,\n expectedAdmin: PartyId,\n registryUrl: string,\n inputUtxos?: string[],\n requestedAt?: string,\n prefetchedRegistryChoiceContext?: {\n factoryId: string\n choiceContext: allocationInstructionRegistryTypes['schemas']['ChoiceContext']\n }\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const choiceArgs = await this.buildAllocationFactoryChoiceArgs(\n allocationSpecification,\n expectedAdmin,\n inputUtxos,\n requestedAt\n )\n\n if (prefetchedRegistryChoiceContext) {\n return this.createAllocationInstructionFromContext(\n prefetchedRegistryChoiceContext.factoryId,\n choiceArgs,\n prefetchedRegistryChoiceContext.choiceContext\n )\n }\n\n const { factoryId, choiceContext } =\n await this.fetchAllocationFactoryChoiceContext(\n registryUrl,\n choiceArgs\n )\n return this.createAllocationInstructionFromContext(\n factoryId,\n choiceArgs,\n choiceContext\n )\n }\n\n private buildAllocationExerciseWithContext(\n templateId: string,\n contractId: string,\n choice:\n | 'Allocation_ExecuteTransfer'\n | 'Allocation_Withdraw'\n | 'Allocation_Cancel',\n choiceContext: allocationInstructionRegistryTypes['schemas']['ChoiceContext']\n ): [ExerciseCommand, DisclosedContract[]] {\n const exercise: ExerciseCommand = {\n templateId,\n contractId,\n choice,\n choiceArgument: {\n extraArgs: {\n context: choiceContext.choiceContextData,\n meta: EMPTY_META,\n },\n },\n }\n return [exercise, choiceContext.disclosedContracts ?? []]\n }\n\n async fetchExecuteTransferChoiceContext(\n allocationId: string,\n registryUrl: string\n ) {\n return this.core.getTokenStandardClient(registryUrl).post(\n '/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer',\n {\n excludeDebugFields: true,\n },\n {\n path: {\n allocationId,\n },\n }\n )\n }\n\n createExecuteTransferAllocationFromContext(\n allocationCid: string,\n choiceContext: allocationInstructionRegistryTypes['schemas']['ChoiceContext']\n ): [ExerciseCommand, DisclosedContract[]] {\n return this.buildAllocationExerciseWithContext(\n ALLOCATION_INTERFACE_ID,\n allocationCid,\n 'Allocation_ExecuteTransfer',\n choiceContext\n )\n }\n\n async createExecuteTransferAllocation(\n allocationCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: allocationInstructionRegistryTypes['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createExecuteTransferAllocationFromContext(\n allocationCid,\n prefetchedRegistryChoiceContext\n )\n }\n const choiceContext = await this.fetchExecuteTransferChoiceContext(\n allocationCid,\n registryUrl\n )\n return this.createExecuteTransferAllocationFromContext(\n allocationCid,\n choiceContext\n )\n }\n\n async fetchWithdrawAllocationChoiceContext(\n allocationCid: string,\n registryUrl: string\n ): Promise<allocationInstructionRegistryTypes['schemas']['ChoiceContext']> {\n return this.core.getTokenStandardClient(registryUrl).post(\n '/registry/allocations/v1/{allocationId}/choice-contexts/withdraw',\n {\n excludeDebugFields: true,\n },\n { path: { allocationId: allocationCid } }\n )\n }\n\n createWithdrawAllocationFromContext(\n allocationCid: string,\n choiceContext: allocationInstructionRegistryTypes['schemas']['ChoiceContext']\n ): [ExerciseCommand, DisclosedContract[]] {\n return this.buildAllocationExerciseWithContext(\n ALLOCATION_INTERFACE_ID,\n allocationCid,\n 'Allocation_Withdraw',\n choiceContext\n )\n }\n\n async createWithdrawAllocation(\n allocationCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: allocationInstructionRegistryTypes['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createWithdrawAllocationFromContext(\n allocationCid,\n prefetchedRegistryChoiceContext\n )\n }\n const choiceContext = await this.fetchWithdrawAllocationChoiceContext(\n allocationCid,\n registryUrl\n )\n return this.createWithdrawAllocationFromContext(\n allocationCid,\n choiceContext\n )\n }\n\n async fetchCancelAllocationChoiceContext(\n allocationCid: string,\n registryUrl: string\n ): Promise<allocationInstructionRegistryTypes['schemas']['ChoiceContext']> {\n return this.core.getTokenStandardClient(registryUrl).post(\n '/registry/allocations/v1/{allocationId}/choice-contexts/cancel',\n {\n excludeDebugFields: true,\n },\n { path: { allocationId: allocationCid } }\n )\n }\n\n createCancelAllocationFromContext(\n allocationCid: string,\n choiceContext: allocationInstructionRegistryTypes['schemas']['ChoiceContext']\n ): [ExerciseCommand, DisclosedContract[]] {\n return this.buildAllocationExerciseWithContext(\n ALLOCATION_INTERFACE_ID,\n allocationCid,\n 'Allocation_Cancel',\n choiceContext\n )\n }\n\n async createCancelAllocation(\n allocationCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: allocationInstructionRegistryTypes['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createCancelAllocationFromContext(\n allocationCid,\n prefetchedRegistryChoiceContext\n )\n }\n const choiceContext = await this.fetchCancelAllocationChoiceContext(\n allocationCid,\n registryUrl\n )\n return this.createCancelAllocationFromContext(\n allocationCid,\n choiceContext\n )\n }\n\n async createWithdrawAllocationInstruction(\n allocationInstructionCid: string\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const exercise: ExerciseCommand = {\n templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,\n contractId: allocationInstructionCid,\n choice: 'AllocationInstruction_Withdraw',\n choiceArgument: {\n extraArgs: {\n context: { values: {} },\n meta: { values: {} },\n },\n },\n }\n return [exercise, []]\n }\n\n async createUpdateAllocationInstruction(\n allocationInstructionCid: string,\n extraActors: PartyId[] = [],\n extraArgsContext: Record<string, unknown> = {},\n extraArgsMeta: Record<string, unknown> = {}\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const exercise: ExerciseCommand = {\n templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,\n contractId: allocationInstructionCid,\n choice: 'AllocationInstruction_Update',\n choiceArgument: {\n extraActors,\n extraArgs: {\n context: { values: extraArgsContext },\n meta: { values: extraArgsMeta },\n },\n },\n }\n return [exercise, []]\n }\n\n async createRejectAllocationRequest(\n allocationRequestCid: string,\n actor: PartyId\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const exercise: ExerciseCommand = {\n templateId: ALLOCATION_REQUEST_INTERFACE_ID,\n contractId: allocationRequestCid,\n choice: 'AllocationRequest_Reject',\n choiceArgument: {\n actor,\n extraArgs: {\n context: { values: {} },\n meta: { values: {} },\n },\n },\n }\n return [exercise, []]\n }\n\n async createWithdrawAllocationRequest(\n allocationRequestCid: string\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const exercise: ExerciseCommand = {\n templateId: ALLOCATION_REQUEST_INTERFACE_ID,\n contractId: allocationRequestCid,\n choice: 'AllocationRequest_Withdraw',\n choiceArgument: {\n extraArgs: {\n context: { values: {} },\n meta: { values: {} },\n },\n },\n }\n return [exercise, []]\n }\n}\n\nclass TransferService {\n constructor(\n private core: CoreService,\n private readonly logger: Logger\n ) {}\n\n public async buildTransferChoiceArgs(\n sender: PartyId,\n receiver: PartyId,\n amount: string,\n instrumentAdmin: PartyId,\n instrumentId: string,\n inputUtxos?: string[],\n memo?: string,\n expiryDate?: Date,\n meta?: Metadata,\n continueUntilCompletion?: boolean\n ): Promise<CreateTransferChoiceArgs> {\n const inputHoldingCids: string[] = await this.core.getInputHoldingsCids(\n {\n sender,\n instrumentAdmin,\n instrumentId,\n inputUtxos: inputUtxos ?? [],\n amount: new Decimal(amount),\n continueUntilCompletion: continueUntilCompletion ?? false,\n }\n )\n\n return {\n expectedAdmin: instrumentAdmin,\n transfer: {\n sender,\n receiver,\n amount,\n instrumentId: { admin: instrumentAdmin, id: instrumentId },\n requestedAt: new Date(\n Date.now() - REQUESTED_AT_SKEW_MS\n ).toISOString(),\n executeBefore: (\n expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1000)\n ).toISOString(),\n inputHoldingCids:\n inputHoldingCids as unknown as ContractId<Holding>[],\n meta: {\n values: {\n [TokenStandardService.MEMO_KEY]: memo || '',\n ...meta?.values,\n },\n },\n },\n extraArgs: {\n context: { values: {} },\n meta: { values: {} },\n },\n }\n }\n\n async fetchTransferFactoryChoiceContext(\n registryUrl: string,\n choiceArgs: CreateTransferChoiceArgs,\n excludeDebugFields: boolean = true\n ): Promise<\n transferInstructionRegistryTypes['schemas']['TransferFactoryWithChoiceContext']\n > {\n return await this.core\n .getTokenStandardClient(registryUrl)\n .post('/registry/transfer-instruction/v1/transfer-factory', {\n choiceArguments: choiceArgs as unknown as Record<string, never>,\n excludeDebugFields,\n })\n }\n\n async createTransferFromContext(\n factoryId: string,\n choiceArgs: CreateTransferChoiceArgs,\n choiceContext: transferInstructionRegistryTypes['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n this.logger.debug('Creating transfer from pre-fetched context...')\n choiceArgs.extraArgs.context = {\n ...choiceContext.choiceContextData,\n values: choiceContext.choiceContextData?.values ?? {},\n }\n const exercise: ExerciseCommand = {\n templateId: TRANSFER_FACTORY_INTERFACE_ID,\n contractId: factoryId,\n choice: 'TransferFactory_Transfer',\n choiceArgument: choiceArgs,\n }\n return [exercise, choiceContext.disclosedContracts]\n }\n\n // TODO: use named parameters\n async createTransfer(\n sender: PartyId,\n receiver: PartyId,\n amount: string,\n instrumentAdmin: PartyId, // TODO (#907): replace with registry call\n instrumentId: string,\n registryUrl: string,\n inputUtxos?: string[],\n memo?: string,\n expiryDate?: Date,\n meta?: Metadata,\n prefetchedRegistryChoiceContext?: {\n factoryId: string\n choiceContext: transferInstructionRegistryTypes['schemas']['ChoiceContext']\n },\n continueUntilCompletion?: boolean\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n try {\n const choiceArgs = await this.buildTransferChoiceArgs(\n sender,\n receiver,\n amount,\n instrumentAdmin,\n instrumentId,\n inputUtxos,\n memo,\n expiryDate,\n meta,\n continueUntilCompletion\n )\n\n if (prefetchedRegistryChoiceContext) {\n return this.createTransferFromContext(\n prefetchedRegistryChoiceContext.factoryId,\n choiceArgs,\n prefetchedRegistryChoiceContext.choiceContext\n )\n }\n\n const { factoryId, choiceContext } =\n await this.fetchTransferFactoryChoiceContext(\n registryUrl,\n choiceArgs\n )\n\n return this.createTransferFromContext(\n factoryId,\n choiceArgs,\n choiceContext\n )\n } catch (e) {\n this.logger.error('Failed to execute transfer:', e)\n throw e\n }\n }\n\n async fetchAcceptTransferInstructionChoiceContext(\n transferInstructionCid: string,\n registryUrl: string\n ): Promise<{\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }> {\n const client = this.core.getTokenStandardClient(registryUrl)\n const choiceContext = await client.post(\n '/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept',\n {\n excludeDebugFields: true,\n },\n {\n path: {\n transferInstructionId: transferInstructionCid,\n },\n }\n )\n return {\n choiceContextData: choiceContext.choiceContextData,\n disclosedContracts: choiceContext.disclosedContracts,\n }\n }\n\n async createAcceptTransferInstructionFromContext(\n transferInstructionCid: string,\n choiceContext: {\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n try {\n const exercise: ExerciseCommand = {\n templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,\n contractId: transferInstructionCid,\n choice: 'TransferInstruction_Accept',\n choiceArgument: {\n extraArgs: {\n context: choiceContext.choiceContextData,\n meta: { values: {} },\n },\n },\n }\n return [exercise, choiceContext.disclosedContracts]\n } catch (e) {\n this.logger.error(\n 'Failed to create accept transfer instruction:',\n e\n )\n throw e\n }\n }\n\n async exerciseDelegateProxyTransferInstructionAccept(\n proxyCid: string,\n transferInstructionCid: string,\n registryUrl: URL,\n featuredAppRightCid: string,\n beneficiaries: Beneficiaries[]\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const [acceptTransferInstructionContext, disclosedContracts] =\n await this.createAcceptTransferInstruction(\n transferInstructionCid,\n registryUrl.href\n )\n\n const choiceArgs = {\n cid: acceptTransferInstructionContext.contractId,\n proxyArg: {\n featuredAppRightCid: featuredAppRightCid,\n beneficiaries: beneficiaries,\n choiceArg: acceptTransferInstructionContext.choiceArgument,\n },\n }\n\n return [\n {\n templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,\n contractId: proxyCid,\n choice: 'DelegateProxy_TransferInstruction_Accept',\n choiceArgument: choiceArgs,\n },\n disclosedContracts,\n ]\n }\n\n async exerciseDelegateProxyTransferInstructionReject(\n proxyCid: string,\n transferInstructionCid: string,\n registryUrl: URL,\n featuredAppRightCid: string,\n beneficiaries: Beneficiaries[]\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const [rejectTransferInstructionContext, disclosedContracts] =\n await this.createRejectTransferInstruction(\n transferInstructionCid,\n registryUrl.href\n )\n\n const choiceArgs = {\n cid: rejectTransferInstructionContext.contractId,\n proxyArg: {\n featuredAppRightCid: featuredAppRightCid,\n beneficiaries,\n choiceArg: rejectTransferInstructionContext.choiceArgument,\n },\n }\n\n return [\n {\n templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,\n contractId: proxyCid,\n choice: 'DelegateProxy_TransferInstruction_Reject',\n choiceArgument: choiceArgs,\n },\n disclosedContracts,\n ]\n }\n\n async exerciseDelegateProxyTransferInstructioWithdraw(\n proxyCid: string,\n transferInstructionCid: string,\n registryUrl: URL,\n featuredAppRightCid: string,\n beneficiaries: Beneficiaries[]\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const [withdrawTransferInstructionContext, disclosedContracts] =\n await this.createWithdrawTransferInstruction(\n transferInstructionCid,\n registryUrl.href\n )\n\n const sumOfWeights: number = beneficiaries.reduce(\n (totalWeight, beneficiary) => totalWeight + beneficiary.weight,\n 0\n )\n\n if (sumOfWeights > 1.0) {\n throw new Error('Sum of beneficiary weights is larger than 1.')\n }\n\n const choiceArgs = {\n cid: withdrawTransferInstructionContext.contractId,\n proxyArg: {\n featuredAppRightCid: featuredAppRightCid,\n beneficiaries,\n choiceArg: withdrawTransferInstructionContext.choiceArgument,\n },\n }\n\n return [\n {\n templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,\n contractId: proxyCid,\n choice: 'DelegateProxy_TransferInstruction_Withdraw',\n choiceArgument: choiceArgs,\n },\n disclosedContracts,\n ]\n }\n\n async createAcceptTransferInstruction(\n transferInstructionCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: transferInstructionRegistryTypes['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createAcceptTransferInstructionFromContext(\n transferInstructionCid,\n {\n choiceContextData:\n prefetchedRegistryChoiceContext.choiceContextData,\n disclosedContracts:\n prefetchedRegistryChoiceContext.disclosedContracts,\n }\n )\n }\n const choiceContext =\n await this.fetchAcceptTransferInstructionChoiceContext(\n transferInstructionCid,\n registryUrl\n )\n return this.createAcceptTransferInstructionFromContext(\n transferInstructionCid,\n choiceContext\n )\n }\n\n async fetchRejectTransferInstructionChoiceContext(\n transferInstructionCid: string,\n registryUrl: string\n ): Promise<{\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }> {\n const client = this.core.getTokenStandardClient(registryUrl)\n const choiceContext = await client.post(\n '/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject',\n {\n excludeDebugFields: true,\n },\n {\n path: {\n transferInstructionId: transferInstructionCid,\n },\n }\n )\n return {\n choiceContextData: choiceContext.choiceContextData,\n disclosedContracts: choiceContext.disclosedContracts,\n }\n }\n\n async createRejectTransferInstructionFromContext(\n transferInstructionCid: string,\n choiceContext: {\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n try {\n const exercise: ExerciseCommand = {\n templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,\n contractId: transferInstructionCid,\n choice: 'TransferInstruction_Reject',\n choiceArgument: {\n extraArgs: {\n context: choiceContext.choiceContextData,\n meta: { values: {} },\n },\n },\n }\n return [exercise, choiceContext.disclosedContracts]\n } catch (e) {\n this.logger.error(\n 'Failed to create reject transfer instruction:',\n e\n )\n throw e\n }\n }\n\n async createRejectTransferInstruction(\n transferInstructionCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: transferInstructionRegistryTypes['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createRejectTransferInstructionFromContext(\n transferInstructionCid,\n {\n choiceContextData:\n prefetchedRegistryChoiceContext.choiceContextData,\n disclosedContracts:\n prefetchedRegistryChoiceContext.disclosedContracts,\n }\n )\n }\n const choiceContext =\n await this.fetchRejectTransferInstructionChoiceContext(\n transferInstructionCid,\n registryUrl\n )\n return this.createRejectTransferInstructionFromContext(\n transferInstructionCid,\n choiceContext\n )\n }\n\n async fetchWithdrawTransferInstructionChoiceContext(\n transferInstructionCid: string,\n registryUrl: string\n ): Promise<{\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }> {\n const client = this.core.getTokenStandardClient(registryUrl)\n\n const choiceContext = await client.post(\n '/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw',\n {\n excludeDebugFields: true,\n },\n {\n path: {\n transferInstructionId: transferInstructionCid,\n },\n }\n )\n return {\n choiceContextData: choiceContext.choiceContextData,\n disclosedContracts: choiceContext.disclosedContracts,\n }\n }\n\n async createWithdrawTransferInstructionFromContext(\n transferInstructionCid: string,\n choiceContext: {\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n try {\n const exercise: ExerciseCommand = {\n templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,\n contractId: transferInstructionCid,\n choice: 'TransferInstruction_Withdraw',\n choiceArgument: {\n extraArgs: {\n context: choiceContext.choiceContextData,\n meta: { values: {} },\n },\n },\n }\n return [exercise, choiceContext.disclosedContracts]\n } catch (e) {\n this.logger.error(\n 'Failed to create withdraw transfer instruction:',\n e\n )\n throw e\n }\n }\n\n async createWithdrawTransferInstruction(\n transferInstructionCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: transferInstructionRegistryTypes['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createWithdrawTransferInstructionFromContext(\n transferInstructionCid,\n {\n choiceContextData:\n prefetchedRegistryChoiceContext.choiceContextData,\n disclosedContracts:\n prefetchedRegistryChoiceContext.disclosedContracts,\n }\n )\n }\n const choiceContext =\n await this.fetchWithdrawTransferInstructionChoiceContext(\n transferInstructionCid,\n registryUrl\n )\n return this.createWithdrawTransferInstructionFromContext(\n transferInstructionCid,\n choiceContext\n )\n }\n\n async createTransferInstruction(\n transferInstructionCid: string,\n registryUrl: string,\n instructionChoice: 'Accept' | 'Reject' | 'Withdraw',\n prefetchedRegistryChoiceContext?: transferInstructionRegistryTypes['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n switch (instructionChoice) {\n case 'Accept':\n return this.createAcceptTransferInstruction(\n transferInstructionCid,\n registryUrl,\n prefetchedRegistryChoiceContext\n )\n case 'Reject':\n return this.createRejectTransferInstruction(\n transferInstructionCid,\n registryUrl,\n prefetchedRegistryChoiceContext\n )\n case 'Withdraw':\n return this.createWithdrawTransferInstruction(\n transferInstructionCid,\n registryUrl,\n prefetchedRegistryChoiceContext\n )\n }\n }\n}\n\nexport class TokenStandardService {\n static readonly MEMO_KEY = 'splice.lfdecentralizedtrust.org/reason'\n\n readonly core: CoreService\n readonly allocation: AllocationService\n readonly transfer: TransferService\n\n constructor(\n private ledgerProvider: AbstractLedgerProvider,\n private logger: Logger,\n private accessTokenProvider: AccessTokenProvider,\n private readonly isMasterUser: boolean\n ) {\n this.core = new CoreService(\n ledgerProvider,\n logger,\n accessTokenProvider,\n isMasterUser\n )\n this.allocation = new AllocationService(this.core, this.logger)\n this.transfer = new TransferService(this.core, this.logger)\n }\n\n async getInstrumentById(registryUrl: string, instrumentId: string) {\n try {\n const params: Record<string, unknown> = {\n path: {\n instrumentId,\n },\n }\n\n const client = this.core.getTokenStandardClient(registryUrl)\n\n return client.get(\n '/registry/metadata/v1/instruments/{instrumentId}',\n params\n )\n } catch (e) {\n this.logger.error(e)\n throw new Error(\n `Instrument id ${instrumentId} does not exist for this instrument admin.`,\n { cause: e }\n )\n }\n }\n\n async getInstrumentAdmin(registryUrl: string): Promise<string> {\n const client = this.core.getTokenStandardClient(registryUrl)\n\n const info = await client.get('/registry/metadata/v1/info')\n\n return info.adminId\n }\n\n async listInstruments(\n registryUrl: string,\n pageSize?: number,\n pageToken?: string\n ) {\n const client = this.core.getTokenStandardClient(registryUrl)\n return client.get('/registry/metadata/v1/instruments', {\n query: {\n ...(pageSize && { pageSize }),\n ...(pageToken && { pageToken }),\n },\n })\n }\n\n async instrumentsToAsset(registryUrl: string) {\n let instrumentsResponse = await this.listInstruments(registryUrl)\n const instruments = [...instrumentsResponse.instruments]\n\n while (instrumentsResponse.nextPageToken) {\n instrumentsResponse = await this.listInstruments(\n registryUrl,\n undefined,\n instrumentsResponse.nextPageToken\n )\n instruments.push(...instrumentsResponse.instruments)\n }\n const instrumentAdmin = await this.getInstrumentAdmin(registryUrl)\n return instruments.map((instrument) => ({\n id: instrument.id,\n displayName: instrument.name,\n symbol: instrument.symbol,\n registryUrl,\n admin: instrumentAdmin,\n }))\n }\n\n async registriesToAssets(registryUrls: string[]) {\n const allInstruments: {\n id: string\n displayName: string\n symbol: string\n registryUrl: string\n admin: PartyId\n }[] = []\n for (const registryUrl of registryUrls) {\n const instruments = await this.instrumentsToAsset(registryUrl)\n allInstruments.push(...instruments)\n }\n return allInstruments\n }\n\n // <T> is shape of viewValue related to queried interface.\n // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen\n async listContractsByInterface<T = ViewValue>(\n interfaceId: string,\n partyId?: PartyId,\n limit?: number,\n offset?: number,\n continueUntilCompletion?: boolean\n ): Promise<PrettyContract<T>[]> {\n return this.core.listContractsByInterface<T>(\n interfaceId,\n partyId,\n limit,\n offset,\n continueUntilCompletion\n )\n }\n\n async listHoldingTransactions(\n partyId: PartyId,\n afterOffset?: number,\n beforeOffset?: number\n ): Promise<PrettyTransactions> {\n try {\n this.logger.debug('Set or query offset')\n const afterOffsetOrLatest =\n afterOffset ??\n (\n await this.ledgerProvider.request<Ops.GetV2StateLatestPrunedOffsets>(\n {\n method: 'ledgerApi',\n params: {\n resource: '/v2/state/latest-pruned-offsets',\n requestMethod: 'get',\n },\n }\n )\n ).participantPrunedUpToInclusive!\n const beforeOffsetOrLatest =\n beforeOffset ??\n (\n await this.ledgerProvider.request<Ops.GetV2StateLedgerEnd>({\n method: 'ledgerApi',\n params: {\n resource: '/v2/state/ledger-end',\n requestMethod: 'get',\n },\n })\n ).offset!\n\n this.logger.debug(afterOffsetOrLatest, 'Using offset')\n const updatesResponse: JsGetUpdatesResponse[] =\n await this.ledgerProvider.request<Ops.PostV2UpdatesFlats>({\n method: 'ledgerApi',\n params: {\n resource: '/v2/updates/flats',\n requestMethod: 'post',\n query: {},\n body: {\n updateFormat: {\n includeTransactions: {\n eventFormat: EventFilterBySetup({\n interfaceIds:\n TokenStandardTransactionInterfaces,\n isMasterUser: this.isMasterUser,\n partyId: partyId,\n includeWildcard: true,\n }),\n transactionShape:\n 'TRANSACTION_SHAPE_LEDGER_EFFECTS',\n },\n },\n beginExclusive: afterOffsetOrLatest,\n endInclusive: beforeOffsetOrLatest,\n verbose: false,\n } as unknown as Ops.PostV2UpdatesFlats['ledgerApi']['params']['body'],\n },\n })\n\n return this.core.toPrettyTransactions(\n updatesResponse,\n partyId\n // this.ledgerProvider\n )\n } catch (err) {\n this.logger.error('Failed to list holding transactions.', err)\n throw err\n }\n }\n\n async getTransactionById(\n updateId: string,\n partyId: PartyId\n ): Promise<Transaction> {\n const transactionFormat: TransactionFormat = {\n eventFormat: EventFilterBySetup({\n interfaceIds: TokenStandardTransactionInterfaces,\n isMasterUser: this.isMasterUser,\n partyId: partyId,\n includeWildcard: true,\n }),\n transactionShape: 'TRANSACTION_SHAPE_LEDGER_EFFECTS',\n }\n\n const getTransactionResponse =\n await this.ledgerProvider.request<Ops.PostV2UpdatesTransactionById>(\n {\n method: 'ledgerApi',\n params: {\n resource: '/v2/updates/transaction-by-id',\n requestMethod: 'post',\n body: {\n updateId,\n transactionFormat,\n } as Ops.PostV2UpdatesTransactionById['ledgerApi']['params']['body'],\n },\n }\n )\n\n return this.core.toPrettyTransaction(getTransactionResponse, partyId)\n }\n\n async getTransferObjectsById(\n updateId: string,\n partyId: PartyId\n ): Promise<TransferObject[]> {\n const transactionFormat: TransactionFormat = {\n eventFormat: EventFilterBySetup({\n interfaceIds: TokenStandardTransactionInterfaces,\n isMasterUser: this.isMasterUser,\n partyId: partyId,\n includeWildcard: true,\n }),\n transactionShape: 'TRANSACTION_SHAPE_LEDGER_EFFECTS',\n }\n\n const getTransactionResponse =\n await this.ledgerProvider.request<Ops.PostV2UpdatesTransactionById>(\n {\n method: 'ledgerApi',\n params: {\n resource: '/v2/updates/transaction-by-id',\n requestMethod: 'post',\n body: {\n updateId,\n transactionFormat,\n } as Ops.PostV2UpdatesTransactionById['ledgerApi']['params']['body'],\n },\n }\n )\n\n return this.core.toPrettyTransferObjects(\n getTransactionResponse,\n partyId\n )\n }\n\n async getInputHoldingsCids(\n sender: PartyId,\n inputUtxos?: string[],\n amount?: Decimal\n ) {\n if (amount) {\n return this.core.getInputHoldingsCids({\n sender,\n inputUtxos: inputUtxos ?? [],\n amount,\n })\n } else {\n return this.core.getInputHoldingsCids({\n sender,\n inputUtxos: inputUtxos ?? [],\n })\n }\n }\n\n async createDelegateProxyTransfer(\n sender: PartyId,\n receiver: PartyId,\n amount: string,\n instrumentAdmin: PartyId, // TODO (#907): replace with registry call\n instrumentId: string,\n registryUrl: string,\n featuredAppRightCid: string,\n proxyCid: string,\n beneficiaries: Beneficiaries[],\n inputUtxos?: string[],\n memo?: string,\n expiryDate?: Date,\n meta?: Metadata\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const [transferCommand, disclosedContracts] =\n await this.transfer.createTransfer(\n sender,\n receiver,\n amount,\n instrumentAdmin,\n instrumentId,\n registryUrl,\n inputUtxos,\n memo,\n expiryDate,\n meta\n )\n\n const sumOfWeights: number = beneficiaries.reduce(\n (totalWeight, beneficiary) => totalWeight + beneficiary.weight,\n 0\n )\n\n if (sumOfWeights > 1.0) {\n throw new Error('Sum of beneficiary weights is larger than 1.')\n }\n\n const choiceArgs = {\n cid: transferCommand.contractId,\n proxyArg: {\n featuredAppRightCid: featuredAppRightCid,\n beneficiaries,\n choiceArg: transferCommand.choiceArgument,\n },\n }\n\n const exercise: ExerciseCommand = {\n templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,\n contractId: proxyCid,\n choice: 'DelegateProxy_TransferFactory_Transfer',\n choiceArgument: choiceArgs,\n }\n\n return [exercise, disclosedContracts]\n }\n\n async exerciseDelegateProxyTransferInstructionAccept(\n exchangeParty: PartyId,\n proxyCid: string,\n transferInstructionCid: string,\n registryUrl: string,\n featuredAppRightCid: string\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const [acceptTransferInstructionContext, disclosedContracts] =\n await this.transfer.createAcceptTransferInstruction(\n transferInstructionCid,\n registryUrl\n )\n\n const choiceArgs = {\n cid: acceptTransferInstructionContext.contractId,\n proxyArg: {\n featuredAppRightCid: featuredAppRightCid,\n beneficiaries: [\n {\n beneficiary: exchangeParty,\n weight: 1.0,\n },\n ],\n choiceArg: acceptTransferInstructionContext.choiceArgument,\n },\n }\n\n return [\n {\n templateId:\n '#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy',\n contractId: proxyCid,\n choice: 'DelegateProxy_TransferInstruction_Accept',\n choiceArgument: choiceArgs,\n },\n disclosedContracts,\n ]\n }\n\n static isHoldingLocked(\n holding: Holding | TxParseHolding,\n currentTime: Date = new Date()\n ): boolean {\n const lock = holding.lock\n if (!lock) return false\n\n const expiresAt = lock.expiresAt\n if (!expiresAt) return true\n\n const expiresAtDate = new Date(expiresAt)\n return currentTime < expiresAtDate\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,uBAAuB;AAI7B,MAAM,aAAuB,EAAE,QAAQ,CAAC,EAAE;AAkC1C,IAAa,cAAb,MAAa,YAAY;CACrB,YACI,gBACA,QACA,qBACA,cACF;EAJU,KAAA,iBAAA;EACS,KAAA,SAAA;EACT,KAAA,sBAAA;EACS,KAAA,eAAA;CAClB;CAEH,uBAAuB,aAA0C;EAC7D,OAAO,IAAI,oBACP,aACA,KAAK,QACL,KAAK,mBACT;CACJ;CAEA,MAAM,qBAAqB,SAOxB;EACC,MAAM,EAAE,QAAQ,iBAAiB,iBAAiB;EAClD,MAAM,sBAAM,IAAI,KAAK;EACrB,IAAI,QAAQ,cAAc,QAAQ,WAAW,SAAS,GAClD,OAAO,QAAQ;EAEnB,MAAM,iBAAiB,MAAM,KAAK,yBAC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AI,KAAK,GACtB;EACP,MAAM,OAAO,QAAQ;EACrB,IAAI,CAAC,MAAM,OAAO;EAElB,MAAM,YAAY,KAAK;EACvB,IAAI,CAAC,WAAW,OAAO;EAGvB,OAAO,cAAc,IADK,KAAK,SACE;CACrC;AACJ;AArYoB,gBAAA,sBAAA,YAAW,wCAAA"}
1
+ {"version":3,"file":"index.js","names":["txUpdate"],"sources":["../src/token-standard-service.ts"],"sourcesContent":["// Copyright (c) 2025-2026 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport {\n TokenStandardClient,\n TRANSFER_FACTORY_INTERFACE_ID,\n HOLDING_INTERFACE_ID,\n ALLOCATION_FACTORY_INTERFACE_ID,\n ALLOCATION_INTERFACE_ID,\n ALLOCATION_REQUEST_INTERFACE_ID,\n ALLOCATION_INSTRUCTION_INTERFACE_ID,\n TRANSFER_INSTRUCTION_INTERFACE_ID,\n HoldingView,\n AllocationFactory_Allocate,\n AllocationSpecification,\n Transfer,\n ExtraArgs,\n Metadata,\n FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,\n Holding,\n Beneficiaries,\n OffLedger,\n} from '@canton-network/core-token-standard'\nimport {\n EventFilterBySetup,\n type LedgerCommonSchemas,\n} from '@canton-network/core-ledger-client-types'\nimport { ContractId, Logger, PartyId } from '@canton-network/core-types'\nimport { ACSReader, AcsOptions } from '@canton-network/core-acs-reader'\nimport {\n TokenStandardTransactionInterfaces,\n ensureInterfaceViewIsPresent,\n TransactionParser,\n PrettyContract,\n renderTransaction,\n ViewValue,\n PrettyTransactions,\n Transaction,\n TransferObject,\n} from '@canton-network/core-tx-parser'\nimport { AccessTokenProvider } from '@canton-network/core-wallet-auth'\nimport {\n AbstractLedgerProvider,\n Ops,\n} from '@canton-network/core-provider-ledger'\nimport { Decimal } from 'decimal.js'\n\nconst REQUESTED_AT_SKEW_MS = 60_000\n\nexport type ExerciseCommand = LedgerCommonSchemas['ExerciseCommand']\nexport type DisclosedContract = LedgerCommonSchemas['DisclosedContract']\nconst EMPTY_META: Metadata = { values: {} }\n\ntype JsGetActiveContractsResponse =\n LedgerCommonSchemas['JsGetActiveContractsResponse']\ntype JsGetUpdatesResponse = Ops.PostV2Updates['ledgerApi']['result'][number]\ntype JsGetUpdateResponse = LedgerCommonSchemas['JsGetUpdateResponse']\ntype OffsetCheckpoint2 = LedgerCommonSchemas['OffsetCheckpoint2']\ntype JsTransaction = LedgerCommonSchemas['JsTransaction']\ntype UpdateFormat = LedgerCommonSchemas['UpdateFormat']\n\ntype JsActiveContract = LedgerCommonSchemas['JsActiveContract']\n\ntype OffsetCheckpointUpdate = {\n update: { OffsetCheckpoint: OffsetCheckpoint2 }\n}\ntype TransactionUpdate = {\n update: { Transaction: { value: JsTransaction } }\n}\n\ntype JsActiveContractEntryResponse = JsGetActiveContractsResponse & {\n contractEntry: {\n JsActiveContract: {\n createdEvent: LedgerCommonSchemas['CreatedEvent']\n }\n }\n}\n\ntype CreateTransferChoiceArgs = {\n expectedAdmin: PartyId\n transfer: Transfer\n extraArgs: ExtraArgs\n}\n\nexport class CoreService {\n constructor(\n private ledgerProvider: AbstractLedgerProvider,\n private readonly logger: Logger,\n private accessTokenProvider: AccessTokenProvider,\n private readonly isMasterUser: boolean\n ) {}\n\n getTokenStandardClient(registryUrl: string): TokenStandardClient {\n return new TokenStandardClient(\n registryUrl,\n this.logger,\n this.accessTokenProvider\n )\n }\n\n async getInputHoldingsCids(options: {\n sender: PartyId\n instrumentAdmin?: string\n instrumentId?: string\n inputUtxos?: string[]\n amount?: Decimal\n continueUntilCompletion?: boolean\n }) {\n const { sender, instrumentAdmin, instrumentId } = options\n const now = new Date()\n if (options.inputUtxos && options.inputUtxos.length > 0) {\n return options.inputUtxos\n }\n const senderHoldings = await this.listContractsByInterface<HoldingView>(\n HOLDING_INTERFACE_ID,\n sender,\n undefined,\n undefined,\n options.continueUntilCompletion\n )\n if (senderHoldings.length === 0) {\n throw new Error(\n \"Sender has no holdings, so transfer can't be executed.\"\n )\n }\n\n const unlockedSenderHoldings = senderHoldings.filter(\n (utxo) => !TokenStandardService.isHoldingLocked(utxo, now)\n )\n\n if (unlockedSenderHoldings.length > 100) {\n this.logger.warn(`Sender has more than 100 unlocked utxos.`)\n }\n\n const unlockedHoldingsForInstrument =\n instrumentAdmin && instrumentId\n ? await CoreService.filterHoldingsByInstrument({\n holdings: unlockedSenderHoldings,\n instrumentAdmin,\n instrumentId,\n })\n : unlockedSenderHoldings\n\n if (options.amount) {\n return CoreService.getInputHoldingsCidsForAmount(\n options.amount,\n unlockedHoldingsForInstrument\n )\n } else {\n return unlockedHoldingsForInstrument.map((h) => h.contractId)\n }\n }\n\n static async filterHoldingsByInstrument(options: {\n holdings: PrettyContract<HoldingView>[]\n instrumentAdmin: string\n instrumentId: string\n }) {\n const { holdings, instrumentAdmin, instrumentId } = options\n return holdings.filter((utxo) => {\n return (\n utxo.interfaceViewValue.instrumentId.id === instrumentId &&\n utxo.interfaceViewValue.instrumentId.admin === instrumentAdmin\n )\n })\n }\n\n static async getInputHoldingsCidsForAmount(\n amount: Decimal,\n unlockedSenderHoldings: PrettyContract<HoldingView>[]\n ) {\n //find holding that is the exact amount if possible\n const exactAmount = unlockedSenderHoldings.find((holding) =>\n new Decimal(holding.interfaceViewValue.amount).equals(amount)\n )\n\n if (exactAmount) {\n return [exactAmount.contractId]\n }\n\n //sort holdings from smallest to largest\n const sortedUnlockedSenderHoldings = unlockedSenderHoldings.toSorted(\n (a, b) =>\n new Decimal(a.interfaceViewValue.amount).comparedTo(\n new Decimal(b.interfaceViewValue.amount)\n )\n )\n\n const largestHoldingAmount = sortedUnlockedSenderHoldings.pop()\n\n if (!largestHoldingAmount) {\n throw new Error(`Sender doesn't have any unlocked holdings`)\n }\n\n let currentSum = new Decimal(\n largestHoldingAmount.interfaceViewValue.amount\n )\n const cIds = [largestHoldingAmount.contractId]\n\n for (const h of sortedUnlockedSenderHoldings) {\n if (currentSum.greaterThanOrEqualTo(amount)) {\n break\n }\n\n const currentHoldingAmount = new Decimal(\n h.interfaceViewValue.amount\n )\n\n currentSum = currentSum.plus(currentHoldingAmount)\n cIds.push(h.contractId)\n }\n\n if (currentSum.lessThan(amount)) {\n throw new Error(\n `Sender doesn't have sufficient funds for this transfer. Missing amount: ${amount.minus(currentSum)}`\n )\n }\n\n if (cIds.length > 100) {\n throw new Error(\n `Exceeded the maximum of 100 utxos in 1 transaction`\n )\n }\n\n return cIds\n }\n\n async listContractsByInterface<T = ViewValue>(\n interfaceId: string,\n partyId?: PartyId,\n limit?: number,\n offset?: number,\n continueUntilCompletion?: boolean\n ): Promise<PrettyContract<T>[]> {\n try {\n const ledgerEnd =\n offset ??\n (\n await this.ledgerProvider.request<Ops.GetV2StateLedgerEnd>({\n method: 'ledgerApi',\n params: {\n resource: '/v2/state/ledger-end',\n requestMethod: 'get',\n query: {},\n },\n })\n ).offset!\n\n const options: AcsOptions = {\n offset: ledgerEnd,\n interfaceIds: [interfaceId],\n parties: [partyId!],\n filterByParty: true,\n continueUntilCompletion: Boolean(continueUntilCompletion),\n }\n\n if (limit !== undefined) {\n options.limit = limit\n }\n\n //TODO: based on the. provider design we can't pass in the continue to completion, so right now it's defaulted to true in the ledger provider. we need to figure out how to add an ACS functionality and ensure better composability\n this.logger.info(\n `continue to completion: ${Boolean(continueUntilCompletion)}`\n )\n\n const reader = new ACSReader(this.ledgerProvider)\n\n const acsResponses: JsGetActiveContractsResponse[] =\n (await reader.raw.read(\n options\n ))! as JsGetActiveContractsResponse[]\n\n /* This filters out responses with entries of:\n - JsEmpty\n - JsIncompleteAssigned\n - JsIncompleteUnassigned\n while leaving JsActiveContract.\n It works fine only with single synchronizer\n TODO (#353) add support for multiple synchronizers\n */\n const isActiveContractEntry = (\n acsResponse: JsGetActiveContractsResponse\n ): acsResponse is JsActiveContractEntryResponse =>\n acsResponse.contractEntry != null &&\n 'JsActiveContract' in acsResponse.contractEntry &&\n acsResponse.contractEntry.JsActiveContract != null &&\n acsResponse.contractEntry.JsActiveContract.createdEvent != null\n\n const results: PrettyContract<T>[] = acsResponses\n .filter(isActiveContractEntry)\n .map((response) =>\n this.toPrettyContract<T>(\n interfaceId,\n response as JsActiveContractEntryResponse,\n ledgerEnd\n )\n )\n return results\n } catch (err) {\n this.logger.error(\n `Failed to list contracts of interface ${interfaceId}`,\n err\n )\n throw err\n }\n }\n\n async toPrettyTransactions(\n updates: JsGetUpdatesResponse[],\n partyId: PartyId\n ): Promise<PrettyTransactions> {\n // Runtime filters that also let TS know which of OneOfs types to check against\n const isOffsetCheckpointUpdate = (\n updateResponse: JsGetUpdatesResponse\n ): updateResponse is OffsetCheckpointUpdate =>\n updateResponse.update != null &&\n 'OffsetCheckpoint' in updateResponse.update\n\n const isTransactionUpdate = (\n updateResponse: JsGetUpdatesResponse\n ): updateResponse is TransactionUpdate =>\n updateResponse.update != null &&\n 'Transaction' in updateResponse.update &&\n !!updateResponse.update.Transaction?.value\n\n const offsetCheckpoints: number[] = updates\n .filter(isOffsetCheckpointUpdate)\n .map(\n (update) =>\n (update.update as OffsetCheckpointUpdate['update'])\n .OffsetCheckpoint.value.offset\n )\n const latestCheckpointOffset =\n offsetCheckpoints.length > 0 ? Math.max(...offsetCheckpoints) : 0\n\n const transactions: Transaction[] = await Promise.all(\n updates\n // exclude OffsetCheckpoint, Reassignment, TopologyTransaction\n .filter(isTransactionUpdate)\n .map(async (update) => {\n const txUpdate = update as TransactionUpdate\n const tx = txUpdate.update.Transaction\n .value as JsTransaction\n const parser = new TransactionParser(\n this.ledgerProvider,\n tx,\n partyId,\n this.isMasterUser\n )\n\n return await parser.parseTransaction()\n })\n )\n\n const transactionOffsets = transactions\n .map((tx) => tx.offset)\n .filter((offset): offset is number => offset !== undefined)\n\n return {\n // OffsetCheckpoint can be anywhere... or not at all, maybe\n nextOffset: Math.max(\n latestCheckpointOffset,\n ...(transactionOffsets.length > 0 ? transactionOffsets : [0])\n ),\n transactions: transactions\n .filter((tx) => tx.events.length > 0)\n .map(renderTransaction),\n }\n }\n\n async toPrettyTransaction(\n getUpdateResponse: JsGetUpdateResponse,\n partyId: PartyId\n ): Promise<Transaction> {\n const tx = this.getTransactionFromUpdate(getUpdateResponse)\n const parser = new TransactionParser(\n this.ledgerProvider,\n tx,\n partyId,\n this.isMasterUser\n )\n const parsedTx = await parser.parseTransaction()\n return renderTransaction(parsedTx)\n }\n\n async toPrettyTransferObjects(\n getUpdateResponse: JsGetUpdateResponse,\n partyId: PartyId\n ): Promise<TransferObject[]> {\n const tx = this.getTransactionFromUpdate(getUpdateResponse)\n const parser = new TransactionParser(\n this.ledgerProvider,\n tx,\n partyId,\n this.isMasterUser\n )\n return await parser.parseTransferObjects()\n }\n\n private getTransactionFromUpdate(\n getUpdateResponse: JsGetUpdateResponse\n ): JsTransaction {\n const update = getUpdateResponse.update\n if (!update || !('Transaction' in update)) {\n throw new Error('Expected transaction update')\n }\n return update.Transaction.value\n }\n\n async toPrettyTransactionsPerParty(\n updates: JsGetUpdatesResponse[],\n parties: PartyId[]\n ): Promise<Map<PartyId, PrettyTransactions>> {\n const all = await Promise.all(\n parties.map(\n async (partyId): Promise<[PartyId, PrettyTransactions]> => [\n partyId,\n await this.toPrettyTransactions(updates, partyId),\n ]\n )\n )\n return new Map(all)\n }\n\n // returns object with JsActiveContract content\n // and contractId and interface view value extracted from it as separate fields for convenience\n toPrettyContract<T>(\n interfaceId: string,\n response: JsActiveContractEntryResponse,\n offset?: number\n ): PrettyContract<T> {\n const activeContract = response.contractEntry\n .JsActiveContract as JsActiveContract\n const { createdEvent } = activeContract\n return {\n contractId: createdEvent.contractId,\n activeContract,\n interfaceViewValue: ensureInterfaceViewIsPresent(\n createdEvent,\n interfaceId\n ).viewValue as T,\n fetchedAtOffset: offset,\n }\n }\n\n toQualifiedMemberId(memberId: string) {\n if (!memberId) throw new Error('memberId is required')\n\n return /^(PAR|MED)::/.test(memberId) ? memberId : `PAR::${memberId}`\n }\n}\n\nclass AllocationService {\n constructor(\n private core: CoreService,\n private readonly logger: Logger\n ) {}\n\n public async buildAllocationFactoryChoiceArgs(\n allocationSpecification: AllocationSpecification,\n expectedAdmin: PartyId,\n inputUtxos?: string[],\n requestedAt?: string\n ): Promise<AllocationFactory_Allocate> {\n const allocationSpecificationNormalized: AllocationSpecification = {\n ...allocationSpecification,\n settlement: {\n ...allocationSpecification.settlement,\n meta: allocationSpecification.settlement.meta ?? { values: {} },\n },\n transferLeg: {\n ...allocationSpecification.transferLeg,\n meta: allocationSpecification.transferLeg.meta ?? {\n values: {},\n },\n },\n }\n\n const inputHoldingCids = await this.core.getInputHoldingsCids({\n sender: allocationSpecificationNormalized.transferLeg.sender,\n inputUtxos: inputUtxos ?? [],\n instrumentAdmin:\n allocationSpecificationNormalized.transferLeg.instrumentId\n .admin,\n instrumentId:\n allocationSpecificationNormalized.transferLeg.instrumentId.id,\n })\n\n return {\n expectedAdmin,\n allocation: allocationSpecificationNormalized,\n requestedAt:\n requestedAt ??\n new Date(Date.now() - REQUESTED_AT_SKEW_MS).toISOString(),\n inputHoldingCids:\n inputHoldingCids as unknown as ContractId<Holding>[],\n extraArgs: {\n context: { values: {} },\n meta: { values: {} },\n },\n }\n }\n\n async fetchAllocationFactoryChoiceContext(\n registryUrl: string,\n choiceArgs: AllocationFactory_Allocate,\n excludeDebugFields: boolean = true\n ): Promise<\n OffLedger.AllocationInstructionV1.components['schemas']['FactoryWithChoiceContext']\n > {\n return this.core\n .getTokenStandardClient(registryUrl)\n .post('/registry/allocation-instruction/v1/allocation-factory', {\n choiceArguments: choiceArgs as unknown as Record<string, never>,\n excludeDebugFields,\n })\n }\n\n async createAllocationInstructionFromContext(\n factoryId: string,\n choiceArgs: AllocationFactory_Allocate,\n choiceContext: OffLedger.AllocationInstructionV1.components['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n choiceArgs.extraArgs.context = {\n ...choiceContext.choiceContextData,\n values: choiceContext.choiceContextData?.values ?? {},\n }\n const exercise: ExerciseCommand = {\n templateId: ALLOCATION_FACTORY_INTERFACE_ID,\n contractId: factoryId,\n choice: 'AllocationFactory_Allocate',\n choiceArgument: choiceArgs,\n }\n return [exercise, choiceContext.disclosedContracts]\n }\n\n async createAllocationInstruction(\n allocationSpecification: AllocationSpecification,\n expectedAdmin: PartyId,\n registryUrl: string,\n inputUtxos?: string[],\n requestedAt?: string,\n prefetchedRegistryChoiceContext?: {\n factoryId: string\n choiceContext: OffLedger.AllocationInstructionV1.components['schemas']['ChoiceContext']\n }\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const choiceArgs = await this.buildAllocationFactoryChoiceArgs(\n allocationSpecification,\n expectedAdmin,\n inputUtxos,\n requestedAt\n )\n\n if (prefetchedRegistryChoiceContext) {\n return this.createAllocationInstructionFromContext(\n prefetchedRegistryChoiceContext.factoryId,\n choiceArgs,\n prefetchedRegistryChoiceContext.choiceContext\n )\n }\n\n const { factoryId, choiceContext } =\n await this.fetchAllocationFactoryChoiceContext(\n registryUrl,\n choiceArgs\n )\n return this.createAllocationInstructionFromContext(\n factoryId,\n choiceArgs,\n choiceContext\n )\n }\n\n private buildAllocationExerciseWithContext(\n templateId: string,\n contractId: string,\n choice:\n | 'Allocation_ExecuteTransfer'\n | 'Allocation_Withdraw'\n | 'Allocation_Cancel',\n choiceContext: OffLedger.AllocationInstructionV1.components['schemas']['ChoiceContext']\n ): [ExerciseCommand, DisclosedContract[]] {\n const exercise: ExerciseCommand = {\n templateId,\n contractId,\n choice,\n choiceArgument: {\n extraArgs: {\n context: choiceContext.choiceContextData,\n meta: EMPTY_META,\n },\n },\n }\n return [exercise, choiceContext.disclosedContracts ?? []]\n }\n\n async fetchExecuteTransferChoiceContext(\n allocationId: string,\n registryUrl: string\n ) {\n return this.core.getTokenStandardClient(registryUrl).post(\n '/registry/allocations/v1/{allocationId}/choice-contexts/execute-transfer',\n {\n excludeDebugFields: true,\n },\n {\n path: {\n allocationId,\n },\n }\n )\n }\n\n createExecuteTransferAllocationFromContext(\n allocationCid: string,\n choiceContext: OffLedger.AllocationInstructionV1.components['schemas']['ChoiceContext']\n ): [ExerciseCommand, DisclosedContract[]] {\n return this.buildAllocationExerciseWithContext(\n ALLOCATION_INTERFACE_ID,\n allocationCid,\n 'Allocation_ExecuteTransfer',\n choiceContext\n )\n }\n\n async createExecuteTransferAllocation(\n allocationCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: OffLedger.AllocationInstructionV1.components['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createExecuteTransferAllocationFromContext(\n allocationCid,\n prefetchedRegistryChoiceContext\n )\n }\n const choiceContext = await this.fetchExecuteTransferChoiceContext(\n allocationCid,\n registryUrl\n )\n return this.createExecuteTransferAllocationFromContext(\n allocationCid,\n choiceContext\n )\n }\n\n async fetchWithdrawAllocationChoiceContext(\n allocationCid: string,\n registryUrl: string\n ): Promise<\n OffLedger.AllocationInstructionV1.components['schemas']['ChoiceContext']\n > {\n return this.core.getTokenStandardClient(registryUrl).post(\n '/registry/allocations/v1/{allocationId}/choice-contexts/withdraw',\n {\n excludeDebugFields: true,\n },\n { path: { allocationId: allocationCid } }\n )\n }\n\n createWithdrawAllocationFromContext(\n allocationCid: string,\n choiceContext: OffLedger.AllocationInstructionV1.components['schemas']['ChoiceContext']\n ): [ExerciseCommand, DisclosedContract[]] {\n return this.buildAllocationExerciseWithContext(\n ALLOCATION_INTERFACE_ID,\n allocationCid,\n 'Allocation_Withdraw',\n choiceContext\n )\n }\n\n async createWithdrawAllocation(\n allocationCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: OffLedger.AllocationInstructionV1.components['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createWithdrawAllocationFromContext(\n allocationCid,\n prefetchedRegistryChoiceContext\n )\n }\n const choiceContext = await this.fetchWithdrawAllocationChoiceContext(\n allocationCid,\n registryUrl\n )\n return this.createWithdrawAllocationFromContext(\n allocationCid,\n choiceContext\n )\n }\n\n async fetchCancelAllocationChoiceContext(\n allocationCid: string,\n registryUrl: string\n ): Promise<\n OffLedger.AllocationInstructionV1.components['schemas']['ChoiceContext']\n > {\n return this.core.getTokenStandardClient(registryUrl).post(\n '/registry/allocations/v1/{allocationId}/choice-contexts/cancel',\n {\n excludeDebugFields: true,\n },\n { path: { allocationId: allocationCid } }\n )\n }\n\n createCancelAllocationFromContext(\n allocationCid: string,\n choiceContext: OffLedger.AllocationInstructionV1.components['schemas']['ChoiceContext']\n ): [ExerciseCommand, DisclosedContract[]] {\n return this.buildAllocationExerciseWithContext(\n ALLOCATION_INTERFACE_ID,\n allocationCid,\n 'Allocation_Cancel',\n choiceContext\n )\n }\n\n async createCancelAllocation(\n allocationCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: OffLedger.AllocationInstructionV1.components['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createCancelAllocationFromContext(\n allocationCid,\n prefetchedRegistryChoiceContext\n )\n }\n const choiceContext = await this.fetchCancelAllocationChoiceContext(\n allocationCid,\n registryUrl\n )\n return this.createCancelAllocationFromContext(\n allocationCid,\n choiceContext\n )\n }\n\n async createWithdrawAllocationInstruction(\n allocationInstructionCid: string\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const exercise: ExerciseCommand = {\n templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,\n contractId: allocationInstructionCid,\n choice: 'AllocationInstruction_Withdraw',\n choiceArgument: {\n extraArgs: {\n context: { values: {} },\n meta: { values: {} },\n },\n },\n }\n return [exercise, []]\n }\n\n async createUpdateAllocationInstruction(\n allocationInstructionCid: string,\n extraActors: PartyId[] = [],\n extraArgsContext: Record<string, unknown> = {},\n extraArgsMeta: Record<string, unknown> = {}\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const exercise: ExerciseCommand = {\n templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID,\n contractId: allocationInstructionCid,\n choice: 'AllocationInstruction_Update',\n choiceArgument: {\n extraActors,\n extraArgs: {\n context: { values: extraArgsContext },\n meta: { values: extraArgsMeta },\n },\n },\n }\n return [exercise, []]\n }\n\n async createRejectAllocationRequest(\n allocationRequestCid: string,\n actor: PartyId\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const exercise: ExerciseCommand = {\n templateId: ALLOCATION_REQUEST_INTERFACE_ID,\n contractId: allocationRequestCid,\n choice: 'AllocationRequest_Reject',\n choiceArgument: {\n actor,\n extraArgs: {\n context: { values: {} },\n meta: { values: {} },\n },\n },\n }\n return [exercise, []]\n }\n\n async createWithdrawAllocationRequest(\n allocationRequestCid: string\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const exercise: ExerciseCommand = {\n templateId: ALLOCATION_REQUEST_INTERFACE_ID,\n contractId: allocationRequestCid,\n choice: 'AllocationRequest_Withdraw',\n choiceArgument: {\n extraArgs: {\n context: { values: {} },\n meta: { values: {} },\n },\n },\n }\n return [exercise, []]\n }\n}\n\nclass TransferService {\n constructor(\n private core: CoreService,\n private readonly logger: Logger\n ) {}\n\n public async buildTransferChoiceArgs(\n sender: PartyId,\n receiver: PartyId,\n amount: string,\n instrumentAdmin: PartyId,\n instrumentId: string,\n inputUtxos?: string[],\n memo?: string,\n expiryDate?: Date,\n meta?: Metadata,\n continueUntilCompletion?: boolean\n ): Promise<CreateTransferChoiceArgs> {\n const inputHoldingCids: string[] = await this.core.getInputHoldingsCids(\n {\n sender,\n instrumentAdmin,\n instrumentId,\n inputUtxos: inputUtxos ?? [],\n amount: new Decimal(amount),\n continueUntilCompletion: continueUntilCompletion ?? false,\n }\n )\n\n return {\n expectedAdmin: instrumentAdmin,\n transfer: {\n sender,\n receiver,\n amount,\n instrumentId: { admin: instrumentAdmin, id: instrumentId },\n requestedAt: new Date(\n Date.now() - REQUESTED_AT_SKEW_MS\n ).toISOString(),\n executeBefore: (\n expiryDate ?? new Date(Date.now() + 24 * 60 * 60 * 1000)\n ).toISOString(),\n inputHoldingCids:\n inputHoldingCids as unknown as ContractId<Holding>[],\n meta: {\n values: {\n [TokenStandardService.MEMO_KEY]: memo || '',\n ...meta?.values,\n },\n },\n },\n extraArgs: {\n context: { values: {} },\n meta: { values: {} },\n },\n }\n }\n\n async fetchTransferFactoryChoiceContext(\n registryUrl: string,\n choiceArgs: CreateTransferChoiceArgs,\n excludeDebugFields: boolean = true\n ): Promise<\n OffLedger.TransferInstructionV1.components['schemas']['TransferFactoryWithChoiceContext']\n > {\n return await this.core\n .getTokenStandardClient(registryUrl)\n .post('/registry/transfer-instruction/v1/transfer-factory', {\n choiceArguments: choiceArgs as unknown as Record<string, never>,\n excludeDebugFields,\n })\n }\n\n async createTransferFromContext(\n factoryId: string,\n choiceArgs: CreateTransferChoiceArgs,\n choiceContext: OffLedger.TransferInstructionV1.components['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n this.logger.debug('Creating transfer from pre-fetched context...')\n choiceArgs.extraArgs.context = {\n ...choiceContext.choiceContextData,\n values: choiceContext.choiceContextData?.values ?? {},\n }\n const exercise: ExerciseCommand = {\n templateId: TRANSFER_FACTORY_INTERFACE_ID,\n contractId: factoryId,\n choice: 'TransferFactory_Transfer',\n choiceArgument: choiceArgs,\n }\n return [exercise, choiceContext.disclosedContracts]\n }\n\n // TODO: use named parameters\n async createTransfer(\n sender: PartyId,\n receiver: PartyId,\n amount: string,\n instrumentAdmin: PartyId, // TODO (#907): replace with registry call\n instrumentId: string,\n registryUrl: string,\n inputUtxos?: string[],\n memo?: string,\n expiryDate?: Date,\n meta?: Metadata,\n prefetchedRegistryChoiceContext?: {\n factoryId: string\n choiceContext: OffLedger.TransferInstructionV1.components['schemas']['ChoiceContext']\n },\n continueUntilCompletion?: boolean\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n try {\n const choiceArgs = await this.buildTransferChoiceArgs(\n sender,\n receiver,\n amount,\n instrumentAdmin,\n instrumentId,\n inputUtxos,\n memo,\n expiryDate,\n meta,\n continueUntilCompletion\n )\n\n if (prefetchedRegistryChoiceContext) {\n return this.createTransferFromContext(\n prefetchedRegistryChoiceContext.factoryId,\n choiceArgs,\n prefetchedRegistryChoiceContext.choiceContext\n )\n }\n\n const { factoryId, choiceContext } =\n await this.fetchTransferFactoryChoiceContext(\n registryUrl,\n choiceArgs\n )\n\n return this.createTransferFromContext(\n factoryId,\n choiceArgs,\n choiceContext\n )\n } catch (e) {\n this.logger.error('Failed to execute transfer:', e)\n throw e\n }\n }\n\n async fetchAcceptTransferInstructionChoiceContext(\n transferInstructionCid: string,\n registryUrl: string\n ): Promise<{\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }> {\n const client = this.core.getTokenStandardClient(registryUrl)\n const choiceContext = await client.post(\n '/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/accept',\n {\n excludeDebugFields: true,\n },\n {\n path: {\n transferInstructionId: transferInstructionCid,\n },\n }\n )\n return {\n choiceContextData: choiceContext.choiceContextData,\n disclosedContracts: choiceContext.disclosedContracts,\n }\n }\n\n async createAcceptTransferInstructionFromContext(\n transferInstructionCid: string,\n choiceContext: {\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n try {\n const exercise: ExerciseCommand = {\n templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,\n contractId: transferInstructionCid,\n choice: 'TransferInstruction_Accept',\n choiceArgument: {\n extraArgs: {\n context: choiceContext.choiceContextData,\n meta: { values: {} },\n },\n },\n }\n return [exercise, choiceContext.disclosedContracts]\n } catch (e) {\n this.logger.error(\n 'Failed to create accept transfer instruction:',\n e\n )\n throw e\n }\n }\n\n async exerciseDelegateProxyTransferInstructionAccept(\n proxyCid: string,\n transferInstructionCid: string,\n registryUrl: URL,\n featuredAppRightCid: string,\n beneficiaries: Beneficiaries[]\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const [acceptTransferInstructionContext, disclosedContracts] =\n await this.createAcceptTransferInstruction(\n transferInstructionCid,\n registryUrl.href\n )\n\n const choiceArgs = {\n cid: acceptTransferInstructionContext.contractId,\n proxyArg: {\n featuredAppRightCid: featuredAppRightCid,\n beneficiaries: beneficiaries,\n choiceArg: acceptTransferInstructionContext.choiceArgument,\n },\n }\n\n return [\n {\n templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,\n contractId: proxyCid,\n choice: 'DelegateProxy_TransferInstruction_Accept',\n choiceArgument: choiceArgs,\n },\n disclosedContracts,\n ]\n }\n\n async exerciseDelegateProxyTransferInstructionReject(\n proxyCid: string,\n transferInstructionCid: string,\n registryUrl: URL,\n featuredAppRightCid: string,\n beneficiaries: Beneficiaries[]\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const [rejectTransferInstructionContext, disclosedContracts] =\n await this.createRejectTransferInstruction(\n transferInstructionCid,\n registryUrl.href\n )\n\n const choiceArgs = {\n cid: rejectTransferInstructionContext.contractId,\n proxyArg: {\n featuredAppRightCid: featuredAppRightCid,\n beneficiaries,\n choiceArg: rejectTransferInstructionContext.choiceArgument,\n },\n }\n\n return [\n {\n templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,\n contractId: proxyCid,\n choice: 'DelegateProxy_TransferInstruction_Reject',\n choiceArgument: choiceArgs,\n },\n disclosedContracts,\n ]\n }\n\n async exerciseDelegateProxyTransferInstructioWithdraw(\n proxyCid: string,\n transferInstructionCid: string,\n registryUrl: URL,\n featuredAppRightCid: string,\n beneficiaries: Beneficiaries[]\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const [withdrawTransferInstructionContext, disclosedContracts] =\n await this.createWithdrawTransferInstruction(\n transferInstructionCid,\n registryUrl.href\n )\n\n const sumOfWeights: number = beneficiaries.reduce(\n (totalWeight, beneficiary) => totalWeight + beneficiary.weight,\n 0\n )\n\n if (sumOfWeights > 1.0) {\n throw new Error('Sum of beneficiary weights is larger than 1.')\n }\n\n const choiceArgs = {\n cid: withdrawTransferInstructionContext.contractId,\n proxyArg: {\n featuredAppRightCid: featuredAppRightCid,\n beneficiaries,\n choiceArg: withdrawTransferInstructionContext.choiceArgument,\n },\n }\n\n return [\n {\n templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,\n contractId: proxyCid,\n choice: 'DelegateProxy_TransferInstruction_Withdraw',\n choiceArgument: choiceArgs,\n },\n disclosedContracts,\n ]\n }\n\n async createAcceptTransferInstruction(\n transferInstructionCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: OffLedger.TransferInstructionV1.components['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createAcceptTransferInstructionFromContext(\n transferInstructionCid,\n {\n choiceContextData:\n prefetchedRegistryChoiceContext.choiceContextData,\n disclosedContracts:\n prefetchedRegistryChoiceContext.disclosedContracts,\n }\n )\n }\n const choiceContext =\n await this.fetchAcceptTransferInstructionChoiceContext(\n transferInstructionCid,\n registryUrl\n )\n return this.createAcceptTransferInstructionFromContext(\n transferInstructionCid,\n choiceContext\n )\n }\n\n async fetchRejectTransferInstructionChoiceContext(\n transferInstructionCid: string,\n registryUrl: string\n ): Promise<{\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }> {\n const client = this.core.getTokenStandardClient(registryUrl)\n const choiceContext = await client.post(\n '/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/reject',\n {\n excludeDebugFields: true,\n },\n {\n path: {\n transferInstructionId: transferInstructionCid,\n },\n }\n )\n return {\n choiceContextData: choiceContext.choiceContextData,\n disclosedContracts: choiceContext.disclosedContracts,\n }\n }\n\n async createRejectTransferInstructionFromContext(\n transferInstructionCid: string,\n choiceContext: {\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n try {\n const exercise: ExerciseCommand = {\n templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,\n contractId: transferInstructionCid,\n choice: 'TransferInstruction_Reject',\n choiceArgument: {\n extraArgs: {\n context: choiceContext.choiceContextData,\n meta: { values: {} },\n },\n },\n }\n return [exercise, choiceContext.disclosedContracts]\n } catch (e) {\n this.logger.error(\n 'Failed to create reject transfer instruction:',\n e\n )\n throw e\n }\n }\n\n async createRejectTransferInstruction(\n transferInstructionCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: OffLedger.TransferInstructionV1.components['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createRejectTransferInstructionFromContext(\n transferInstructionCid,\n {\n choiceContextData:\n prefetchedRegistryChoiceContext.choiceContextData,\n disclosedContracts:\n prefetchedRegistryChoiceContext.disclosedContracts,\n }\n )\n }\n const choiceContext =\n await this.fetchRejectTransferInstructionChoiceContext(\n transferInstructionCid,\n registryUrl\n )\n return this.createRejectTransferInstructionFromContext(\n transferInstructionCid,\n choiceContext\n )\n }\n\n async fetchWithdrawTransferInstructionChoiceContext(\n transferInstructionCid: string,\n registryUrl: string\n ): Promise<{\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }> {\n const client = this.core.getTokenStandardClient(registryUrl)\n\n const choiceContext = await client.post(\n '/registry/transfer-instruction/v1/{transferInstructionId}/choice-contexts/withdraw',\n {\n excludeDebugFields: true,\n },\n {\n path: {\n transferInstructionId: transferInstructionCid,\n },\n }\n )\n return {\n choiceContextData: choiceContext.choiceContextData,\n disclosedContracts: choiceContext.disclosedContracts,\n }\n }\n\n async createWithdrawTransferInstructionFromContext(\n transferInstructionCid: string,\n choiceContext: {\n choiceContextData: unknown\n disclosedContracts: DisclosedContract[]\n }\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n try {\n const exercise: ExerciseCommand = {\n templateId: TRANSFER_INSTRUCTION_INTERFACE_ID,\n contractId: transferInstructionCid,\n choice: 'TransferInstruction_Withdraw',\n choiceArgument: {\n extraArgs: {\n context: choiceContext.choiceContextData,\n meta: { values: {} },\n },\n },\n }\n return [exercise, choiceContext.disclosedContracts]\n } catch (e) {\n this.logger.error(\n 'Failed to create withdraw transfer instruction:',\n e\n )\n throw e\n }\n }\n\n async createWithdrawTransferInstruction(\n transferInstructionCid: string,\n registryUrl: string,\n prefetchedRegistryChoiceContext?: OffLedger.TransferInstructionV1.components['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n if (prefetchedRegistryChoiceContext) {\n return this.createWithdrawTransferInstructionFromContext(\n transferInstructionCid,\n {\n choiceContextData:\n prefetchedRegistryChoiceContext.choiceContextData,\n disclosedContracts:\n prefetchedRegistryChoiceContext.disclosedContracts,\n }\n )\n }\n const choiceContext =\n await this.fetchWithdrawTransferInstructionChoiceContext(\n transferInstructionCid,\n registryUrl\n )\n return this.createWithdrawTransferInstructionFromContext(\n transferInstructionCid,\n choiceContext\n )\n }\n\n async createTransferInstruction(\n transferInstructionCid: string,\n registryUrl: string,\n instructionChoice: 'Accept' | 'Reject' | 'Withdraw',\n prefetchedRegistryChoiceContext?: OffLedger.TransferInstructionV1.components['schemas']['ChoiceContext']\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n switch (instructionChoice) {\n case 'Accept':\n return this.createAcceptTransferInstruction(\n transferInstructionCid,\n registryUrl,\n prefetchedRegistryChoiceContext\n )\n case 'Reject':\n return this.createRejectTransferInstruction(\n transferInstructionCid,\n registryUrl,\n prefetchedRegistryChoiceContext\n )\n case 'Withdraw':\n return this.createWithdrawTransferInstruction(\n transferInstructionCid,\n registryUrl,\n prefetchedRegistryChoiceContext\n )\n }\n }\n}\n\nexport class TokenStandardService {\n static readonly MEMO_KEY = 'splice.lfdecentralizedtrust.org/reason'\n\n readonly core: CoreService\n readonly allocation: AllocationService\n readonly transfer: TransferService\n\n constructor(\n private ledgerProvider: AbstractLedgerProvider,\n private logger: Logger,\n private accessTokenProvider: AccessTokenProvider,\n private readonly isMasterUser: boolean\n ) {\n this.core = new CoreService(\n ledgerProvider,\n logger,\n accessTokenProvider,\n isMasterUser\n )\n this.allocation = new AllocationService(this.core, this.logger)\n this.transfer = new TransferService(this.core, this.logger)\n }\n\n async getInstrumentById(registryUrl: string, instrumentId: string) {\n try {\n const params: Record<string, unknown> = {\n path: {\n instrumentId,\n },\n }\n\n const client = this.core.getTokenStandardClient(registryUrl)\n\n return client.get(\n '/registry/metadata/v1/instruments/{instrumentId}',\n params\n )\n } catch (e) {\n this.logger.error(e)\n throw new Error(\n `Instrument id ${instrumentId} does not exist for this instrument admin.`,\n { cause: e }\n )\n }\n }\n\n async getInstrumentAdmin(registryUrl: string): Promise<string> {\n const client = this.core.getTokenStandardClient(registryUrl)\n\n const info = await client.get('/registry/metadata/v1/info')\n\n return info.adminId\n }\n\n async listInstruments(\n registryUrl: string,\n pageSize?: number,\n pageToken?: string\n ) {\n const client = this.core.getTokenStandardClient(registryUrl)\n return client.get('/registry/metadata/v1/instruments', {\n query: {\n ...(pageSize && { pageSize }),\n ...(pageToken && { pageToken }),\n },\n })\n }\n\n async instrumentsToAsset(registryUrl: string) {\n let instrumentsResponse = await this.listInstruments(registryUrl)\n const instruments = [...instrumentsResponse.instruments]\n\n while (instrumentsResponse.nextPageToken) {\n instrumentsResponse = await this.listInstruments(\n registryUrl,\n undefined,\n instrumentsResponse.nextPageToken\n )\n instruments.push(...instrumentsResponse.instruments)\n }\n const instrumentAdmin = await this.getInstrumentAdmin(registryUrl)\n return instruments.map((instrument) => ({\n id: instrument.id,\n displayName: instrument.name,\n symbol: instrument.symbol,\n registryUrl,\n admin: instrumentAdmin,\n }))\n }\n\n async registriesToAssets(registryUrls: string[]) {\n const allInstruments: {\n id: string\n displayName: string\n symbol: string\n registryUrl: string\n admin: PartyId\n }[] = []\n for (const registryUrl of registryUrls) {\n const instruments = await this.instrumentsToAsset(registryUrl)\n allInstruments.push(...instruments)\n }\n return allInstruments\n }\n\n // <T> is shape of viewValue related to queried interface.\n // i.e. when querying by TransferInstruction interfaceId, <T> would be TransferInstructionView from daml codegen\n async listContractsByInterface<T = ViewValue>(\n interfaceId: string,\n partyId?: PartyId,\n limit?: number,\n offset?: number,\n continueUntilCompletion?: boolean\n ): Promise<PrettyContract<T>[]> {\n return this.core.listContractsByInterface<T>(\n interfaceId,\n partyId,\n limit,\n offset,\n continueUntilCompletion\n )\n }\n\n async listHoldingTransactions(\n partyId: PartyId,\n afterOffset?: number,\n beforeOffset?: number\n ): Promise<PrettyTransactions> {\n try {\n this.logger.debug('Set or query offset')\n const afterOffsetOrLatest =\n afterOffset ??\n (\n await this.ledgerProvider.request<Ops.GetV2StateLatestPrunedOffsets>(\n {\n method: 'ledgerApi',\n params: {\n resource: '/v2/state/latest-pruned-offsets',\n requestMethod: 'get',\n },\n }\n )\n ).participantPrunedUpToInclusive!\n const beforeOffsetOrLatest =\n beforeOffset ??\n (\n await this.ledgerProvider.request<Ops.GetV2StateLedgerEnd>({\n method: 'ledgerApi',\n params: {\n resource: '/v2/state/ledger-end',\n requestMethod: 'get',\n query: {},\n },\n })\n ).offset!\n\n this.logger.debug(afterOffsetOrLatest, 'Using offset')\n const updatesResponse: JsGetUpdatesResponse[] =\n await this.ledgerProvider.request<Ops.PostV2Updates>({\n method: 'ledgerApi',\n params: {\n resource: '/v2/updates',\n requestMethod: 'post',\n query: {},\n body: {\n updateFormat: {\n includeTransactions: {\n eventFormat: EventFilterBySetup({\n interfaceIds:\n TokenStandardTransactionInterfaces,\n isMasterUser: this.isMasterUser,\n partyId: partyId,\n includeWildcard: true,\n }),\n transactionShape:\n 'TRANSACTION_SHAPE_LEDGER_EFFECTS',\n },\n },\n beginExclusive: afterOffsetOrLatest,\n endInclusive: beforeOffsetOrLatest,\n },\n },\n })\n\n return this.core.toPrettyTransactions(\n updatesResponse,\n partyId\n // this.ledgerProvider\n )\n } catch (err) {\n this.logger.error('Failed to list holding transactions.', err)\n throw err\n }\n }\n\n async getTransactionById(\n updateId: string,\n partyId: PartyId\n ): Promise<Transaction> {\n const updateFormat: UpdateFormat = {\n includeTransactions: {\n eventFormat: EventFilterBySetup({\n interfaceIds: TokenStandardTransactionInterfaces,\n isMasterUser: this.isMasterUser,\n partyId: partyId,\n includeWildcard: true,\n }),\n transactionShape: 'TRANSACTION_SHAPE_LEDGER_EFFECTS',\n },\n }\n\n const getUpdateResponse =\n await this.ledgerProvider.request<Ops.PostV2UpdatesUpdateById>({\n method: 'ledgerApi',\n params: {\n resource: '/v2/updates/update-by-id',\n requestMethod: 'post',\n body: {\n updateId,\n updateFormat,\n },\n },\n })\n\n return this.core.toPrettyTransaction(getUpdateResponse, partyId)\n }\n\n async getTransferObjectsById(\n updateId: string,\n partyId: PartyId\n ): Promise<TransferObject[]> {\n const updateFormat: UpdateFormat = {\n includeTransactions: {\n eventFormat: EventFilterBySetup({\n interfaceIds: TokenStandardTransactionInterfaces,\n isMasterUser: this.isMasterUser,\n partyId: partyId,\n includeWildcard: true,\n }),\n transactionShape: 'TRANSACTION_SHAPE_LEDGER_EFFECTS',\n },\n }\n\n const getUpdateResponse =\n await this.ledgerProvider.request<Ops.PostV2UpdatesUpdateById>({\n method: 'ledgerApi',\n params: {\n resource: '/v2/updates/update-by-id',\n requestMethod: 'post',\n body: {\n updateId,\n updateFormat,\n },\n },\n })\n\n return this.core.toPrettyTransferObjects(getUpdateResponse, partyId)\n }\n\n async getInputHoldingsCids(\n sender: PartyId,\n inputUtxos?: string[],\n amount?: Decimal\n ) {\n if (amount) {\n return this.core.getInputHoldingsCids({\n sender,\n inputUtxos: inputUtxos ?? [],\n amount,\n })\n } else {\n return this.core.getInputHoldingsCids({\n sender,\n inputUtxos: inputUtxos ?? [],\n })\n }\n }\n\n async createDelegateProxyTransfer(\n sender: PartyId,\n receiver: PartyId,\n amount: string,\n instrumentAdmin: PartyId, // TODO (#907): replace with registry call\n instrumentId: string,\n registryUrl: string,\n featuredAppRightCid: string,\n proxyCid: string,\n beneficiaries: Beneficiaries[],\n inputUtxos?: string[],\n memo?: string,\n expiryDate?: Date,\n meta?: Metadata\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const [transferCommand, disclosedContracts] =\n await this.transfer.createTransfer(\n sender,\n receiver,\n amount,\n instrumentAdmin,\n instrumentId,\n registryUrl,\n inputUtxos,\n memo,\n expiryDate,\n meta\n )\n\n const sumOfWeights: number = beneficiaries.reduce(\n (totalWeight, beneficiary) => totalWeight + beneficiary.weight,\n 0\n )\n\n if (sumOfWeights > 1.0) {\n throw new Error('Sum of beneficiary weights is larger than 1.')\n }\n\n const choiceArgs = {\n cid: transferCommand.contractId,\n proxyArg: {\n featuredAppRightCid: featuredAppRightCid,\n beneficiaries,\n choiceArg: transferCommand.choiceArgument,\n },\n }\n\n const exercise: ExerciseCommand = {\n templateId: FEATURED_APP_DELEGATE_PROXY_INTERFACE_ID,\n contractId: proxyCid,\n choice: 'DelegateProxy_TransferFactory_Transfer',\n choiceArgument: choiceArgs,\n }\n\n return [exercise, disclosedContracts]\n }\n\n async exerciseDelegateProxyTransferInstructionAccept(\n exchangeParty: PartyId,\n proxyCid: string,\n transferInstructionCid: string,\n registryUrl: string,\n featuredAppRightCid: string\n ): Promise<[ExerciseCommand, DisclosedContract[]]> {\n const [acceptTransferInstructionContext, disclosedContracts] =\n await this.transfer.createAcceptTransferInstruction(\n transferInstructionCid,\n registryUrl\n )\n\n const choiceArgs = {\n cid: acceptTransferInstructionContext.contractId,\n proxyArg: {\n featuredAppRightCid: featuredAppRightCid,\n beneficiaries: [\n {\n beneficiary: exchangeParty,\n weight: 1.0,\n },\n ],\n choiceArg: acceptTransferInstructionContext.choiceArgument,\n },\n }\n\n return [\n {\n templateId:\n '#splice-util-featured-app-proxies:Splice.Util.FeaturedApp.DelegateProxy:DelegateProxy',\n contractId: proxyCid,\n choice: 'DelegateProxy_TransferInstruction_Accept',\n choiceArgument: choiceArgs,\n },\n disclosedContracts,\n ]\n }\n\n static isHoldingLocked(\n holding: PrettyContract<HoldingView>,\n currentTime: Date = new Date()\n ): boolean {\n const lock = holding.interfaceViewValue.lock\n if (!lock) return false\n\n let expiresAtAbsolute: Date | null = null\n let expiresAtRelative: Date | null = null\n\n if (lock.expiresAfter) {\n const createdAt = new Date(\n holding.activeContract.createdEvent.createdAt\n )\n\n // 1 microsecond = 0.001 milliseconds\n const msToAdd = parseInt(lock.expiresAfter.microseconds) / 1000\n\n expiresAtRelative = new Date(createdAt.getTime() + msToAdd)\n }\n if (lock.expiresAt) {\n expiresAtAbsolute = new Date(lock.expiresAt)\n }\n\n let expiresAt: Date\n\n // If both `expiresAt` and `expiresAfter` are set, the lock expires at the earlier of the two times.\n if (expiresAtRelative && expiresAtAbsolute) {\n expiresAt =\n expiresAtRelative < expiresAtAbsolute\n ? expiresAtRelative\n : expiresAtAbsolute\n } else if (expiresAtRelative) {\n expiresAt = expiresAtRelative\n } else if (expiresAtAbsolute) {\n expiresAt = expiresAtAbsolute\n } else {\n // No expiration => locked\n return true\n }\n\n return currentTime < expiresAt\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CA,MAAM,uBAAuB;AAI7B,MAAM,aAAuB,EAAE,QAAQ,CAAC,EAAE;AAiC1C,IAAa,cAAb,MAAa,YAAY;CACrB,YACI,gBACA,QACA,qBACA,cACF;EAJU,KAAA,iBAAA;EACS,KAAA,SAAA;EACT,KAAA,sBAAA;EACS,KAAA,eAAA;CAClB;CAEH,uBAAuB,aAA0C;EAC7D,OAAO,IAAI,oBACP,aACA,KAAK,QACL,KAAK,mBACT;CACJ;CAEA,MAAM,qBAAqB,SAOxB;EACC,MAAM,EAAE,QAAQ,iBAAiB,iBAAiB;EAClD,MAAM,sBAAM,IAAI,KAAK;EACrB,IAAI,QAAQ,cAAc,QAAQ,WAAW,SAAS,GAClD,OAAO,QAAQ;EAEnB,MAAM,iBAAiB,MAAM,KAAK,yBAC9B,sBACA,QACA,KAAA,GACA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