@fairmint/canton-node-sdk 0.0.288 → 0.0.290

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.
Files changed (113) hide show
  1. package/README.md +178 -8
  2. package/build/src/clients/ledger-json-api/operations/v2/parties/external/allocate-external-party.d.ts +10 -2
  3. package/build/src/clients/ledger-json-api/operations/v2/parties/external/allocate-external-party.d.ts.map +1 -1
  4. package/build/src/clients/ledger-json-api/operations/v2/parties/external/allocate-external-party.js +27 -3
  5. package/build/src/clients/ledger-json-api/operations/v2/parties/external/allocate-external-party.js.map +1 -1
  6. package/build/src/clients/ledger-json-api/operations/v2/users/delete-user.js +1 -1
  7. package/build/src/clients/ledger-json-api/operations/v2/users/delete-user.js.map +1 -1
  8. package/build/src/clients/ledger-json-api/operations/v2/users/get-user.js +1 -1
  9. package/build/src/clients/ledger-json-api/operations/v2/users/get-user.js.map +1 -1
  10. package/build/src/clients/ledger-json-api/operations/v2/users/grant-user-rights.d.ts +2 -0
  11. package/build/src/clients/ledger-json-api/operations/v2/users/grant-user-rights.d.ts.map +1 -1
  12. package/build/src/clients/ledger-json-api/operations/v2/users/grant-user-rights.js +5 -6
  13. package/build/src/clients/ledger-json-api/operations/v2/users/grant-user-rights.js.map +1 -1
  14. package/build/src/clients/ledger-json-api/operations/v2/users/list-user-rights.d.ts +3 -0
  15. package/build/src/clients/ledger-json-api/operations/v2/users/list-user-rights.d.ts.map +1 -1
  16. package/build/src/clients/ledger-json-api/operations/v2/users/list-user-rights.js +5 -3
  17. package/build/src/clients/ledger-json-api/operations/v2/users/list-user-rights.js.map +1 -1
  18. package/build/src/clients/ledger-json-api/operations/v2/users/revoke-user-rights.js +1 -1
  19. package/build/src/clients/ledger-json-api/operations/v2/users/revoke-user-rights.js.map +1 -1
  20. package/build/src/clients/ledger-json-api/operations/v2/users/update-user-identity-provider.js +1 -1
  21. package/build/src/clients/ledger-json-api/operations/v2/users/update-user-identity-provider.js.map +1 -1
  22. package/build/src/clients/ledger-json-api/operations/v2/users/update-user.js +1 -1
  23. package/build/src/clients/ledger-json-api/operations/v2/users/update-user.js.map +1 -1
  24. package/build/src/clients/ledger-json-api/schemas/operations/users.d.ts +2 -0
  25. package/build/src/clients/ledger-json-api/schemas/operations/users.d.ts.map +1 -1
  26. package/build/src/clients/ledger-json-api/schemas/operations/users.js +4 -0
  27. package/build/src/clients/ledger-json-api/schemas/operations/users.js.map +1 -1
  28. package/build/src/utils/external-signing/allocate-external-party.d.ts +2 -0
  29. package/build/src/utils/external-signing/allocate-external-party.d.ts.map +1 -1
  30. package/build/src/utils/external-signing/allocate-external-party.js +1 -0
  31. package/build/src/utils/external-signing/allocate-external-party.js.map +1 -1
  32. package/build/src/utils/external-signing/allocation-user-id.d.ts +6 -0
  33. package/build/src/utils/external-signing/allocation-user-id.d.ts.map +1 -0
  34. package/build/src/utils/external-signing/allocation-user-id.js +18 -0
  35. package/build/src/utils/external-signing/allocation-user-id.js.map +1 -0
  36. package/build/src/utils/external-signing/create-external-party.d.ts +6 -0
  37. package/build/src/utils/external-signing/create-external-party.d.ts.map +1 -1
  38. package/build/src/utils/external-signing/create-external-party.js +4 -1
  39. package/build/src/utils/external-signing/create-external-party.js.map +1 -1
  40. package/build/src/utils/external-signing/external-party-onboarding.d.ts +24 -0
  41. package/build/src/utils/external-signing/external-party-onboarding.d.ts.map +1 -1
  42. package/build/src/utils/external-signing/external-party-onboarding.js +71 -0
  43. package/build/src/utils/external-signing/external-party-onboarding.js.map +1 -1
  44. package/build/src/utils/external-signing/external-party-wallet.d.ts +110 -0
  45. package/build/src/utils/external-signing/external-party-wallet.d.ts.map +1 -1
  46. package/build/src/utils/external-signing/external-party-wallet.js +173 -1
  47. package/build/src/utils/external-signing/external-party-wallet.js.map +1 -1
  48. package/build/src/utils/external-signing/external-signing-client.d.ts +6 -0
  49. package/build/src/utils/external-signing/external-signing-client.d.ts.map +1 -1
  50. package/build/src/utils/external-signing/external-signing-client.js +4 -0
  51. package/build/src/utils/external-signing/external-signing-client.js.map +1 -1
  52. package/build/src/utils/token-standard/v1/holdings.d.ts +3 -9
  53. package/build/src/utils/token-standard/v1/holdings.d.ts.map +1 -1
  54. package/build/src/utils/token-standard/v1/holdings.js +6 -74
  55. package/build/src/utils/token-standard/v1/holdings.js.map +1 -1
  56. package/build/src/wallets/acs.d.ts.map +1 -1
  57. package/build/src/wallets/acs.js +21 -0
  58. package/build/src/wallets/acs.js.map +1 -1
  59. package/build/src/wallets/amulet/constants.d.ts +33 -0
  60. package/build/src/wallets/amulet/constants.d.ts.map +1 -0
  61. package/build/src/wallets/amulet/constants.js +34 -0
  62. package/build/src/wallets/amulet/constants.js.map +1 -0
  63. package/build/src/wallets/amulet/registry.d.ts +65 -0
  64. package/build/src/wallets/amulet/registry.d.ts.map +1 -0
  65. package/build/src/wallets/amulet/registry.js +187 -0
  66. package/build/src/wallets/amulet/registry.js.map +1 -0
  67. package/build/src/wallets/cip103.d.ts +17 -3
  68. package/build/src/wallets/cip103.d.ts.map +1 -1
  69. package/build/src/wallets/cip103.js +19 -6
  70. package/build/src/wallets/cip103.js.map +1 -1
  71. package/build/src/wallets/commands.d.ts +5 -0
  72. package/build/src/wallets/commands.d.ts.map +1 -1
  73. package/build/src/wallets/commands.js +23 -7
  74. package/build/src/wallets/commands.js.map +1 -1
  75. package/build/src/wallets/contracts.d.ts +56 -3
  76. package/build/src/wallets/contracts.d.ts.map +1 -1
  77. package/build/src/wallets/contracts.js +63 -11
  78. package/build/src/wallets/contracts.js.map +1 -1
  79. package/build/src/wallets/da-utilities/client.d.ts +4 -0
  80. package/build/src/wallets/da-utilities/client.d.ts.map +1 -1
  81. package/build/src/wallets/da-utilities/client.js +2 -0
  82. package/build/src/wallets/da-utilities/client.js.map +1 -1
  83. package/build/src/wallets/errors.d.ts +3 -1
  84. package/build/src/wallets/errors.d.ts.map +1 -1
  85. package/build/src/wallets/errors.js +3 -2
  86. package/build/src/wallets/errors.js.map +1 -1
  87. package/build/src/wallets/holding-view.d.ts +47 -0
  88. package/build/src/wallets/holding-view.d.ts.map +1 -0
  89. package/build/src/wallets/holding-view.js +121 -0
  90. package/build/src/wallets/holding-view.js.map +1 -0
  91. package/build/src/wallets/holdings.d.ts +59 -5
  92. package/build/src/wallets/holdings.d.ts.map +1 -1
  93. package/build/src/wallets/holdings.js +85 -15
  94. package/build/src/wallets/holdings.js.map +1 -1
  95. package/build/src/wallets/index.d.ts +20 -3
  96. package/build/src/wallets/index.d.ts.map +1 -1
  97. package/build/src/wallets/index.js +30 -1
  98. package/build/src/wallets/index.js.map +1 -1
  99. package/build/src/wallets/store.d.ts +19 -1
  100. package/build/src/wallets/store.d.ts.map +1 -1
  101. package/build/src/wallets/store.js +78 -3
  102. package/build/src/wallets/store.js.map +1 -1
  103. package/build/src/wallets/tokens.d.ts +120 -0
  104. package/build/src/wallets/tokens.d.ts.map +1 -0
  105. package/build/src/wallets/tokens.js +166 -0
  106. package/build/src/wallets/tokens.js.map +1 -0
  107. package/build/src/wallets/types.d.ts +14 -0
  108. package/build/src/wallets/types.d.ts.map +1 -1
  109. package/build/src/wallets/wallet.d.ts +81 -5
  110. package/build/src/wallets/wallet.d.ts.map +1 -1
  111. package/build/src/wallets/wallet.js +331 -49
  112. package/build/src/wallets/wallet.js.map +1 -1
  113. package/package.json +1 -1
