@partylayer/sdk 0.20.0 → 0.21.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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { toWalletId, toPartyId, isRecognizedNetwork, detectNetworkMismatch, ledgerApiBodyToObject, normalizeLedgerMethodLower, hashForPrivacy, createMetricsPayload, isOfficialAdapterFactory, isOfficialProviderAdapter, mapUnknownErrorToPartyLayerError, findMatchingWalletInfo, NetworkMismatchError, METRICS, WalletNotFoundError, AdapterNotRegisteredError, capabilityGuard, installGuard, toSessionId, CapabilityNotSupportedError, toTransferIntent, errorMetricName, TransportError, toSignature, toTransactionHash, toCAIP2Network } from '@partylayer/core';
1
+ import { toWalletId, toPartyId, isRecognizedNetwork, detectNetworkMismatch, ledgerApiBodyToObject, normalizeLedgerMethodLower, hashForPrivacy, createMetricsPayload, isOfficialAdapterFactory, isOfficialProviderAdapter, mapUnknownErrorToPartyLayerError, findMatchingWalletInfo, NetworkMismatchError, METRICS, WalletNotFoundError, AdapterNotRegisteredError, capabilityGuard, installGuard, toSessionId, CapabilityNotSupportedError, toTransferIntent, errorMetricName, TransportError, toSignature, toCAIP2Network, toTransactionHash } from '@partylayer/core';
2
2
  export { AdapterNotRegisteredError, PartyLayerError as CantonConnectError, CapabilityNotSupportedError, ENABLEMENT_METRICS, ERROR_METRICS, InternalError, METRICS, OriginNotAllowedError, PartyLayerError, REGISTRY_METRICS, RegistryFetchFailedError, RegistrySchemaInvalidError, RegistryVerificationFailedError, SessionExpiredError, TRANSFER_INTENT_FIELDS, TimeoutError, TransportError, UserRejectedError, WalletNotFoundError, WalletNotInstalledError, errorMetricName, isOfficialAdapterFactory, isOfficialProviderAdapter, toTransferIntent } from '@partylayer/core';
3
3
  import { RegistryClient } from '@partylayer/registry-client';
4
4
  export { deriveGenericWalletName, findMatchingWallet, findMatchingWalletInfo, isCip0103Native, matchesProviderDetection } from '@partylayer/registry-client';
