@unicitylabs/sphere-sdk 0.13.2-dev.1 → 0.13.2-dev.2

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.
@@ -10089,8 +10089,7 @@ var PaymentsModule = class _PaymentsModule {
10089
10089
  incrementalHistoryPulls = 0;
10090
10090
  hydrationEpoch = 0;
10091
10091
  // Storage event subscriptions (push-based sync)
10092
- storageEventUnsubscribers = [];
10093
- syncDebounceTimer = null;
10092
+ inventoryDebounceTimer = null;
10094
10093
  static SYNC_DEBOUNCE_MS = 500;
10095
10094
  /** Quiet-then-escalate logging for the background wallet-api pumps (#630). */
10096
10095
  pumpHealth = new PumpHealth();
@@ -10215,7 +10214,6 @@ var PaymentsModule = class _PaymentsModule {
10215
10214
  assertLegalCustodyComposition(deps);
10216
10215
  this.teardownDeliveryPump();
10217
10216
  this.teardownPaymentRequestPump();
10218
- this.unsubscribeStorageEvents();
10219
10217
  for (const [, resolver] of this.pendingResponseResolvers) {
10220
10218
  clearTimeout(resolver.timeout);
10221
10219
  resolver.reject(new Error("Address switched"));
@@ -10284,7 +10282,6 @@ var PaymentsModule = class _PaymentsModule {
10284
10282
  this.pumpHealth.run("payment-requests", () => this.pumpPaymentRequests());
10285
10283
  }, DELIVERY_POLL_INTERVAL_MS);
10286
10284
  }
10287
- this.subscribeToStorageEvents();
10288
10285
  }
10289
10286
  /**
10290
10287
  * Load all token data from storage providers and restore wallet state.
@@ -10457,7 +10454,6 @@ var PaymentsModule = class _PaymentsModule {
10457
10454
  this.reservationLedger.clear();
10458
10455
  this.parsedTokenCache.clear();
10459
10456
  this.tokens.clear();
10460
- this.unsubscribeStorageEvents();
10461
10457
  }
10462
10458
  // ===========================================================================
10463
10459
  // Public API - Send
@@ -12451,115 +12447,29 @@ var PaymentsModule = class _PaymentsModule {
12451
12447
  // Public API - Sync & Validate
12452
12448
  // ===========================================================================
12453
12449
  /**
12454
- * Sync local token state with all configured token storage providers (IPFS, file, etc.).
12450
+ * Flush local token state to every configured token storage provider.
12455
12451
  *
12456
- * For each provider, the local data is packaged into TXF storage format, sent
12457
- * to the provider's `sync()` method, and the merged result is applied locally.
12458
- * Emits `sync:started`, `sync:completed`, and `sync:error` events.
12459
- *
12460
- * @returns Summary with counts of tokens added and removed during sync.
12452
+ * Named `sync` for history: it once merged remote TXF state back in, which
12453
+ * only IPFS ever supplied. The remaining providers all implement `sync()` as
12454
+ * "save and return the input unchanged", so this is a write, and the returned
12455
+ * counts are always zero.
12461
12456
  */
12462
12457
  async sync() {
12463
12458
  this.ensureInitialized();
12464
- if (this._syncInProgress) {
12465
- return this._syncInProgress;
12466
- }
12467
- this._syncInProgress = this._doSync();
12459
+ if (this._syncInProgress) return this._syncInProgress;
12460
+ this._syncInProgress = this._doFlush();
12468
12461
  try {
12469
12462
  return await this._syncInProgress;
12470
12463
  } finally {
12471
12464
  this._syncInProgress = null;
12472
12465
  }
12473
12466
  }