@@ -9,19 +9,35 @@ exports.createWallet = createWallet;
9
9
  * its choice context from DA's Utilities API, refuses anything that does not check out, and submits as the wallet party
10
10
  * only.
11
11
  *
12
- * Trust: a holding counts when its registrar and owner signed it; an offer, a request or a preapproval when it names
13
- * DA's operator and (offers and requests) a provider trusted for its instrument admin signed it. By default a registrar
14
- * must be its own provider; `registry.trustedProviders` trusts others (see `isFromRegistry`).
12
+ * Canton Coin (on by default, `WalletOptions.cantonCoin`): the party's Canton Coin holdings (Splice `Amulet` and
13
+ * `LockedAmulet`, read through their `HoldingV1` interface view) are listed with its other tokens, and Canton Coin
14
+ * transfer offers (`AmuletTransferInstruction`s, for example a faucet's) beside DA's, to accept, reject or withdraw the
15
+ * same way. Canton Coin is not transferred or burnt through this wallet.
16
+ *
17
+ * Trust: a holding counts when its instrument admin (DA's registrar, or for Canton Coin the DSO) and its owner signed
18
+ * it; an offer, a request or a preapproval when it names DA's operator and (offers and requests) a provider trusted for
19
+ * its instrument admin signed it. By default a registrar must be its own provider; `registry.trustedProviders` trusts
20
+ * others (see `isFromRegistry`). A Canton Coin offer counts when it is of Canton Coin and the DSO and its sender signed
21
+ * it. The DSO party is resolved once for both (`createAmuletRegistry`): pinned, else the registry's `adminId`; while it
22
+ * is unconfirmed, no Canton Coin is listed (`WalletState.cantonCoinUnavailable`).
15
23
  */
16
24
  const cip103_1 = require("./cip103");
17
25
  const commands_1 = require("./commands");
18
26
  const contracts_1 = require("./contracts");
19
27
  const client_1 = require("./da-utilities/client");
20
28
  const abort_1 = require("./abort");
29
+ const constants_1 = require("./amulet/constants");
30
+ const registry_1 = require("./amulet/registry");
21
31
  const errors_1 = require("./errors");
32
+ const holding_view_1 = require("./holding-view");
22
33
  const holdings_1 = require("./holdings");
23
- const templates_1 = require("../da-registry/templates");
24
- const constants_1 = require("../utils/token-standard/v1/constants");
34
+ const decimal_1 = require("./decimal");
35
+ const instrument_1 = require("./instrument");
36
+ const json_1 = require("./json");
37
+ const templates_1 = require("./templates");
38
+ const tokens_1 = require("./tokens");
39
+ const templates_2 = require("../da-registry/templates");
40
+ const constants_2 = require("../utils/token-standard/v1/constants");
25
41
  const SECOND_MS = 1000;
26
42
  const DAY_MS = 24 * 60 * 60 * SECOND_MS;
27
43
  /** Transfers: `executeBefore` defaults to now + 24 h, a common wallet default. */
@@ -68,14 +84,37 @@ const TRANSFER_KIND_DESCRIPTIONS = {
68
84
  offer: 'Offer: the receiver must accept it before it expires. Your tokens stay locked until it is accepted, rejected by the receiver or withdrawn by you; expiry only stops acceptance and does not unlock them.',
69
85
  self: 'Self-transfer: the receiver is this wallet; the holdings are merged or split.',
70
86
  };
71
- /** Every template a state snapshot reads, in one cumulative filter. */
72
- const STATE_TEMPLATES = [
73
- templates_1.DA_REGISTRY_TEMPLATES.holding,
74
- templates_1.DA_REGISTRY_TEMPLATES.transferOffer,
75
- templates_1.DA_REGISTRY_TEMPLATES.mintOffer,
76
- templates_1.DA_REGISTRY_TEMPLATES.burnRequest,
77
- templates_1.DA_REGISTRY_TEMPLATES.transferPreapproval,
87
+ /** The DA templates a state snapshot reads. */
88
+ const DA_STATE_TEMPLATES = [
89
+ templates_2.DA_REGISTRY_TEMPLATES.holding,
90
+ templates_2.DA_REGISTRY_TEMPLATES.transferOffer,
91
+ templates_2.DA_REGISTRY_TEMPLATES.mintOffer,
92
+ templates_2.DA_REGISTRY_TEMPLATES.burnRequest,
93
+ templates_2.DA_REGISTRY_TEMPLATES.transferPreapproval,
94
+ ];
95
+ /** Canton Coin's holdings, read through the `HoldingV1` view (the interface filter matches DA's `Holding` too). */
96
+ const CANTON_COIN_HOLDING_FILTERS = [
97
+ { interfaceId: holding_view_1.HOLDING_V1_INTERFACE_ID, includeInterfaceView: true },
78
98
  ];
99
+ /**
100
+ * Every filter a state snapshot reads with Canton Coin on, in one cumulative filter: `HoldingV1` with its view (it
101
+ * matches Canton Coin's `Amulet` and `LockedAmulet`, and DA's `Holding` again, which the ledger returns once), the DA
102
+ * templates, and Canton Coin's transfer instructions.
103
+ */
104
+ const CANTON_COIN_STATE_FILTERS = [
105
+ ...CANTON_COIN_HOLDING_FILTERS,
106
+ ...DA_STATE_TEMPLATES,
107
+ constants_1.AMULET_TEMPLATES.transferInstruction,
108
+ ];
109
+ /** Canton Coin's holding templates. */
110
+ const CANTON_COIN_HOLDING_TEMPLATES = [constants_1.AMULET_TEMPLATES.amulet, constants_1.AMULET_TEMPLATES.lockedAmulet];
111
+ /** Canton Coin contracts whose DSO must be confirmed before they are listed. */
112
+ const CANTON_COIN_TEMPLATES = [
113
+ ...CANTON_COIN_HOLDING_TEMPLATES,
114
+ constants_1.AMULET_TEMPLATES.transferInstruction,
115
+ ];
116
+ /** Whether any of `contracts` is of one of `templateIds`. */
117
+ const anyOf = (contracts, templateIds) => contracts.some((contract) => templateIds.some((templateId) => (0, templates_1.isTemplate)(contract, templateId)));
79
118
  function requireNonEmpty(value, field) {
80
119
  if (typeof value !== 'string' || value.trim().length === 0) {
81
120
  throw new errors_1.WalletError('invalid-input', `${field} is required`);
@@ -116,6 +155,12 @@ function createWallet(options) {
116
155
  throw new TypeError('createWallet: network must be devnet or mainnet');
117
156
  const registry = (0, client_1.createDaUtilitiesClient)(network, options.registry);
118
157
  const now = () => requireTime(clock(), 'now()');
158
+ /** Canton Coin's registry: the one DSO resolution holdings and offers share; null with `cantonCoin: false`. */
159
+ const cantonCoin = options.cantonCoin === false ? null : (0, registry_1.createAmuletRegistry)(network, options.cantonCoin, { now });
160
+ const stateFilters = cantonCoin === null ? DA_STATE_TEMPLATES : CANTON_COIN_STATE_FILTERS;
161
+ const offerTemplates = cantonCoin === null
162
+ ? [templates_2.DA_REGISTRY_TEMPLATES.transferOffer]
163
+ : [templates_2.DA_REGISTRY_TEMPLATES.transferOffer, constants_1.AMULET_TEMPLATES.transferInstruction];
119
164
  /** Refuse a write once the wallet session this wallet belongs to ended (`isActive`). */
120
165
  function requireActive() {
121
166
  if (isActive !== undefined && !isActive()) {
@@ -125,7 +170,8 @@ function createWallet(options) {
125
170
  const ledger = (0, cip103_1.cip103Wallet)(provider, partyId, readRetry !== undefined ? { readRetry } : {});
126
171
  /** A ledger read; an aborted `signal` stops waiting for it (the wallet's read itself cannot be cancelled). */
127
172
  async function read(templateId, signal) {
128
- return (await (0, abort_1.awaitWithAbort)(async () => ledger.readActiveContracts([templateId]), signal)).contracts;
173
+ const templateIds = typeof templateId === 'string' ? [templateId] : templateId;
174
+ return (await (0, abort_1.awaitWithAbort)(async () => ledger.readActiveContracts(templateIds), signal)).contracts;
129
175
  }
130
176
  async function submit(submission, signal) {
131
177
  // Checked again right before the wallet signs: a write's reads and registry calls await, and the session may end
@@ -154,10 +200,66 @@ function createWallet(options) {
154
200
  writesSettled += 1;
155
201
  }
156
202
  }
157
- const holdingsIn = (contracts) => contracts.flatMap((contract) => {
158
- const holding = (0, holdings_1.parseHolding)(contract);
159
- return holding !== null && holding.owner === partyId ? [holding] : [];
160
- });
203
+ /**
204
+ * The confirmed DSO party for the Canton Coin among `contracts`. The registry is asked only when there is Canton Coin
205
+ * to check, so a party without any never calls it. `unavailable` when there is but the DSO cannot be confirmed: all
206
+ * of it is then left out (fail closed, never every DSO's).
207
+ */
208
+ async function cantonCoinDso(contracts, signal, waitMs) {
209
+ if (cantonCoin === null || !anyOf(contracts, CANTON_COIN_TEMPLATES)) {
210
+ return { dso: undefined, unavailable: false };
211
+ }
212
+ const dso = await cantonCoin.dsoParty(signal, waitMs);
213
+ return { dso, unavailable: dso === undefined };
214
+ }
215
+ /**
216
+ * The party's genuine holdings among `contracts`, each contract once. Canton Coin counts only when it is of the
217
+ * confirmed `dso`; without one, none does.
218
+ */
219
+ function holdingsIn(contracts, dso) {
220
+ const seen = new Set();
221
+ return contracts.flatMap((contract) => {
222
+ const holding = (0, holdings_1.parseHolding)(contract);
223
+ if (holding?.owner !== partyId || seen.has(holding.contractId))
224
+ return [];
225
+ if ((0, holdings_1.isCantonCoin)(holding) && (dso === undefined || holding.instrumentId.admin !== dso))
226
+ return [];
227
+ seen.add(holding.contractId);
228
+ return [holding];
229
+ });
230
+ }
231
+ /** The party's DA Registry holdings, for a transfer or burn (Canton Coin is read-only here). */
232
+ const daHoldingsIn = (contracts) => holdingsIn(contracts).filter((holding) => !(0, holdings_1.isCantonCoin)(holding));
233
+ /**
234
+ * Refuse a Canton Coin transfer or burn: this wallet only reads Canton Coin. Before any read when the instrument is
235
+ * the known DSO's `Amulet` (pinned, or already confirmed by the registry); otherwise (`holdings` given) an `Amulet`
236
+ * the party holds no DA Registry holding of. A DA Registry instrument a registrar named `Amulet` stays transferable.
237
+ */
238
+ function refuseCantonCoin(instrumentId, action, holdings) {
239
+ if (instrumentId.id !== constants_1.AMULET_INSTRUMENT_ID)
240
+ return;
241
+ if (cantonCoin === null)
242
+ return;
243
+ const knownDso = cantonCoin.knownDsoParty();
244
+ // A known DSO decides; otherwise, with the holdings read, an `Amulet` the party holds no DA Registry holding of.
245
+ const isAmulet = knownDso !== undefined
246
+ ? instrumentId.admin === knownDso
247
+ : holdings !== undefined &&
248
+ !holdings.some((holding) => holding.instrumentId.admin === instrumentId.admin && holding.instrumentId.id === instrumentId.id);
249
+ if (isAmulet) {
250
+ throw new errors_1.WalletError('invalid-input', `Canton Coin (Amulet) cannot be ${action} through this wallet yet; nothing was submitted`);
251
+ }
252
+ }
253
+ /**
254
+ * Refuse a DA transfer preapproval for Canton Coin's DSO: it would do nothing for Canton Coin (a DSO
255
+ * `TransferPreapproval` is made through a validator, not this wallet). `dso` is the DSO party: pinned, or confirmed
256
+ * by Canton Coin's registry; undefined when neither is known.
257
+ */
258
+ function refuseCantonCoinPreapproval(instrumentAdmin, dso) {
259
+ if (dso !== undefined && instrumentAdmin === dso) {
260
+ throw new errors_1.WalletError('invalid-input', `${instrumentAdmin} is Canton Coin's DSO party: a DA transfer preapproval does nothing for Canton Coin; nothing was submitted`);
261
+ }
262
+ }
161
263
  /** The registry contracts of `parse` among `contracts` that DA's registry made (see `isFromRegistry`). */
162
264
  function fromRegistry(contracts, parse, operator) {
163
265
  return contracts.flatMap((contract) => {
@@ -169,13 +271,29 @@ function createWallet(options) {
169
271
  }
170
272
  const ownMintOffers = (contracts, operator) => fromRegistry(contracts, contracts_1.parseMintOffer, operator).filter((offer) => offer.holder === partyId);
171
273
  const ownBurnRequests = (contracts, operator) => fromRegistry(contracts, contracts_1.parseBurnRequest, operator).filter((request) => request.holder === partyId);
172
- function transferOffers(contracts, operator) {
173
- const offers = fromRegistry(contracts, contracts_1.parseTransferOffer, operator);
174
- return {
175
- incoming: offers.filter((offer) => offer.receiver === partyId && offer.sender !== partyId),
176
- outgoing: offers.filter((offer) => offer.sender === partyId),
177
- };
274
+ /**
275
+ * DA's transfer offers among `contracts` that DA's registry made, and Canton Coin's of the confirmed `dso` that the
276
+ * DSO and their sender signed (none without one).
277
+ */
278
+ function transferOffers(contracts, operator, dso) {
279
+ return byDirection([
280
+ ...fromRegistry(contracts, contracts_1.parseTransferOffer, operator),
281
+ ...amuletTransferOffers(contracts, dso),
282
+ ]);
283
+ }
284
+ /** Canton Coin's transfer offers among `contracts` of the confirmed `dso`, signed by it and their sender. */
285
+ function amuletTransferOffers(contracts, dso) {
286
+ if (dso === undefined)
287
+ return [];
288
+ return contracts.flatMap((contract) => {
289
+ const offer = (0, contracts_1.parseAmuletTransferOffer)(contract, dso);
290
+ return offer === null ? [] : [offer];
291
+ });
178
292
  }
293
+ const byDirection = (offers) => ({
294
+ incoming: offers.filter((offer) => offer.receiver === partyId && offer.sender !== partyId),
295
+ outgoing: offers.filter((offer) => offer.sender === partyId),
296
+ });
179
297
  /** The party's own preapprovals under DA's operator: the party is their only signatory. */
180
298
  const ownPreapprovals = (contracts, operator) => contracts.flatMap((contract) => {
181
299
  const preapproval = (0, contracts_1.parseTransferPreapproval)(contract);
@@ -194,24 +312,49 @@ function createWallet(options) {
194
312
  }
195
313
  return found;
196
314
  }
197
- async function balancesWithMetadata(holdings) {
315
+ /** The balances of `holdings`, each with its registry's metadata (Canton Coin's is given: it is looked up apart). */
316
+ async function balancesWithMetadata(holdings, cantonCoinMetadata) {
198
317
  return Promise.all((0, holdings_1.instrumentBalances)(holdings).map(async (balance) => {
199
- const metadata = await registry.instrumentMetadata(balance.instrumentId);
318
+ const metadata = (0, holdings_1.isCantonCoin)(balance)
319
+ ? cantonCoinMetadata
320
+ : await registry.instrumentMetadata(balance.instrumentId);
200
321
  return metadata === undefined ? balance : { ...balance, metadata };
201
322
  }));
202
323
  }
203
324
  async function readState() {
204
- const { offset, contracts } = await ledger.readActiveContracts(STATE_TEMPLATES);
205
- const holdings = holdingsIn(contracts);
206
- const [operator, balances] = await Promise.all([registry.operatorParty(), balancesWithMetadata(holdings)]);
325
+ const { offset, contracts } = await ledger.readActiveContracts(stateFilters);
326
+ // Asked only when the party has Canton Coin. The DSO and Canton Coin's metadata are looked up at once, so a
327
+ // snapshot waits for the registry once (see `createAmuletRegistry` for how long).
328
+ const [{ dso, unavailable }, cantonCoinMetadata] = await Promise.all([
329
+ cantonCoinDso(contracts, undefined),
330
+ cantonCoin !== null && anyOf(contracts, CANTON_COIN_HOLDING_TEMPLATES)
331
+ ? cantonCoin.instrumentMetadata()
332
+ : undefined,
333
+ ]);
334
+ const holdings = holdingsIn(contracts, dso);
335
+ const [operator, balances] = await Promise.all([
336
+ registry.operatorParty(),
337
+ balancesWithMetadata(holdings, cantonCoinMetadata),
338
+ ]);
339
+ const at = now();
340
+ const withExpiry = (offers) => offers.map((offer) => ({ ...offer, expired: (0, tokens_1.isTransferOfferExpired)(offer, at) }));
341
+ const offers = transferOffers(contracts, operator, dso);
342
+ const outgoing = withExpiry(offers.outgoing);
343
+ const reclaimable = (0, tokens_1.lockedInExpiredOffers)(holdings, outgoing.filter((offer) => offer.expired === true));
344
+ const inExpiredLocks = (0, tokens_1.unitsByInstrument)((0, tokens_1.expiredUnclaimedLocks)(holdings, [...offers.incoming, ...offers.outgoing], at));
207
345
  return {
208
346
  offset,
209
347
  holdings,
210
- balances,
211
- transferOffers: transferOffers(contracts, operator),
348
+ balances: balances.map((balance) => ({
349
+ ...balance,
350
+ lockedInExpiredOffers: (0, decimal_1.formatDecimalUnits)(reclaimable.get(balance.key) ?? 0n),
351
+ lockedInExpiredLocks: (0, decimal_1.formatDecimalUnits)(inExpiredLocks.get(balance.key) ?? 0n),
352
+ })),
353
+ transferOffers: { incoming: withExpiry(offers.incoming), outgoing },
212
354
  mintOffers: ownMintOffers(contracts, operator),
213
355
  burnRequests: ownBurnRequests(contracts, operator),
214
356
  transferPreapprovals: ownPreapprovals(contracts, operator),
357
+ cantonCoinUnavailable: unavailable,
215
358
  };
216
359
  }
217
360
  let inFlight;
@@ -233,9 +376,11 @@ function createWallet(options) {
233
376
  /** A validated, frozen copy of a transfer request, so a later change to the caller's object changes nothing. */
234
377
  function plannedRequest(request) {
235
378
  const { memo, requirePreapproval, executeBefore } = request;
379
+ const instrumentId = requireInstrumentId(request.instrumentId);
380
+ refuseCantonCoin(instrumentId, 'transferred');
236
381
  return Object.freeze({
237
382
  receiver: requireNonEmpty(request.receiver, 'receiver'),
238
- instrumentId: Object.freeze(requireInstrumentId(request.instrumentId)),
383
+ instrumentId: Object.freeze(instrumentId),
239
384
  amount: request.amount,
240
385
  ...(memo !== undefined && memo.length > 0 && { memo }),
241
386
  ...(requirePreapproval === true && { requirePreapproval }),
@@ -249,7 +394,9 @@ function createWallet(options) {
249
394
  async function prepareTransfer(request, signal) {
250
395
  const at = now();
251
396
  const executeBefore = deadline(request.executeBefore, at, TRANSFER_TTL_MS);
252
- const selection = (0, holdings_1.selectHoldings)(holdingsIn(await read(templates_1.DA_REGISTRY_TEMPLATES.holding, signal)), {
397
+ const daHoldings = daHoldingsIn(await read(templates_2.DA_REGISTRY_TEMPLATES.holding, signal));
398
+ refuseCantonCoin(request.instrumentId, 'transferred', daHoldings);
399
+ const selection = (0, holdings_1.selectHoldings)(daHoldings, {
253
400
  owner: partyId,
254
401
  instrumentId: request.instrumentId,
255
402
  amount: request.amount,
@@ -262,7 +409,7 @@ function createWallet(options) {
262
409
  requestedAt: isoTime(at - REQUESTED_AT_SKEW_MS, 'requestedAt'),
263
410
  executeBefore,
264
411
  inputHoldingCids: selection.inputHoldingCids,
265
- meta: { values: request.memo !== undefined ? { [constants_1.TOKEN_STANDARD_V1_REASON_META_KEY]: request.memo } : {} },
412
+ meta: { values: request.memo !== undefined ? { [constants_2.TOKEN_STANDARD_V1_REASON_META_KEY]: request.memo } : {} },
266
413
  };
267
414
  const factory = await registry.transferFactory(request.instrumentId.admin, transfer, signal);
268
415
  const factoryError = (0, client_1.factoryTemplateError)(factory, client_1.DA_TRANSFER_FACTORY_TEMPLATES[factory.transferKind]);
@@ -306,34 +453,159 @@ function createWallet(options) {
306
453
  });
307
454
  }
308
455
  async function answerTransferOffer(transferOfferCid, action, signal) {
309
- const [contracts, operator] = await Promise.all([
310
- read(templates_1.DA_REGISTRY_TEMPLATES.transferOffer, signal),
311
- registry.operatorParty(signal),
312
- ]);
313
- const { incoming, outgoing } = transferOffers(contracts, operator);
456
+ // Read the target first, then resolve only the registry that validates it: the DSO for a Canton Coin offer, DA's
457
+ // operator for a DA offer. Neither offer kind depends on the other registry being up.
458
+ const target = (await read(offerTemplates, signal)).filter((contract) => contract.contractId === transferOfferCid);
459
+ let offers;
460
+ if (cantonCoin !== null && anyOf(target, [constants_1.AMULET_TEMPLATES.transferInstruction])) {
461
+ const { dso, unavailable } = await cantonCoinDso(target, signal, registry_1.AMULET_REGISTRY_REQUEST_TIMEOUT_MS);
462
+ if (unavailable) {
463
+ throw new errors_1.RegistryResponseError(`${registry_1.AMULET_REGISTRY_NAME} could not confirm Canton Coin's DSO party, so transfer offer ${transferOfferCid} cannot be checked; nothing was submitted. Try again later, or pin cantonCoin.dsoParty.`);
464
+ }
465
+ offers = byDirection(amuletTransferOffers(target, dso));
466
+ }
467
+ else if (anyOf(target, [templates_2.DA_REGISTRY_TEMPLATES.transferOffer])) {
468
+ offers = byDirection(fromRegistry(target, contracts_1.parseTransferOffer, await registry.operatorParty(signal)));
469
+ }
470
+ else {
471
+ offers = { incoming: [], outgoing: [] };
472
+ }
473
+ const { incoming, outgoing } = offers;
314
474
  const offer = find(action === 'withdraw' ? outgoing : incoming, transferOfferCid, action === 'withdraw' ? 'Outgoing transfer offer' : 'Incoming transfer offer');
315
- const context = await registry.transferInstructionContext(offer.instrumentId.admin, transferOfferCid, action, signal);
475
+ return submitOfferAnswer(offer, action, signal);
476
+ }
477
+ /** Exercise `action` on a transfer offer already read and validated, with its own registry's choice context. */
478
+ async function submitOfferAnswer(offer, action, signal) {
479
+ const transferOfferCid = offer.contractId;
480
+ const context = offer.registry === 'amulet' && cantonCoin !== null
481
+ ? await cantonCoin.transferInstructionContext(transferOfferCid, action, signal)
482
+ : await registry.transferInstructionContext(offer.instrumentId.admin, transferOfferCid, action, signal);
316
483
  return submit({
317
484
  commands: [(0, commands_1.transferInstructionCommand)(transferOfferCid, action, context.choiceContextData)],
318
485
  disclosedContracts: context.disclosedContracts,
319
486
  }, signal);
320
487
  }
488
+ /**
489
+ * Withdraw every one of the party's own expired transfer offers of `instrumentId`, one submission each, oldest
490
+ * deadline first; with `releaseLocks`, then release each of the party's own expired Canton Coin locks of it that no
491
+ * active offer names (`LockedAmulet_OwnerExpireLockV2`), oldest expiry first. Read once; each offer is withdrawn
492
+ * through its own registry (Canton Coin's for a Canton Coin offer, DA's for a DA offer), exactly as
493
+ * `withdrawTransferOffer` does. Stops at the first failure: thrown when nothing committed yet, else reported in the
494
+ * result (what committed stays committed; a reload shows it).
495
+ */
496
+ async function runReclaim(instrumentIdInput, releaseLocks, signal) {
497
+ const instrumentId = requireInstrumentId(instrumentIdInput);
498
+ // A known DSO decides: a registrar's own `Amulet` (another admin) goes straight to DA's path, never to Scan.
499
+ const knownDso = cantonCoin?.knownDsoParty();
500
+ const isAmuletId = cantonCoin !== null &&
501
+ instrumentId.id === constants_1.AMULET_INSTRUMENT_ID &&
502
+ (knownDso === undefined || instrumentId.admin === knownDso);
503
+ const readLocks = releaseLocks && isAmuletId;
504
+ const all = readLocks
505
+ ? (await (0, abort_1.awaitWithAbort)(async () => ledger.readActiveContracts([...offerTemplates, ...CANTON_COIN_HOLDING_FILTERS]), signal)).contracts
506
+ : await read(offerTemplates, signal);
507
+ const contracts = all.filter((contract) => {
508
+ const transfer = contract.createArgument?.['transfer'];
509
+ return (0, json_1.isRecord)(transfer) && transfer['sender'] === partyId;
510
+ });
511
+ const candidates = [];
512
+ let cantonCoinUnconfirmed = false;
513
+ let expiredLocks = [];
514
+ if (isAmuletId &&
515
+ (readLocks ? anyOf(all, CANTON_COIN_TEMPLATES) : anyOf(contracts, [constants_1.AMULET_TEMPLATES.transferInstruction]))) {
516
+ const { dso, unavailable } = await cantonCoinDso(all, signal, registry_1.AMULET_REGISTRY_REQUEST_TIMEOUT_MS);
517
+ cantonCoinUnconfirmed = unavailable;
518
+ candidates.push(...amuletTransferOffers(contracts, dso));
519
+ if (readLocks && dso !== undefined) {
520
+ expiredLocks = (0, tokens_1.expiredUnclaimedLocks)(holdingsIn(all, dso), amuletTransferOffers(all, dso), now())
521
+ .filter((holding) => (0, instrument_1.sameInstrument)(holding.instrumentId, instrumentId))
522
+ .sort((a, b) => Date.parse(a.lockExpiresAt ?? '') - Date.parse(b.lockExpiresAt ?? '') ||
523
+ (a.contractId < b.contractId ? -1 : 1));
524
+ }
525
+ }
526
+ const cantonCoinUnconfirmedError = () => new errors_1.RegistryResponseError(`${registry_1.AMULET_REGISTRY_NAME} could not confirm Canton Coin's DSO party, so the wallet's Canton Coin offers cannot be checked; nothing was submitted. Try again later, or pin cantonCoin.dsoParty.`);
527
+ const isAmuletOf = candidates.some((offer) => (0, instrument_1.sameInstrument)(offer.instrumentId, instrumentId));
528
+ if (!isAmuletOf && expiredLocks.length === 0 && anyOf(contracts, [templates_2.DA_REGISTRY_TEMPLATES.transferOffer])) {
529
+ let operator;
530
+ try {
531
+ operator = await registry.operatorParty(signal);
532
+ }
533
+ catch (error) {
534
+ // Canton Coin's `Amulet` with an unconfirmed DSO: only Scan can validate its offers, so say that, not why DA's
535
+ // operator (asked in case a registrar issued an `Amulet` of its own) could not be read.
536
+ (0, abort_1.throwIfAborted)(signal);
537
+ if (cantonCoinUnconfirmed)
538
+ throw cantonCoinUnconfirmedError();
539
+ throw error;
540
+ }
541
+ candidates.push(...fromRegistry(contracts, contracts_1.parseTransferOffer, operator));
542
+ }
543
+ const at = now();
544
+ const expired = byDirection(candidates)
545
+ .outgoing.filter((offer) => (0, instrument_1.sameInstrument)(offer.instrumentId, instrumentId) && (0, tokens_1.isTransferOfferExpired)(offer, at))
546
+ .sort((a, b) => Date.parse(a.executeBefore) - Date.parse(b.executeBefore) || (a.contractId < b.contractId ? -1 : 1));
547
+ if (expired.length === 0 && expiredLocks.length === 0) {
548
+ if (cantonCoinUnconfirmed)
549
+ throw cantonCoinUnconfirmedError();
550
+ throw new errors_1.WalletError('not-found', releaseLocks
551
+ ? `The wallet has no expired outgoing transfer offers or expired locks of ${instrumentId.id}; nothing was submitted`
552
+ : `The wallet has no expired outgoing transfer offers of ${instrumentId.id}; nothing was submitted`);
553
+ }
554
+ const steps = [
555
+ ...expired.map((offer) => ({ kind: 'offer', offer })),
556
+ ...expiredLocks.map((holding) => ({ kind: 'lock', holding })),
557
+ ];
558
+ const contractIdOf = (step) => step.kind === 'offer' ? step.offer.contractId : step.holding.contractId;
559
+ const withdrawn = [];
560
+ const released = [];
561
+ for (const [index, step] of steps.entries()) {
562
+ try {
563
+ if (step.kind === 'offer') {
564
+ const result = await submitOfferAnswer(step.offer, 'withdraw', signal);
565
+ withdrawn.push({
566
+ ...result,
567
+ transferOfferCid: step.offer.contractId,
568
+ amount: step.offer.amount,
569
+ registry: step.offer.registry ?? 'da',
570
+ });
571
+ }
572
+ else {
573
+ const result = await submit({ commands: [(0, commands_1.ownerExpireLockCommand)(step.holding.contractId)] }, signal);
574
+ released.push({ ...result, lockedHoldingCid: step.holding.contractId, amount: step.holding.amount });
575
+ }
576
+ }
577
+ catch (error) {
578
+ if (index === 0)
579
+ throw error;
580
+ return {
581
+ withdrawn,
582
+ released,
583
+ failed: { contractId: contractIdOf(step), error },
584
+ notAttempted: steps.slice(index + 1).map(contractIdOf),
585
+ };
586
+ }
587
+ }
588
+ return { withdrawn, released, notAttempted: [] };
589
+ }
321
590
  async function ownMintOffer(mintOfferCid, signal) {
322
591
  const [contracts, operator] = await Promise.all([
323
- read(templates_1.DA_REGISTRY_TEMPLATES.mintOffer, signal),
592
+ read(templates_2.DA_REGISTRY_TEMPLATES.mintOffer, signal),
324
593
  registry.operatorParty(signal),
325
594
  ]);
326
595
  return find(ownMintOffers(contracts, operator), mintOfferCid, 'Mint offer');
327
596
  }
328
597
  async function runRequestBurn(burn, signal) {
329
598
  const instrumentId = requireInstrumentId(burn.instrumentId);
599
+ refuseCantonCoin(instrumentId, 'burned');
330
600
  const at = now();
331
601
  const reference = burn.reference ?? newBurnReference(new Date(at));
332
602
  if (typeof reference !== 'string' || !exports.BURN_REFERENCE_PATTERN.test(reference)) {
333
603
  throw new errors_1.WalletError('invalid-input', 'reference must be 1-100 characters of letters, digits and . _ : - (starting with a letter or digit), with no personal data');
334
604
  }
335
605
  const executeBefore = deadline(burn.executeBefore, at, BURN_TTL_MS);
336
- const selection = (0, holdings_1.selectHoldings)(holdingsIn(await read(templates_1.DA_REGISTRY_TEMPLATES.holding, signal)), {
606
+ const daHoldings = daHoldingsIn(await read(templates_2.DA_REGISTRY_TEMPLATES.holding, signal));
607
+ refuseCantonCoin(instrumentId, 'burned', daHoldings);
608
+ const selection = (0, holdings_1.selectHoldings)(daHoldings, {
337
609
  owner: partyId,
338
610
  instrumentId,
339
611
  amount: burn.amount,
@@ -384,19 +656,27 @@ function createWallet(options) {
384
656
  }
385
657
  async function runCreateTransferPreapproval(preapproval, signal) {
386
658
  const instrumentAdmin = requireNonEmpty(preapproval.instrumentAdmin, 'instrumentAdmin');
659
+ // A known DSO (pinned, or confirmed earlier) refuses before any read.
660
+ const knownDso = cantonCoin?.knownDsoParty();
661
+ refuseCantonCoinPreapproval(instrumentAdmin, knownDso);
387
662
  const instrumentIds = [...new Set(preapproval.instrumentIds ?? [])];
388
663
  if (instrumentIds.length > commands_1.MAX_PREAPPROVAL_INSTRUMENTS) {
389
664
  throw new errors_1.WalletError('invalid-input', `A preapproval allows at most ${commands_1.MAX_PREAPPROVAL_INSTRUMENTS} instrument ids`);
390
665
  }
391
666
  instrumentIds.forEach((id) => requireNonEmpty(id, 'instrumentIds[]'));
392
- const [contracts, operator] = await Promise.all([
393
- read(templates_1.DA_REGISTRY_TEMPLATES.transferPreapproval, signal),
667
+ // Only the party's preapprovals are read (never its holdings, which could exceed the participant's ACS list limit).
668
+ // Unpinned and not yet confirmed, Canton Coin's registry is asked for the DSO alongside, with its usual bounds (the
669
+ // whole request on a first lookup, then a short wait; nothing during the back-off after a failure). When it cannot
670
+ // confirm the DSO, the DA preapproval is still created (fail open): DA writes do not depend on Scan, and a DA
671
+ // preapproval naming the DSO is inert (it lets no Canton Coin in) and can be withdrawn.
672
+ const [contracts, operator, dso] = await Promise.all([
673
+ read(templates_2.DA_REGISTRY_TEMPLATES.transferPreapproval, signal),
394
674
  registry.operatorParty(signal),
675
+ cantonCoin === null || knownDso !== undefined ? knownDso : cantonCoin.dsoParty(signal),
395
676
  ]);
396
- const covering = ownPreapprovals(contracts, operator).find((existing) => existing.instrumentAdmin === instrumentAdmin &&
397
- (existing.instrumentIds.length === 0 ||
398
- (instrumentIds.length > 0 && instrumentIds.every((id) => existing.instrumentIds.includes(id)))));
399
- if (covering !== undefined) {
677
+ refuseCantonCoinPreapproval(instrumentAdmin, dso);
678
+ const covering = (0, contracts_1.coveringPreapproval)(ownPreapprovals(contracts, operator), { instrumentAdmin, instrumentIds });
679
+ if (covering !== null) {
400
680
  throw new errors_1.WalletError('already-exists', `Transfer preapproval ${covering.contractId} already covers ${instrumentIds.length === 0 ? 'every instrument' : instrumentIds.join(', ')} of ${instrumentAdmin}; nothing was submitted`);
401
681
  }
402
682
  return submit({
@@ -405,7 +685,7 @@ function createWallet(options) {
405
685
  }
406
686
  async function runRemoveTransferPreapproval(preapprovalCid, signal) {
407
687
  const [contracts, operator] = await Promise.all([
408
- read(templates_1.DA_REGISTRY_TEMPLATES.transferPreapproval, signal),
688
+ read(templates_2.DA_REGISTRY_TEMPLATES.transferPreapproval, signal),
409
689
  registry.operatorParty(signal),
410
690
  ]);
411
691
  find(ownPreapprovals(contracts, operator), preapprovalCid, 'Transfer preapproval');
@@ -419,6 +699,8 @@ function createWallet(options) {
419
699
  acceptTransferOffer: async (cid, { signal } = {}) => exclusive(signal, async () => answerTransferOffer(cid, 'accept', signal)),
420
700
  rejectTransferOffer: async (cid, { signal } = {}) => exclusive(signal, async () => answerTransferOffer(cid, 'reject', signal)),
421
701
  withdrawTransferOffer: async (cid, { signal } = {}) => exclusive(signal, async () => answerTransferOffer(cid, 'withdraw', signal)),
702
+ withdrawExpiredTransferOffers: async (instrumentId, { signal } = {}) => exclusive(signal, async () => runReclaim(instrumentId, false, signal)),
703
+ reclaimLockedTokens: async (instrumentId, { signal } = {}) => exclusive(signal, async () => runReclaim(instrumentId, true, signal)),
422
704
  acceptMintOffer: async (cid, { signal } = {}) => exclusive(signal, async () => {
423
705
  await ownMintOffer(cid, signal);
424
706
  const context = await registry.mintOfferAcceptContext(cid, signal);
@@ -434,7 +716,7 @@ function createWallet(options) {
434
716
  requestBurn: async (burn, { signal } = {}) => exclusive(signal, async () => runRequestBurn(burn, signal)),
435
717
  cancelBurnRequest: async (cid, { signal } = {}) => exclusive(signal, async () => {
436
718
  const [contracts, operator] = await Promise.all([
437
- read(templates_1.DA_REGISTRY_TEMPLATES.burnRequest, signal),
719
+ read(templates_2.DA_REGISTRY_TEMPLATES.burnRequest, signal),
438
720
  registry.operatorParty(signal),
439
721
  ]);
440
722
  find(ownBurnRequests(contracts, operator), cid, 'Burn request');