@canton-network/core-token-standard-service 2.2.0 → 2.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import { ALLOCATION_FACTORY_INTERFACE_ID, ALLOCATION_INSTRUCTION_INTERFACE_ID, A
2
2
  import { EventFilterBySetup } from "@canton-network/core-ledger-client-types";
3
3
  import { TokenStandardTransactionInterfaces, TransactionParser, ensureInterfaceViewIsPresent, renderTransaction } from "@canton-network/core-tx-parser";
4
4
  import Decimal$1, { Decimal } from "decimal.js";
5
- import { ALLOCATION_FACTORY_INTERFACE_ID_V2, ALLOCATION_INSTRUCTION_INTERFACE_ID_V2, ALLOCATION_INTERFACE_ID_V2, ALLOCATION_REQUEST_INTERFACE_ID_V2, TRANSFER_FACTORY_INTERFACE_ID_V2, TRANSFER_INSTRUCTION_INTERFACE_ID_V2, TokenStandardClient as TokenStandardClient$1, TransferInstruction as TransferInstruction$1 } from "@canton-network/core-token-standard-v2";
5
+ import { ALLOCATION_FACTORY_INTERFACE_ID_V2, ALLOCATION_INSTRUCTION_INTERFACE_ID_V2, ALLOCATION_INTERFACE_ID_V2, ALLOCATION_REQUEST_INTERFACE_ID_V2, AllocationInstruction, HOLDING_INTERFACE_ID_V2, TRANSFER_FACTORY_INTERFACE_ID_V2, TRANSFER_INSTRUCTION_INTERFACE_ID_V2, TokenStandardClient as TokenStandardClient$1, TransferInstruction as TransferInstruction$1, isSameAccount } from "@canton-network/core-token-standard-v2";
6
6
  import { getLogger } from "@logtape/logtape";
7
7
  import { ACSReader } from "@canton-network/core-acs-reader";
8
8
  // src/types.ts
@@ -16,7 +16,7 @@ const KEY_MAPPING = {
16
16
  "allocation-instruction": "allocationInstruction",
17
17
  "allocation-request": "allocationRequest"
18
18
  };
19
- // \0@oxc-project+runtime@0.155.0/helpers/esm/typeof.js
19
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/typeof.js
20
20
  function _typeof(o) {
21
21
  "@babel/helpers - typeof";
22
22
  return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
@@ -25,23 +25,23 @@ function _typeof(o) {
25
25
  return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
26
26
  }, _typeof(o);
27
27
  }
28
- // \0@oxc-project+runtime@0.155.0/helpers/esm/toPrimitive.js
29
- function toPrimitive(t, r) {
28
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/toPrimitive.js
29
+ function toPrimitive(t, e) {
30
30
  if ("object" != _typeof(t) || !t) return t;
31
- var e = t[Symbol.toPrimitive];
32
- if (void 0 !== e) {
33
- var i = e.call(t, r || "default");
31
+ var r;
32
+ if ("undefined" != typeof Symbol && void 0 !== (r = t[Symbol.toPrimitive])) {
33
+ var i = r.call(t, e || "default");
34
34
  if ("object" != _typeof(i)) return i;
35
35
  throw new TypeError("@@toPrimitive must return a primitive value.");
36
36
  }
37
- return ("string" === r ? String : Number)(t);
37
+ return ("string" === e ? String : Number)(t);
38
38
  }
39
- // \0@oxc-project+runtime@0.155.0/helpers/esm/toPropertyKey.js
39
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/toPropertyKey.js
40
40
  function toPropertyKey(t) {
41
41
  var i = toPrimitive(t, "string");
42
42
  return "symbol" == _typeof(i) ? i : i + "";
43
43
  }
44
- // \0@oxc-project+runtime@0.155.0/helpers/esm/defineProperty.js
44
+ // \0@oxc-project+runtime@0.157.0/helpers/esm/defineProperty.js
45
45
  function _defineProperty(e, r, t) {
46
46
  return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
47
47
  value: t,
@@ -568,15 +568,12 @@ var CoreService = class CoreService {
568
568
  id: ""
569
569
  };
570
570
  }
571
- isSameAccount(a, b) {
572
- return a.id === b.id && a.owner === b.owner && a.provider === b.provider;
573
- }
574
571
  async getInputHoldingCidsForAccount(opts) {
575
572
  if (opts.inputUtxos?.length) return opts.inputUtxos;
576
573
  const party = opts.partyId ?? opts.account.owner;
577
574
  if (!party) throw new Error("No party to query as");
578
575
  const now = /* @__PURE__ */ new Date();
579
- const holdings = (await this.listContractsByInterface("#splice-api-token-holding-v2:Splice.Api.Token.HoldingV2:Holding", party, opts.limit, opts.offset, opts.continueUntilCompletion ?? false)).filter((h) => h.interfaceViewValue.instrumentId.admin === opts.instrumentAdmin && h.interfaceViewValue.instrumentId.id == opts.instrumentId && this.isSameAccount(opts.account, h.interfaceViewValue.account) && !TokenStandardService.isHoldingLocked(h, now));
576
+ const holdings = (await this.listContractsByInterface(HOLDING_INTERFACE_ID_V2, party, opts.limit, opts.offset, opts.continueUntilCompletion ?? false)).filter((h) => h.interfaceViewValue.instrumentId.admin === opts.instrumentAdmin && h.interfaceViewValue.instrumentId.id === opts.instrumentId && isSameAccount(opts.account, h.interfaceViewValue.account) && !TokenStandardService.isHoldingLocked(h, now) && !opts.excludeCids?.has(h.contractId));
580
577
  return opts.amount ? CoreService.getInputHoldingsCidsForAmount(opts.amount, holdings) : holdings.map((h) => h.contractId);
581
578
  }
582
579
  async getInputHoldingsCids(options) {
@@ -734,7 +731,8 @@ var AllocationService = class AllocationService {
734
731
  account: spec.authorizer,
735
732
  instrumentAdmin: admin,
736
733
  instrumentId,
737
- amount
734
+ amount,
735
+ excludeCids: used
738
736
  });
739
737
  cids.forEach((c) => used.add(c));
740
738
  inputHoldingCids.push(...cids);
@@ -780,10 +778,15 @@ var AllocationService = class AllocationService {
780
778
  return this.createAllocationChoiceFromContext(action, allocationCid, actors, ctx);
781
779
  }
782
780
  createAllocationRequestChoice(action, allocationRequestCid, actors) {
781
+ const choice = {
782
+ accept: "AllocationRequest_Accept",
783
+ reject: "AllocationRequest_Reject",
784
+ withdraw: "AllocationRequest_Withdraw"
785
+ }[action];
783
786
  return [{
784
787
  templateId: ALLOCATION_REQUEST_INTERFACE_ID_V2,
785
788
  contractId: allocationRequestCid,
786
- choice: action === "reject" ? "AllocationRequest_Reject" : "AllocationRequest_Withdraw",
789
+ choice,
787
790
  choiceArgument: {
788
791
  actors,
789
792
  extraArgs: EMPTY_EXTRA_ARGS()
@@ -825,12 +828,36 @@ var AllocationService = class AllocationService {
825
828
  choiceArgument: choiceArgs
826
829
  }, choiceContext.disclosedContracts];
827
830
  }
831
+ async fetchAllocationInstructionChoiceContext(action, allocationInstructionCid, registryUrl, excludeDebugFields = true) {
832
+ return this.core.getTokenStandardClientV2(registryUrl).post(`/registry/allocation-instruction/v2/{allocationInstructionId}/choice-contexts/${action}`, { excludeDebugFields }, { path: { allocationInstructionId: allocationInstructionCid } });
833
+ }
834
+ async createAllocationInstructionChoice(action, allocationInstructionCid, actors, registryUrl, excludeDebugFields = true, prefetched) {
835
+ const ctx = prefetched ?? await this.fetchAllocationInstructionChoiceContext(action, allocationInstructionCid, registryUrl, excludeDebugFields);
836
+ return [{
837
+ templateId: ALLOCATION_INSTRUCTION_INTERFACE_ID_V2,
838
+ contractId: allocationInstructionCid,
839
+ choice: action === "accept" ? AllocationInstruction.AllocationInstruction_Accept.choiceName : AllocationInstruction.AllocationInstruction_Withdraw.choiceName,
840
+ choiceArgument: {
841
+ actors,
842
+ extraArgs: {
843
+ context: ctx.choiceContextData,
844
+ meta: { values: {} }
845
+ }
846
+ }
847
+ }, ctx.disclosedContracts ?? []];
848
+ }
828
849
  async fetchSettlementFactory(args, registryUrl) {
829
850
  return this.core.getTokenStandardClientV2(registryUrl).post("/registry/allocation/v2/settlement-factory", {
830
851
  choiceArguments: args,
831
852
  excludeDebugFields: true
832
853
  });
833
854
  }
855
+ /**
856
+ *
857
+ * @deprecated Use {@link createAllocationsForRequestForLoggedInParty}
858
+ * instead, which creates only the allocations owned by a given party and
859
+ * reports allocations whose registry could not be resolved
860
+ */
834
861
  async createAllocationsForRequest(opts) {
835
862
  const used = /* @__PURE__ */ new Set();
836
863
  const results = [];
@@ -859,6 +886,60 @@ var AllocationService = class AllocationService {
859
886
  const dcs = new Map(results.flatMap(([, d]) => d).filter((d) => d.contractId !== void 0).map((d) => [d.contractId, d]));
860
887
  return [results.map(([c]) => c), [...dcs.values()]];
861
888
  }
889
+ /**
890
+ * Prepares the commands for a party to accept an allocation request.
891
+ *
892
+ * Creates one `AllocationFactory_Allocate` command for each allocation in the
893
+ * request that the party owns, followed by an `AllocationRequest_Accept`
894
+ * command. Holdings used as inputs by one allocation are excluded from later
895
+ * allocations, so no holding is spent twice within the same request.
896
+ *
897
+ * If no registry serves an allocation's instrument admin, that allocation is
898
+ * skipped and its admin is added to `skipped`. In that case `accept` is
899
+ * `null`, because the request cannot be accepted until every allocation
900
+ * exists.
901
+ *
902
+ * @param opts.requestCid - Contract ID of the allocation request.
903
+ * @param opts.request - The allocation request's interface view.
904
+ * @param opts.registry - Resolves an instrument admin to its registry URL,
905
+ * or `null` if no registry serves that admin.
906
+ * @param opts.partyId - The party accepting the request. Only allocations
907
+ * this party owns are created, and it acts on every command.
908
+ * @params opts.skipSpec Specs to leave out (e.g. already allocated by an earlier attempt).
909
+ * @returns The allocate commands with their disclosed contracts, the accept
910
+ * command with its disclosed contracts (or `null` if any allocation was
911
+ * skipped), and the admins whose allocations were skipped.
912
+ * @throws If the request contains no allocations owned by `partyId`.
913
+ */
914
+ async createAllocationsForRequestForLoggedInParty(opts) {
915
+ const ownSpecs = opts.request.allocations.filter((p) => p.authorizer.owner === opts.partyId);
916
+ if (ownSpecs.length === 0) throw new Error(`Request ${opts.requestCid} has no allocation for account ${opts.partyId}`);
917
+ const specs = opts.skipSpec ? ownSpecs.filter((spec) => !opts.skipSpec(spec)) : ownSpecs;
918
+ const used = /* @__PURE__ */ new Set();
919
+ const allocate = [];
920
+ const skipped = [];
921
+ for (const spec of specs) {
922
+ const registryUrl = await opts.registry(spec.admin);
923
+ if (!registryUrl) {
924
+ if (!skipped.includes(spec.admin)) skipped.push(spec.admin);
925
+ continue;
926
+ }
927
+ const [cmd, dcs] = await this.createAllocation({
928
+ settlement: opts.request.settlement,
929
+ spec,
930
+ admin: spec.admin,
931
+ actors: [opts.partyId],
932
+ excludeCids: used
933
+ }, registryUrl);
934
+ for (const cid of cmd.choiceArgument.inputHoldingCids) used.add(cid);
935
+ allocate.push([cmd, dcs]);
936
+ }
937
+ return {
938
+ allocate,
939
+ accept: skipped.length === 0 ? this.createAllocationRequestChoice("accept", opts.requestCid, [opts.partyId]) : null,
940
+ skipped
941
+ };
942
+ }
862
943
  };
863
944
  // src/token-standard-service.ts
864
945
  function isApiVersion(v) {
@@ -884,7 +965,7 @@ function resolveCapabilities(opts) {
884
965
  for (const key in resolvedCapabilities) resolvedCapabilities[key].sort();
885
966
  return resolvedCapabilities;
886
967
  }
887
- var TokenStandardService = class {
968
+ var TokenStandardService = class TokenStandardService {
888
969
  constructor(ledgerProvider, accessTokenProvider, isMasterUser) {
889
970
  this.ledgerProvider = ledgerProvider;
890
971
  this.accessTokenProvider = accessTokenProvider;
@@ -1095,13 +1176,12 @@ var TokenStandardService = class {
1095
1176
  }
1096
1177
  }, disclosedContracts];
1097
1178
  }
1098
- static isHoldingLocked(holding, currentTime = /* @__PURE__ */ new Date()) {
1099
- const lock = holding.interfaceViewValue.lock;
1179
+ static checkLock(lock, createdAtTime, currentTime = /* @__PURE__ */ new Date()) {
1100
1180
  if (!lock) return false;
1101
1181
  let expiresAtAbsolute = null;
1102
1182
  let expiresAtRelative = null;
1103
1183
  if (lock.expiresAfter) {
1104
- const createdAt = new Date(holding.activeContract.createdEvent.createdAt);
1184
+ const createdAt = new Date(createdAtTime);
1105
1185
  const msToAdd = parseInt(lock.expiresAfter.microseconds) / 1e3;
1106
1186
  expiresAtRelative = new Date(createdAt.getTime() + msToAdd);
1107
1187
  }
@@ -1113,6 +1193,10 @@ var TokenStandardService = class {
1113
1193
  else return true;
1114
1194
  return currentTime < expiresAt;
1115
1195
  }
1196
+ static isHoldingLocked(holding, currentTime = /* @__PURE__ */ new Date()) {
1197
+ const lock = holding.interfaceViewValue.lock;
1198
+ return TokenStandardService.checkLock(lock, holding.activeContract.createdEvent.createdAt, currentTime);
1199
+ }
1116
1200
  };
1117
1201
  _defineProperty(TokenStandardService, "MEMO_KEY", "splice.lfdecentralizedtrust.org/reason");
1118
1202
  export { EMPTY_META, KEY_MAPPING, REQUESTED_AT_SKEW_MS, SUPPORTED_VERSIONS, TokenStandardService, isApiVersion, resolveCapabilities };