@@ -439,13 +439,13 @@ var NativeConnectionOwner = class {
439
439
  this.identityRefreshing = true;
440
440
  let verified = false;
441
441
  try {
442
- const identity = await this.probe(provider, this.registrations.get(id));
442
+ const identity2 = await this.probe(provider, this.registrations.get(id));
443
443
  if (revision !== this.refreshRevision || this.getProvider(id) !== provider)
444
444
  throw disconnected();
445
445
  verified = true;
446
- this.projection = { id, identity };
447
- if (identity.account.partyId !== partyId || detectNetworkMismatch(network, identity.network)) {
448
- this.changed(id, identity);
446
+ this.projection = { id, identity: identity2 };
447
+ if (identity2.account.partyId !== partyId || detectNetworkMismatch(network, identity2.network)) {
448
+ this.changed(id, identity2);
449
449
  throw new Error("Wallet identity changed during message signing");
450
450
  }
451
451
  } catch (error) {
@@ -490,12 +490,12 @@ var NativeConnectionOwner = class {
490
490
  this.identityRefreshing = true;
491
491
  const registration = this.registrations.get(id);
492
492
  void this.probe(provider, registration).then(
493
- (identity) => {
493
+ (identity2) => {
494
494
  if (revision !== this.refreshRevision || this.projection?.id !== id || this.disposed)
495
495
  return;
496
496
  this.identityRefreshing = false;
497
- this.projection = { id, identity };
498
- this.changed(id, identity);
497
+ this.projection = { id, identity: identity2 };
498
+ this.changed(id, identity2);
499
499
  },
500
500
  () => {
501
501
  if (revision === this.refreshRevision) this.invalidate(id);
@@ -1732,7 +1732,7 @@ var PartyLayerClient = class {
1732
1732
  this.crypto = config.crypto || new DefaultCrypto();
1733
1733
  this.storage = config.storage || new DefaultStorage();
1734
1734
  if (typeof window !== "undefined") {
1735
- this.nativeOwner = new NativeConnectionOwner((id, identity) => this.onNativeIdentityChanged(id, identity));
1735
+ this.nativeOwner = new NativeConnectionOwner((id, identity2) => this.onNativeIdentityChanged(id, identity2));
1736
1736
  }
1737
1737
  const telemetryAdapter = createTelemetryAdapter(config.telemetry);
1738
1738
  this.telemetry = telemetryAdapter || new DefaultTelemetry();
@@ -1810,11 +1810,11 @@ var PartyLayerClient = class {
1810
1810
  nativeOwnerBindings.set(adapter, this.nativeOwner);
1811
1811
  }
1812
1812
  }
1813
- onNativeIdentityChanged(id, identity) {
1813
+ onNativeIdentityChanged(id, identity2) {
1814
1814
  const active = this.activeSession;
1815
1815
  if (this.destroyed || !active || String(active.walletId) !== id) return;
1816
1816
  ++this.sessionRevision;
1817
- if (!identity) {
1817
+ if (!identity2) {
1818
1818
  this.restorationBlocked = true;
1819
1819
  this.warmPlans.clear();
1820
1820
  this.activeSession = null;
@@ -1822,7 +1822,7 @@ var PartyLayerClient = class {
1822
1822
  this.emit("session:disconnected", { type: "session:disconnected", sessionId: active.sessionId });
1823
1823
  return;
1824
1824
  }
1825
- const session = { ...active, partyId: identity.account.partyId, network: identity.network };
1825
+ const session = { ...active, partyId: identity2.account.partyId, network: identity2.network };
1826
1826
  const mismatch = this.networkMismatch(session);
1827
1827
  if (mismatch) session.networkMismatch = mismatch;
1828
1828
  else delete session.networkMismatch;
@@ -3069,7 +3069,210 @@ var PartyLayerClient = class {
3069
3069
  function createPartyLayer(config) {
3070
3070
  return new PartyLayerClient(config);
3071
3071
  }
3072
+ function object(value) {
3073
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Malformed Ledger API response");
3074
+ return value;
3075
+ }
3076
+ function text(value) {
3077
+ if (typeof value !== "string" || !value || value.length > 2048 || /\p{Cc}/u.test(value)) {
3078
+ throw new Error("Invalid Ledger API identifier");
3079
+ }
3080
+ return value;
3081
+ }
3082
+ var identity = (s) => JSON.stringify([s.sessionId, s.walletId, s.partyId, toCAIP2Network(s.network).networkId]);
3083
+ function createWalletLedgerReader(client, options) {
3084
+ return createScopedLedgerReader(client, options);
3085
+ }
3086
+ function createScopedLedgerReader(client, options, applicationRequest) {
3087
+ const networkId = text(options.networkId);
3088
+ if (!/^canton:[a-zA-Z0-9_-]+$/.test(networkId)) throw new Error("Expected a Canton CAIP-2 network id");
3089
+ const interfaceId = options.holdingInterfaceId === void 0 ? void 0 : text(options.holdingInterfaceId);
3090
+ if (interfaceId && !/^[^:#\s]+:[^:\s]+:[^:\s]+$/.test(interfaceId)) throw new Error("Use an exact package-id-qualified holding interface id");
3091
+ const timeoutMs = options.timeoutMs ?? 3e4;
3092
+ const maxContracts = options.maxContracts ?? 1e3;
3093
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 3e5) throw new Error("Invalid ledger read timeout");
3094
+ if (!Number.isInteger(maxContracts) || maxContracts < 1 || maxContracts > 1e4) throw new Error("Invalid snapshot limit");
3095
+ async function read(signal, action) {
3096
+ let timer;
3097
+ let stop;
3098
+ let stopped = false;
3099
+ const controller = new AbortController();
3100
+ const aborted = new Promise((_resolve, reject) => {
3101
+ stop = () => {
3102
+ stopped = true;
3103
+ controller.abort();
3104
+ reject(new Error("Ledger read cancelled or timed out"));
3105
+ };
3106
+ if (signal?.aborted) stop();
3107
+ else signal?.addEventListener("abort", stop, { once: true });
3108
+ timer = setTimeout(stop, timeoutMs);
3109
+ });
3110
+ const run = async () => {
3111
+ const session = await client.getActiveSession();
3112
+ if (stopped) throw new Error("Ledger read cancelled");
3113
+ if (!session || session.networkMismatch || toCAIP2Network(session.network).networkId !== networkId) {
3114
+ throw new Error("Connect a wallet on the expected network before reading the ledger");
3115
+ }
3116
+ if (!applicationRequest && !session.capabilitiesSnapshot.includes("ledgerApi")) throw new Error("This wallet does not expose ledgerApi");
3117
+ const captured = identity(session);
3118
+ const assertCurrent = async () => {
3119
+ const current = await client.getActiveSession();
3120
+ if (stopped || !current || current.networkMismatch || identity(current) !== captured) throw new Error("Wallet session changed during ledger read");
3121
+ };
3122
+ const request = async (resource, body) => {
3123
+ await assertCurrent();
3124
+ let result2 = applicationRequest ? await applicationRequest(session, resource, body, controller.signal) : await client.asProvider().request({ method: "ledgerApi", params: {
3125
+ requestMethod: body ? "post" : "get",
3126
+ resource,
3127
+ ...body ? { body } : {}
3128
+ } });
3129
+ await assertCurrent();
3130
+ if (result2 && typeof result2 === "object" && !Array.isArray(result2) && Object.keys(result2).length === 1 && typeof result2.response === "string") result2 = result2.response;
3131
+ if (typeof result2 === "string") {
3132
+ if (result2.length > 8e6) throw new Error("Ledger response is too large");
3133
+ result2 = JSON.parse(result2);
3134
+ }
3135
+ return result2;
3136
+ };
3137
+ const result = await action(session, request);
3138
+ await assertCurrent();
3139
+ return result;
3140
+ };
3141
+ try {
3142
+ return await Promise.race([run(), aborted]);
3143
+ } finally {
3144
+ if (timer) clearTimeout(timer);
3145
+ if (stop) signal?.removeEventListener("abort", stop);
3146
+ }
3147
+ }
3148
+ return {
3149
+ /** A bounded, complete ACS snapshot of the connected party's configured HoldingV1 interface. */
3150
+ readHoldings(signal) {
3151
+ return read(signal, async (session, request) => {
3152
+ if (!interfaceId) throw new Error("Configure holdingInterfaceId before reading holdings");
3153
+ const end = object(await request("/v2/state/ledger-end"));
3154
+ if (!Number.isSafeInteger(end.offset) || end.offset < 0) throw new Error("Unsafe or invalid ledger offset");
3155
+ const rows = await request("/v2/state/active-contracts", {
3156
+ activeAtOffset: end.offset,
3157
+ eventFormat: { filtersByParty: { [String(session.partyId)]: { cumulative: [{
3158
+ identifierFilter: { InterfaceFilter: { value: { interfaceId, includeInterfaceView: true } } }
3159
+ }] } }, verbose: false }
3160
+ });
3161
+ if (!Array.isArray(rows) || rows.length >= maxContracts) throw new Error("Incomplete or oversized holdings snapshot");
3162
+ const seen = /* @__PURE__ */ new Set();
3163
+ const holdings = rows.map((row) => {
3164
+ const entry = object(object(row).contractEntry);
3165
+ if (Object.keys(entry).length !== 1 || !entry.JsActiveContract) throw new Error("Snapshot contains an incomplete reassignment");
3166
+ const created = object(object(entry.JsActiveContract).createdEvent);
3167
+ const cid = text(created.contractId);
3168
+ if (seen.has(cid)) throw new Error("Duplicate holding contract in snapshot");
3169
+ seen.add(cid);
3170
+ if (!Array.isArray(created.interfaceViews)) throw new Error("Missing holding interface view");
3171
+ const views = created.interfaceViews.filter((v) => object(v).interfaceId === interfaceId);
3172
+ if (views.length !== 1) throw new Error("Missing or ambiguous holding interface view");
3173
+ const view = object(views[0]);
3174
+ if (object(view.viewStatus).code !== 0) throw new Error("Holding interface view failed");
3175
+ const value = object(view.viewValue);
3176
+ if (value.owner !== String(session.partyId)) throw new Error("Holding belongs to another party");
3177
+ const instrument = object(value.instrumentId);
3178
+ if (typeof value.amount !== "string" || !/^(?:0|[1-9]\d{0,27})(?:\.\d{1,10})?$/.test(value.amount)) throw new Error("Invalid token decimal");
3179
+ let lock;
3180
+ if (value.lock !== null && value.lock !== void 0) {
3181
+ const raw = object(value.lock);
3182
+ if (!Array.isArray(raw.holders)) throw new Error("Invalid holding lock");
3183
+ lock = { holders: raw.holders.map(text) };
3184
+ for (const key of ["expiresAt", "expiresAfter", "context"]) {
3185
+ if (raw[key] !== void 0 && raw[key] !== null) lock[key] = text(raw[key]);
3186
+ }
3187
+ }
3188
+ let meta;
3189
+ if (value.meta !== void 0 && value.meta !== null) {
3190
+ const raw = object(value.meta);
3191
+ const values = Object.hasOwn(raw, "values") ? object(raw.values) : raw;
3192
+ if (Object.values(values).some((v) => typeof v !== "string")) throw new Error("Invalid holding metadata");
3193
+ meta = { ...values };
3194
+ }
3195
+ return { cid, holding: {
3196
+ owner: String(session.partyId),
3197
+ instrumentId: { admin: text(instrument.admin), id: text(instrument.id) },
3198
+ amount: value.amount,
3199
+ ...lock ? { lock } : {},
3200
+ ...meta ? { meta } : {}
3201
+ } };
3202
+ });
3203
+ return { walletId: String(session.walletId), partyId: String(session.partyId), networkId, offset: end.offset, holdings };
3204
+ });
3205
+ },
3206
+ /** One read, never polling or resubmission. Unknown remains unknown if ids cannot be correlated. */
3207
+ async confirmTransaction({ transaction, signal }) {
3208
+ const updateId = transaction.receipt?.updateId ?? transaction.updateId;
3209
+ if (!updateId || !transaction.commandId) return { status: "unknown", reason: "An update id and the original app command id are required" };
3210
+ if (transaction.receipt?.commandId && transaction.receipt.commandId !== transaction.commandId) {
3211
+ return { status: "unknown", reason: "Wallet receipt conflicts with the original command id" };
3212
+ }
3213
+ text(updateId);
3214
+ text(transaction.commandId);
3215
+ return read(signal, async (session, request) => {
3216
+ if (transaction.networkId !== networkId || transaction.partyId !== String(session.partyId) || transaction.walletId !== String(session.walletId)) {
3217
+ throw new Error("Transaction does not belong to the connected wallet account and network");
3218
+ }
3219
+ if (transaction.updateId && transaction.updateId !== updateId) throw new Error("Conflicting update ids");
3220
+ const result = object(await request("/v2/updates/update-by-id", {
3221
+ updateId,
3222
+ updateFormat: { includeTransactions: {
3223
+ eventFormat: { filtersByParty: { [String(session.partyId)]: {} }, verbose: false },
3224
+ transactionShape: "TRANSACTION_SHAPE_ACS_DELTA"
3225
+ } }
3226
+ }));
3227
+ const update = object(result.update);
3228
+ if (Object.keys(update).length !== 1 || !update.Transaction) throw new Error("Requested update is not a transaction");
3229
+ const tx = object(object(update.Transaction).value);
3230
+ if (tx.updateId !== updateId || tx.commandId !== transaction.commandId || !Array.isArray(tx.events)) {
3231
+ return { status: "unknown", reason: "Ledger transaction cannot be correlated with the original command" };
3232
+ }
3233
+ return { status: "confirmed", updateId };
3234
+ });
3235
+ }
3236
+ };
3237
+ }
3238
+ function createApplicationLedgerReader(client, options) {
3239
+ if (!/^[\w.:-]{1,100}$/.test(options.sourceId)) throw new Error("Invalid application ledger source id");
3240
+ return createScopedLedgerReader(client, options, async (session, resource, body, signal) => {
3241
+ const browserOrigin = typeof window !== "undefined" ? window.location.origin : void 0;
3242
+ const origin = browserOrigin ?? options.origin;
3243
+ if (!origin || browserOrigin && options.origin && options.origin !== browserOrigin) throw new Error("Application reads require the current application origin");
3244
+ const base = new URL(origin);
3245
+ if (base.origin !== origin || base.protocol !== "https:" && !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname))) throw new Error("Invalid application origin");
3246
+ const url = new URL(options.endpoint, origin);
3247
+ if (url.origin !== origin || url.username || url.password || url.hash) throw new Error("Application ledger endpoint must be same-origin");
3248
+ if (!["/v2/state/ledger-end", "/v2/state/active-contracts", "/v2/updates/update-by-id"].includes(resource)) throw new Error("Unsupported application ledger read");
3249
+ const response = await (options.fetch ?? globalThis.fetch)(url.href, {
3250
+ method: "POST",
3251
+ credentials: "same-origin",
3252
+ cache: "no-store",
3253
+ redirect: "error",
3254
+ headers: { "Content-Type": "application/json", Accept: "application/json" },
3255
+ signal,
3256
+ body: JSON.stringify({
3257
+ version: 1,
3258
+ sourceId: options.sourceId,
3259
+ partyId: String(session.partyId),
3260
+ networkId: toCAIP2Network(session.network).networkId,
3261
+ resource,
3262
+ ...body ? { body } : {}
3263
+ })
3264
+ });
3265
+ if (!response.ok || !/^application\/json\b/i.test(response.headers.get("content-type") ?? "")) throw new Error("Authorized application ledger read is unavailable");
3266
+ const raw = await response.text();
3267
+ if (raw.length > 8e6) throw new Error("Application ledger response is too large");
3268
+ const result = JSON.parse(raw);
3269
+ if (!result || result.version !== 1 || result.sourceId !== options.sourceId || result.partyId !== String(session.partyId) || result.networkId !== options.networkId || result.resource !== resource || result.complete !== true || !Object.hasOwn(result, "value")) {
3270
+ throw new Error("Incomplete or incorrectly scoped application ledger response");
3271
+ }
3272
+ return result.value;
3273
+ });
3274
+ }
3072
3275
 
3073
- export { ANNOUNCED_WALLET_ID_PREFIX, PartyLayerClient as CantonConnectClient, DEFAULT_REGISTRY_URL, GenericAnnounceAdapter, GenericDiscoveryAdapter, MetricsTelemetryAdapter, PartyLayerClient, announcedWalletId, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, getBuiltinAdapters, getDiscoveryCapabilities, isTelemetryConfig };
3276
+ export { ANNOUNCED_WALLET_ID_PREFIX, PartyLayerClient as CantonConnectClient, DEFAULT_REGISTRY_URL, GenericAnnounceAdapter, GenericDiscoveryAdapter, MetricsTelemetryAdapter, PartyLayerClient, announcedWalletId, createApplicationLedgerReader, createPartyLayer as createCantonConnect, createPartyLayer, createTelemetryAdapter, createWalletLedgerReader, getBuiltinAdapters, getDiscoveryCapabilities, isTelemetryConfig };
3074
3277
  //# sourceMappingURL=index.mjs.map
3075
3278
  //# sourceMappingURL=index.mjs.map