12474
- async _doSync() {
12467
+ async _doFlush() {
12475
12468
  this.deps.emitEvent("sync:started", { source: "payments" });
12476
12469
  try {
12477
- const providers = this.getTokenStorageProviders();
12478
- if (providers.size === 0) {
12479
- await this.save();
12480
- this.deps.emitEvent("sync:completed", {
12481
- source: "payments",
12482
- count: this.tokens.size
12483
- });
12484
- return { added: 0, removed: 0 };
12485
- }
12486
- const localData = await this.createStorageData();
12487
- let totalAdded = 0;
12488
- let totalRemoved = 0;
12489
- const savedNametags = [...this.nametags];
12490
- for (const [providerId, provider] of providers) {
12491
- try {
12492
- const result = await provider.sync(localData);
12493
- if (result.success && result.merged) {
12494
- const mergedMeta = result.merged?._meta;
12495
- const currentChain = this.deps.identity.chainPubkey;
12496
- const isLegacyAlpha = mergedMeta?.address?.startsWith("alpha1") ?? false;
12497
- if (mergedMeta?.address && currentChain && !isLegacyAlpha && mergedMeta.address !== currentChain) {
12498
- logger.warn("Payments", `Sync: rejecting data from provider ${providerId} \u2014 address mismatch (got=${mergedMeta.address.slice(0, 20)}... expected=${currentChain.slice(0, 20)}...)`);
12499
- continue;
12500
- }
12501
- const savedTokens = new Map(this.tokens);
12502
- this.loadFromStorageData(result.merged);
12503
- const existingGenesisIds = /* @__PURE__ */ new Set();
12504
- for (const existing of this.tokens.values()) {
12505
- const gid = extractTokenIdFromSdkData(existing.sdkData);
12506
- if (gid) existingGenesisIds.add(gid);
12507
- }
12508
- let restoredCount = 0;
12509
- for (const [tokenId, token] of savedTokens) {
12510
- if (this.tokens.has(tokenId)) continue;
12511
- const sdkTokenId = extractTokenIdFromSdkData(token.sdkData);
12512
- const stateHash = extractStateHashFromSdkData(token.sdkData);
12513
- if (sdkTokenId && stateHash && this.isStateTombstoned(sdkTokenId, stateHash)) {
12514
- continue;
12515
- }
12516
- if (sdkTokenId && existingGenesisIds.has(sdkTokenId)) {
12517
- continue;
12518
- }
12519
- this.tokens.set(tokenId, token);
12520
- if (sdkTokenId) existingGenesisIds.add(sdkTokenId);
12521
- restoredCount++;
12522
- }
12523
- if (restoredCount > 0) {
12524
- logger.debug("Payments", `Sync: restored ${restoredCount} token(s) lost by loadFromStorageData`);
12525
- }
12526
- if (this.nametags.length === 0 && savedNametags.length > 0) {
12527
- this.nametags = savedNametags;
12528
- }
12529
- await this.rebuildParsedTokenCache();
12530
- const txfData = result.merged;
12531
- if (txfData._history && txfData._history.length > 0) {
12532
- const imported = await this.importRemoteHistoryEntries(txfData._history);
12533
- if (imported > 0) {
12534
- logger.debug("Payments", `Imported ${imported} history entries from IPFS sync`);
12535
- }
12536
- }
12537
- totalAdded += result.added;
12538
- totalRemoved += result.removed;
12539
- }
12540
- this.deps.emitEvent("sync:provider", {
12541
- providerId,
12542
- success: result.success,
12543
- added: result.added,
12544
- removed: result.removed
12545
- });
12546
- } catch (providerError) {
12547
- logger.warn("Payments", `Sync failed for provider ${providerId}:`, providerError);
12548
- this.deps.emitEvent("sync:provider", {
12549
- providerId,
12550
- success: false,
12551
- error: providerError instanceof Error ? providerError.message : String(providerError)
12552
- });
12553
- }
12554
- }
12555
- if (totalAdded > 0 || totalRemoved > 0) {
12556
- await this.save();
12557
- }
12558
- this.deps.emitEvent("sync:completed", {
12559
- source: "payments",
12560
- count: this.tokens.size
12561
- });
12562
- return { added: totalAdded, removed: totalRemoved };
12470
+ await this.save();
12471
+ this.deps.emitEvent("sync:completed", { source: "payments", count: this.tokens.size });
12472
+ return { added: 0, removed: 0 };
12563
12473
  } catch (error) {
12564
12474
  this.deps.emitEvent("sync:error", {
12565
12475
  source: "payments",
@@ -12568,66 +12478,6 @@ var PaymentsModule = class _PaymentsModule {
12568
12478
  throw error;
12569
12479
  }
12570
12480
  }
12571
- // ===========================================================================
12572
- // Storage Event Subscription (Push-Based Sync)
12573
- // ===========================================================================
12574
- /**
12575
- * Subscribe to 'storage:remote-updated' events from all token storage providers.
12576
- * When a provider emits this event, a debounced sync is triggered.
12577
- */
12578
- subscribeToStorageEvents() {
12579
- this.unsubscribeStorageEvents();
12580
- const providers = this.getTokenStorageProviders();
12581
- for (const [providerId, provider] of providers) {
12582
- if (provider.onEvent) {
12583
- const unsub = provider.onEvent((event) => {
12584
- if (event.type === "storage:remote-updated") {
12585
- logger.debug("Payments", "Remote update detected from provider", providerId, event.data);
12586
- this.debouncedSyncFromRemoteUpdate(providerId, event.data);
12587
- }
12588
- });
12589
- this.storageEventUnsubscribers.push(unsub);
12590
- }
12591
- }
12592
- }
12593
- /**
12594
- * Unsubscribe from all storage provider events and clear debounce timer.
12595
- */
12596
- unsubscribeStorageEvents() {
12597
- for (const unsub of this.storageEventUnsubscribers) {
12598
- unsub();
12599
- }
12600
- this.storageEventUnsubscribers = [];
12601
- if (this.syncDebounceTimer) {
12602
- clearTimeout(this.syncDebounceTimer);
12603
- this.syncDebounceTimer = null;
12604
- }
12605
- }
12606
- /**
12607
- * Debounced sync triggered by a storage:remote-updated event.
12608
- * Waits 500ms to batch rapid updates, then performs sync.
12609
- */
12610
- debouncedSyncFromRemoteUpdate(providerId, eventData) {
12611
- if (this.syncDebounceTimer) {
12612
- clearTimeout(this.syncDebounceTimer);
12613
- }
12614
- this.syncDebounceTimer = setTimeout(() => {
12615
- this.syncDebounceTimer = null;
12616
- this.sync().then((result) => {
12617
- const data = eventData;
12618
- this.deps?.emitEvent("sync:remote-update", {
12619
- providerId,
12620
- name: data?.name ?? "",
12621
- sequence: data?.sequence ?? 0,
12622
- cid: data?.cid ?? "",
12623
- added: result.added,
12624
- removed: result.removed
12625
- });
12626
- }).catch((err) => {
12627
- logger.debug("Payments", "Auto-sync from remote update failed:", err);
12628
- });
12629
- }, _PaymentsModule.SYNC_DEBOUNCE_MS);
12630
- }
12631
12481
  /**
12632
12482
  * Get all active (non-disabled) token storage providers
12633
12483
  */
@@ -12672,7 +12522,6 @@ var PaymentsModule = class _PaymentsModule {
12672
12522
  updateTokenStorageProviders(providers) {
12673
12523
  if (this.deps) {
12674
12524
  this.deps.tokenStorageProviders = providers;
12675
- this.subscribeToStorageEvents();
12676
12525
  }
12677
12526
  }
12678
12527
  /**
@@ -12834,6 +12683,10 @@ var PaymentsModule = class _PaymentsModule {
12834
12683
  teardownDeliveryPump() {
12835
12684
  this.deliveryWakeUnsub?.();
12836
12685
  this.deliveryWakeUnsub = null;
12686
+ if (this.inventoryDebounceTimer !== null) {
12687
+ clearTimeout(this.inventoryDebounceTimer);
12688
+ this.inventoryDebounceTimer = null;
12689
+ }
12837
12690
  if (this.deliveryPollTimer !== null) {
12838
12691
  clearInterval(this.deliveryPollTimer);
12839
12692
  this.deliveryPollTimer = null;
@@ -12873,11 +12726,11 @@ var PaymentsModule = class _PaymentsModule {
12873
12726
  * without waiting for the next poll tick.
12874
12727
  */
12875
12728
  debouncedInventorySyncFromWake() {
12876
- if (this.syncDebounceTimer) {
12877
- clearTimeout(this.syncDebounceTimer);
12729
+ if (this.inventoryDebounceTimer) {
12730
+ clearTimeout(this.inventoryDebounceTimer);
12878
12731
  }
12879
- this.syncDebounceTimer = setTimeout(() => {
12880
- this.syncDebounceTimer = null;
12732
+ this.inventoryDebounceTimer = setTimeout(() => {
12733
+ this.inventoryDebounceTimer = null;
12881
12734
  this.pumpHealth.run("inventory", () => this.resyncInventory(true));
12882
12735
  }, _PaymentsModule.SYNC_DEBOUNCE_MS);
12883
12736
  }
@@ -29021,16 +28874,6 @@ var Sphere = class _Sphere {
29021
28874
  });
29022
28875
  if (unsub) this._providerEventCleanups.push(unsub);
29023
28876
  }
29024
- for (const [providerId, provider] of this._tokenStorageProviders) {
29025
- if (typeof provider.onEvent === "function") {
29026
- const unsub = provider.onEvent((event) => {
29027
- if (event.type === "storage:error" || event.type === "sync:error") {
29028
- this.emitConnectionChanged(providerId, provider.isConnected(), provider.getStatus(), event.error);
29029
- }
29030
- });
29031
- if (unsub) this._providerEventCleanups.push(unsub);
29032
- }
29033
- }
29034
28877
  }
29035
28878
  /**
29036
28879
  * Emit connection:changed with deduplication — only emits if status actually changed.