@unicitylabs/sphere-sdk 0.2.2 → 0.2.3

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.d.cts CHANGED
@@ -886,7 +886,7 @@ interface PaymentRequest {
886
886
  readonly coinId: string;
887
887
  /** Optional message/memo */
888
888
  readonly message?: string;
889
- /** Recipient nametag (who should pay) */
889
+ /** Where tokens should be sent */
890
890
  readonly recipientNametag?: string;
891
891
  /** Custom metadata */
892
892
  readonly metadata?: Record<string, unknown>;
@@ -913,7 +913,7 @@ interface IncomingPaymentRequest$1 {
913
913
  readonly symbol: string;
914
914
  /** Message from sender */
915
915
  readonly message?: string;
916
- /** Who this request is for (our nametag) */
916
+ /** Requester's nametag (where tokens should be sent) */
917
917
  readonly recipientNametag?: string;
918
918
  /** Original request ID from sender */
919
919
  readonly requestId: string;
@@ -1444,6 +1444,8 @@ interface IncomingPaymentRequest {
1444
1444
  id: string;
1445
1445
  /** Transport-specific pubkey of sender */
1446
1446
  senderTransportPubkey: string;
1447
+ /** Sender's nametag (if included in encrypted content) */
1448
+ senderNametag?: string;
1447
1449
  /** Parsed request data */
1448
1450
  request: {
1449
1451
  requestId: string;
@@ -1610,6 +1612,12 @@ declare class L1PaymentsModule {
1610
1612
  private _transport?;
1611
1613
  constructor(config?: L1PaymentsModuleConfig);
1612
1614
  initialize(deps: L1PaymentsModuleDependencies): Promise<void>;
1615
+ /**
1616
+ * Ensure the Fulcrum WebSocket is connected. Called lazily before any
1617
+ * operation that needs the network. If the singleton is already connected
1618
+ * (e.g. by the address scanner), this is a no-op.
1619
+ */
1620
+ private ensureConnected;
1613
1621
  destroy(): void;
1614
1622
  /**
1615
1623
  * Check if a string looks like an L1 address (alpha1... or alphat1...)
@@ -1619,7 +1627,7 @@ declare class L1PaymentsModule {
1619
1627
  * Resolve recipient to L1 address
1620
1628
  * Supports: L1 address (alpha1...), nametag (with or without @)
1621
1629
  */
1622
- private resolveL1Address;
1630
+ resolveL1Address(recipient: string): Promise<string>;
1623
1631
  /**
1624
1632
  * Resolve nametag to L1 address using transport provider
1625
1633
  */
@@ -2147,8 +2155,8 @@ interface PaymentsModuleConfig {
2147
2155
  maxRetries?: number;
2148
2156
  /** Enable debug logging */
2149
2157
  debug?: boolean;
2150
- /** L1 (ALPHA blockchain) configuration */
2151
- l1?: L1PaymentsModuleConfig;
2158
+ /** L1 (ALPHA blockchain) configuration. Set to null to explicitly disable L1. */
2159
+ l1?: L1PaymentsModuleConfig | null;
2152
2160
  }
2153
2161
  interface PaymentsModuleDependencies {
2154
2162
  identity: FullIdentity;
@@ -2736,6 +2744,8 @@ declare const STORAGE_KEYS: {
2736
2744
  readonly ADDRESS_NAMETAGS: "address_nametags";
2737
2745
  /** Active addresses registry (JSON: TrackedAddressesStorage) */
2738
2746
  readonly TRACKED_ADDRESSES: "tracked_addresses";
2747
+ /** Last processed Nostr wallet event timestamp (unix seconds), keyed per pubkey */
2748
+ readonly LAST_WALLET_EVENT_TS: "last_wallet_event_ts";
2739
2749
  };
2740
2750
  /** Default Nostr relays */
2741
2751
  declare const DEFAULT_NOSTR_RELAYS: readonly ["wss://relay.unicity.network", "wss://relay.damus.io", "wss://nos.lol", "wss://relay.nostr.band"];
@@ -3309,6 +3319,7 @@ declare class Sphere {
3309
3319
  transport: TransportProvider;
3310
3320
  oracle: OracleProvider;
3311
3321
  tokenStorage?: TokenStorageProvider<TxfStorageDataBase>;
3322
+ l1?: L1Config;
3312
3323
  }): Promise<{
3313
3324
  success: boolean;
3314
3325
  mnemonic?: string;
@@ -3363,6 +3374,8 @@ declare class Sphere {
3363
3374
  tokenStorage?: TokenStorageProvider<TxfStorageDataBase>;
3364
3375
  /** Optional nametag to register */
3365
3376
  nametag?: string;
3377
+ /** L1 (ALPHA blockchain) configuration */
3378
+ l1?: L1Config;
3366
3379
  }): Promise<{
3367
3380
  success: boolean;
3368
3381
  sphere?: Sphere;
package/dist/index.d.ts CHANGED
@@ -886,7 +886,7 @@ interface PaymentRequest {
886
886
  readonly coinId: string;
887
887
  /** Optional message/memo */
888
888
  readonly message?: string;
889
- /** Recipient nametag (who should pay) */
889
+ /** Where tokens should be sent */
890
890
  readonly recipientNametag?: string;
891
891
  /** Custom metadata */
892
892
  readonly metadata?: Record<string, unknown>;
@@ -913,7 +913,7 @@ interface IncomingPaymentRequest$1 {
913
913
  readonly symbol: string;
914
914
  /** Message from sender */
915
915
  readonly message?: string;
916
- /** Who this request is for (our nametag) */
916
+ /** Requester's nametag (where tokens should be sent) */
917
917
  readonly recipientNametag?: string;
918
918
  /** Original request ID from sender */
919
919
  readonly requestId: string;
@@ -1444,6 +1444,8 @@ interface IncomingPaymentRequest {
1444
1444
  id: string;
1445
1445
  /** Transport-specific pubkey of sender */
1446
1446
  senderTransportPubkey: string;
1447
+ /** Sender's nametag (if included in encrypted content) */
1448
+ senderNametag?: string;
1447
1449
  /** Parsed request data */
1448
1450
  request: {
1449
1451
  requestId: string;
@@ -1610,6 +1612,12 @@ declare class L1PaymentsModule {
1610
1612
  private _transport?;
1611
1613
  constructor(config?: L1PaymentsModuleConfig);
1612
1614
  initialize(deps: L1PaymentsModuleDependencies): Promise<void>;
1615
+ /**
1616
+ * Ensure the Fulcrum WebSocket is connected. Called lazily before any
1617
+ * operation that needs the network. If the singleton is already connected
1618
+ * (e.g. by the address scanner), this is a no-op.
1619
+ */
1620
+ private ensureConnected;
1613
1621
  destroy(): void;
1614
1622
  /**
1615
1623
  * Check if a string looks like an L1 address (alpha1... or alphat1...)
@@ -1619,7 +1627,7 @@ declare class L1PaymentsModule {
1619
1627
  * Resolve recipient to L1 address
1620
1628
  * Supports: L1 address (alpha1...), nametag (with or without @)
1621
1629
  */
1622
- private resolveL1Address;
1630
+ resolveL1Address(recipient: string): Promise<string>;
1623
1631
  /**
1624
1632
  * Resolve nametag to L1 address using transport provider
1625
1633
  */
@@ -2147,8 +2155,8 @@ interface PaymentsModuleConfig {
2147
2155
  maxRetries?: number;
2148
2156
  /** Enable debug logging */
2149
2157
  debug?: boolean;
2150
- /** L1 (ALPHA blockchain) configuration */
2151
- l1?: L1PaymentsModuleConfig;
2158
+ /** L1 (ALPHA blockchain) configuration. Set to null to explicitly disable L1. */
2159
+ l1?: L1PaymentsModuleConfig | null;
2152
2160
  }
2153
2161
  interface PaymentsModuleDependencies {
2154
2162
  identity: FullIdentity;
@@ -2736,6 +2744,8 @@ declare const STORAGE_KEYS: {
2736
2744
  readonly ADDRESS_NAMETAGS: "address_nametags";
2737
2745
  /** Active addresses registry (JSON: TrackedAddressesStorage) */
2738
2746
  readonly TRACKED_ADDRESSES: "tracked_addresses";
2747
+ /** Last processed Nostr wallet event timestamp (unix seconds), keyed per pubkey */
2748
+ readonly LAST_WALLET_EVENT_TS: "last_wallet_event_ts";
2739
2749
  };
2740
2750
  /** Default Nostr relays */
2741
2751
  declare const DEFAULT_NOSTR_RELAYS: readonly ["wss://relay.unicity.network", "wss://relay.damus.io", "wss://nos.lol", "wss://relay.nostr.band"];
@@ -3309,6 +3319,7 @@ declare class Sphere {
3309
3319
  transport: TransportProvider;
3310
3320
  oracle: OracleProvider;
3311
3321
  tokenStorage?: TokenStorageProvider<TxfStorageDataBase>;
3322
+ l1?: L1Config;
3312
3323
  }): Promise<{
3313
3324
  success: boolean;
3314
3325
  mnemonic?: string;
@@ -3363,6 +3374,8 @@ declare class Sphere {
3363
3374
  tokenStorage?: TokenStorageProvider<TxfStorageDataBase>;
3364
3375
  /** Optional nametag to register */
3365
3376
  nametag?: string;
3377
+ /** L1 (ALPHA blockchain) configuration */
3378
+ l1?: L1Config;
3366
3379
  }): Promise<{
3367
3380
  success: boolean;
3368
3381
  sphere?: Sphere;
package/dist/index.js CHANGED
@@ -1612,7 +1612,7 @@ var L1PaymentsModule = class {
1612
1612
  _transport;
1613
1613
  constructor(config) {
1614
1614
  this._config = {
1615
- electrumUrl: config?.electrumUrl ?? "wss://fulcrum.alpha.unicity.network:50004",
1615
+ electrumUrl: config?.electrumUrl ?? "wss://fulcrum.unicity.network:50004",
1616
1616
  network: config?.network ?? "mainnet",
1617
1617
  defaultFeeRate: config?.defaultFeeRate ?? 10,
1618
1618
  enableVesting: config?.enableVesting ?? true
@@ -1644,10 +1644,17 @@ var L1PaymentsModule = class {
1644
1644
  });
1645
1645
  }
1646
1646
  }
1647
- if (this._config.electrumUrl) {
1647
+ this._initialized = true;
1648
+ }
1649
+ /**
1650
+ * Ensure the Fulcrum WebSocket is connected. Called lazily before any
1651
+ * operation that needs the network. If the singleton is already connected
1652
+ * (e.g. by the address scanner), this is a no-op.
1653
+ */
1654
+ async ensureConnected() {
1655
+ if (!isWebSocketConnected() && this._config.electrumUrl) {
1648
1656
  await connect(this._config.electrumUrl);
1649
1657
  }
1650
- this._initialized = true;
1651
1658
  }
1652
1659
  destroy() {
1653
1660
  if (isWebSocketConnected()) {
@@ -1705,6 +1712,7 @@ var L1PaymentsModule = class {
1705
1712
  }
1706
1713
  async send(request) {
1707
1714
  this.ensureInitialized();
1715
+ await this.ensureConnected();
1708
1716
  if (!this._wallet || !this._identity) {
1709
1717
  return { success: false, error: "No wallet available" };
1710
1718
  }
@@ -1739,6 +1747,7 @@ var L1PaymentsModule = class {
1739
1747
  }
1740
1748
  async getBalance() {
1741
1749
  this.ensureInitialized();
1750
+ await this.ensureConnected();
1742
1751
  const addresses = this._getWatchedAddresses();
1743
1752
  let totalAlpha = 0;
1744
1753
  let vestedSats = BigInt(0);
@@ -1770,6 +1779,7 @@ var L1PaymentsModule = class {
1770
1779
  }
1771
1780
  async getUtxos() {
1772
1781
  this.ensureInitialized();
1782
+ await this.ensureConnected();
1773
1783
  const result = [];
1774
1784
  const currentHeight = await getCurrentBlockHeight();
1775
1785
  const allUtxos = await this._getAllUtxos();
@@ -1805,42 +1815,73 @@ var L1PaymentsModule = class {
1805
1815
  return result;
1806
1816
  }
1807
1817
  async getHistory(limit) {
1818
+ await this.ensureConnected();
1808
1819
  this.ensureInitialized();
1809
1820
  const addresses = this._getWatchedAddresses();
1810
1821
  const transactions = [];
1811
1822
  const seenTxids = /* @__PURE__ */ new Set();
1812
1823
  const currentHeight = await getCurrentBlockHeight();
1824
+ const txCache = /* @__PURE__ */ new Map();
1825
+ const fetchTx = async (txid) => {
1826
+ if (txCache.has(txid)) return txCache.get(txid);
1827
+ const detail = await getTransaction(txid);
1828
+ txCache.set(txid, detail);
1829
+ return detail;
1830
+ };
1831
+ const addressSet = new Set(addresses.map((a) => a.toLowerCase()));
1813
1832
  for (const address of addresses) {
1814
1833
  const history = await getTransactionHistory(address);
1815
1834
  for (const item of history) {
1816
1835
  if (seenTxids.has(item.tx_hash)) continue;
1817
1836
  seenTxids.add(item.tx_hash);
1818
- const tx = await getTransaction(item.tx_hash);
1837
+ const tx = await fetchTx(item.tx_hash);
1819
1838
  if (!tx) continue;
1820
- const isSend = tx.vin?.some(
1821
- (vin) => addresses.includes(vin.txid ?? "")
1822
- );
1823
- let amount = "0";
1839
+ let isSend = false;
1840
+ for (const vin of tx.vin ?? []) {
1841
+ if (!vin.txid) continue;
1842
+ const prevTx = await fetchTx(vin.txid);
1843
+ if (prevTx?.vout?.[vin.vout]) {
1844
+ const prevOut = prevTx.vout[vin.vout];
1845
+ const prevAddrs = [
1846
+ ...prevOut.scriptPubKey?.addresses ?? [],
1847
+ ...prevOut.scriptPubKey?.address ? [prevOut.scriptPubKey.address] : []
1848
+ ];
1849
+ if (prevAddrs.some((a) => addressSet.has(a.toLowerCase()))) {
1850
+ isSend = true;
1851
+ break;
1852
+ }
1853
+ }
1854
+ }
1855
+ let amountToUs = 0;
1856
+ let amountToOthers = 0;
1824
1857
  let txAddress = address;
1858
+ let externalAddress = "";
1825
1859
  if (tx.vout) {
1826
1860
  for (const vout of tx.vout) {
1827
- const voutAddresses = vout.scriptPubKey?.addresses ?? [];
1828
- if (vout.scriptPubKey?.address) {
1829
- voutAddresses.push(vout.scriptPubKey.address);
1830
- }
1831
- const matchedAddr = voutAddresses.find((a) => addresses.includes(a));
1832
- if (matchedAddr) {
1833
- amount = Math.floor((vout.value ?? 0) * 1e8).toString();
1834
- txAddress = matchedAddr;
1835
- break;
1861
+ const voutAddresses = [
1862
+ ...vout.scriptPubKey?.addresses ?? [],
1863
+ ...vout.scriptPubKey?.address ? [vout.scriptPubKey.address] : []
1864
+ ];
1865
+ const isOurs = voutAddresses.some((a) => addressSet.has(a.toLowerCase()));
1866
+ const valueSats = Math.floor((vout.value ?? 0) * 1e8);
1867
+ if (isOurs) {
1868
+ amountToUs += valueSats;
1869
+ if (!txAddress) txAddress = voutAddresses[0];
1870
+ } else {
1871
+ amountToOthers += valueSats;
1872
+ if (!externalAddress && voutAddresses.length > 0) {
1873
+ externalAddress = voutAddresses[0];
1874
+ }
1836
1875
  }
1837
1876
  }
1838
1877
  }
1878
+ const amount = isSend ? amountToOthers.toString() : amountToUs.toString();
1879
+ const displayAddress = isSend ? externalAddress || txAddress : txAddress;
1839
1880
  transactions.push({
1840
1881
  txid: item.tx_hash,
1841
1882
  type: isSend ? "send" : "receive",
1842
1883
  amount,
1843
- address: txAddress,
1884
+ address: displayAddress,
1844
1885
  confirmations: item.height > 0 ? currentHeight - item.height : 0,
1845
1886
  timestamp: tx.time ? tx.time * 1e3 : Date.now(),
1846
1887
  blockHeight: item.height > 0 ? item.height : void 0
@@ -1852,6 +1893,7 @@ var L1PaymentsModule = class {
1852
1893
  }
1853
1894
  async getTransaction(txid) {
1854
1895
  this.ensureInitialized();
1896
+ await this.ensureConnected();
1855
1897
  const tx = await getTransaction(txid);
1856
1898
  if (!tx) return null;
1857
1899
  const addresses = this._getWatchedAddresses();
@@ -1887,6 +1929,7 @@ var L1PaymentsModule = class {
1887
1929
  }
1888
1930
  async estimateFee(to, amount) {
1889
1931
  this.ensureInitialized();
1932
+ await this.ensureConnected();
1890
1933
  if (!this._wallet) {
1891
1934
  return { fee: "0", feeRate: this._config.defaultFeeRate ?? 10 };
1892
1935
  }
@@ -2410,7 +2453,9 @@ var STORAGE_KEYS_GLOBAL = {
2410
2453
  /** Nametag cache per address (separate from tracked addresses registry) */
2411
2454
  ADDRESS_NAMETAGS: "address_nametags",
2412
2455
  /** Active addresses registry (JSON: TrackedAddressesStorage) */
2413
- TRACKED_ADDRESSES: "tracked_addresses"
2456
+ TRACKED_ADDRESSES: "tracked_addresses",
2457
+ /** Last processed Nostr wallet event timestamp (unix seconds), keyed per pubkey */
2458
+ LAST_WALLET_EVENT_TS: "last_wallet_event_ts"
2414
2459
  };
2415
2460
  var STORAGE_KEYS_ADDRESS = {
2416
2461
  /** Pending transfers for this address */
@@ -3983,7 +4028,7 @@ async function parseTokenInfo(tokenData) {
3983
4028
  try {
3984
4029
  const sdkToken = await SdkToken2.fromJSON(data);
3985
4030
  if (sdkToken.id) {
3986
- defaultInfo.tokenId = sdkToken.id.toString();
4031
+ defaultInfo.tokenId = sdkToken.id.toJSON();
3987
4032
  }
3988
4033
  if (sdkToken.coins && sdkToken.coins.coins) {
3989
4034
  const rawCoins = sdkToken.coins.coins;
@@ -4274,8 +4319,7 @@ var PaymentsModule = class _PaymentsModule {
4274
4319
  maxRetries: config?.maxRetries ?? 3,
4275
4320
  debug: config?.debug ?? false
4276
4321
  };
4277
- const l1Enabled = config?.l1?.electrumUrl && config.l1.electrumUrl.length > 0;
4278
- this.l1 = l1Enabled ? new L1PaymentsModule(config?.l1) : null;
4322
+ this.l1 = config?.l1 === null ? null : new L1PaymentsModule(config?.l1);
4279
4323
  }
4280
4324
  /** Get module configuration */
4281
4325
  getConfig() {
@@ -4937,13 +4981,16 @@ var PaymentsModule = class _PaymentsModule {
4937
4981
  if (this.paymentRequests.find((r) => r.id === transportRequest.id)) {
4938
4982
  return;
4939
4983
  }
4984
+ const coinId = transportRequest.request.coinId;
4985
+ const registry = TokenRegistry.getInstance();
4986
+ const coinDef = registry.getDefinition(coinId);
4940
4987
  const request = {
4941
4988
  id: transportRequest.id,
4942
4989
  senderPubkey: transportRequest.senderTransportPubkey,
4990
+ senderNametag: transportRequest.senderNametag,
4943
4991
  amount: transportRequest.request.amount,
4944
- coinId: transportRequest.request.coinId,
4945
- symbol: transportRequest.request.coinId,
4946
- // Use coinId as symbol for now
4992
+ coinId,
4993
+ symbol: coinDef?.symbol || coinId.slice(0, 8),
4947
4994
  message: transportRequest.request.message,
4948
4995
  recipientNametag: transportRequest.request.recipientNametag,
4949
4996
  requestId: transportRequest.request.requestId,
@@ -7877,8 +7924,8 @@ var Sphere = class _Sphere {
7877
7924
  if (options.nametag) {
7878
7925
  await sphere.registerNametag(options.nametag);
7879
7926
  } else {
7880
- await sphere.syncIdentityWithTransport();
7881
7927
  await sphere.recoverNametagFromTransport();
7928
+ await sphere.syncIdentityWithTransport();
7882
7929
  }
7883
7930
  return sphere;
7884
7931
  }
@@ -7925,9 +7972,14 @@ var Sphere = class _Sphere {
7925
7972
  if (!options.mnemonic && !options.masterKey) {
7926
7973
  throw new Error("Either mnemonic or masterKey is required");
7927
7974
  }
7975
+ console.log("[Sphere.import] Starting import...");
7976
+ console.log("[Sphere.import] Clearing existing wallet data...");
7928
7977
  await _Sphere.clear({ storage: options.storage, tokenStorage: options.tokenStorage });
7978
+ console.log("[Sphere.import] Clear done");
7929
7979
  if (!options.storage.isConnected()) {
7980
+ console.log("[Sphere.import] Reconnecting storage...");
7930
7981
  await options.storage.connect();
7982
+ console.log("[Sphere.import] Storage reconnected");
7931
7983
  }
7932
7984
  const sphere = new _Sphere(
7933
7985
  options.storage,
@@ -7941,9 +7993,12 @@ var Sphere = class _Sphere {
7941
7993
  if (!_Sphere.validateMnemonic(options.mnemonic)) {
7942
7994
  throw new Error("Invalid mnemonic");
7943
7995
  }
7996
+ console.log("[Sphere.import] Storing mnemonic...");
7944
7997
  await sphere.storeMnemonic(options.mnemonic, options.derivationPath, options.basePath);
7998
+ console.log("[Sphere.import] Initializing identity from mnemonic...");
7945
7999
  await sphere.initializeIdentityFromMnemonic(options.mnemonic, options.derivationPath);
7946
8000
  } else if (options.masterKey) {
8001
+ console.log("[Sphere.import] Storing master key...");
7947
8002
  await sphere.storeMasterKey(
7948
8003
  options.masterKey,
7949
8004
  options.chainCode,
@@ -7951,24 +8006,35 @@ var Sphere = class _Sphere {
7951
8006
  options.basePath,
7952
8007
  options.derivationMode
7953
8008
  );
8009
+ console.log("[Sphere.import] Initializing identity from master key...");
7954
8010
  await sphere.initializeIdentityFromMasterKey(
7955
8011
  options.masterKey,
7956
8012
  options.chainCode,
7957
8013
  options.derivationPath
7958
8014
  );
7959
8015
  }
8016
+ console.log("[Sphere.import] Initializing providers...");
7960
8017
  await sphere.initializeProviders();
8018
+ console.log("[Sphere.import] Providers initialized. Initializing modules...");
7961
8019
  await sphere.initializeModules();
8020
+ console.log("[Sphere.import] Modules initialized");
7962
8021
  if (!options.nametag) {
8022
+ console.log("[Sphere.import] Recovering nametag from transport...");
7963
8023
  await sphere.recoverNametagFromTransport();
8024
+ console.log("[Sphere.import] Nametag recovery done");
8025
+ await sphere.syncIdentityWithTransport();
7964
8026
  }
8027
+ console.log("[Sphere.import] Finalizing wallet creation...");
7965
8028
  await sphere.finalizeWalletCreation();
7966
8029
  sphere._initialized = true;
7967
8030
  _Sphere.instance = sphere;
8031
+ console.log("[Sphere.import] Tracking address 0...");
7968
8032
  await sphere.ensureAddressTracked(0);
7969
8033
  if (options.nametag) {
8034
+ console.log("[Sphere.import] Registering nametag...");
7970
8035
  await sphere.registerNametag(options.nametag);
7971
8036
  }
8037
+ console.log("[Sphere.import] Import complete");
7972
8038
  return sphere;
7973
8039
  }
7974
8040
  /**
@@ -7993,6 +8059,10 @@ var Sphere = class _Sphere {
7993
8059
  static async clear(storageOrOptions) {
7994
8060
  const storage = "get" in storageOrOptions ? storageOrOptions : storageOrOptions.storage;
7995
8061
  const tokenStorage = "get" in storageOrOptions ? void 0 : storageOrOptions.tokenStorage;
8062
+ if (!storage.isConnected()) {
8063
+ await storage.connect();
8064
+ }
8065
+ console.log("[Sphere.clear] Removing storage keys...");
7996
8066
  await storage.remove(STORAGE_KEYS_GLOBAL.MNEMONIC);
7997
8067
  await storage.remove(STORAGE_KEYS_GLOBAL.MASTER_KEY);
7998
8068
  await storage.remove(STORAGE_KEYS_GLOBAL.CHAIN_CODE);
@@ -8005,12 +8075,30 @@ var Sphere = class _Sphere {
8005
8075
  await storage.remove(STORAGE_KEYS_GLOBAL.ADDRESS_NAMETAGS);
8006
8076
  await storage.remove(STORAGE_KEYS_ADDRESS.PENDING_TRANSFERS);
8007
8077
  await storage.remove(STORAGE_KEYS_ADDRESS.OUTBOX);
8078
+ console.log("[Sphere.clear] Storage keys removed");
8008
8079
  if (tokenStorage?.clear) {
8009
- await tokenStorage.clear();
8080
+ console.log("[Sphere.clear] Clearing token storage...");
8081
+ try {
8082
+ await Promise.race([
8083
+ tokenStorage.clear(),
8084
+ new Promise(
8085
+ (_, reject) => setTimeout(() => reject(new Error("tokenStorage.clear() timed out after 2s")), 2e3)
8086
+ )
8087
+ ]);
8088
+ console.log("[Sphere.clear] Token storage cleared");
8089
+ } catch (err) {
8090
+ console.warn("[Sphere.clear] Token storage clear failed/timed out:", err);
8091
+ }
8010
8092
  }
8093
+ console.log("[Sphere.clear] Destroying vesting classifier...");
8011
8094
  await vestingClassifier.destroy();
8095
+ console.log("[Sphere.clear] Vesting classifier destroyed");
8012
8096
  if (_Sphere.instance) {
8097
+ console.log("[Sphere.clear] Destroying Sphere instance...");
8013
8098
  await _Sphere.instance.destroy();
8099
+ console.log("[Sphere.clear] Sphere instance destroyed");
8100
+ } else {
8101
+ console.log("[Sphere.clear] No Sphere instance to destroy");
8014
8102
  }
8015
8103
  }
8016
8104
  /**
@@ -8391,7 +8479,8 @@ var Sphere = class _Sphere {
8391
8479
  storage: options.storage,
8392
8480
  transport: options.transport,
8393
8481
  oracle: options.oracle,
8394
- tokenStorage: options.tokenStorage
8482
+ tokenStorage: options.tokenStorage,
8483
+ l1: options.l1
8395
8484
  });
8396
8485
  return { success: true, mnemonic };
8397
8486
  }
@@ -8404,7 +8493,8 @@ var Sphere = class _Sphere {
8404
8493
  storage: options.storage,
8405
8494
  transport: options.transport,
8406
8495
  oracle: options.oracle,
8407
- tokenStorage: options.tokenStorage
8496
+ tokenStorage: options.tokenStorage,
8497
+ l1: options.l1
8408
8498
  });
8409
8499
  return { success: true };
8410
8500
  }
@@ -8463,7 +8553,8 @@ var Sphere = class _Sphere {
8463
8553
  transport: options.transport,
8464
8554
  oracle: options.oracle,
8465
8555
  tokenStorage: options.tokenStorage,
8466
- nametag: options.nametag
8556
+ nametag: options.nametag,
8557
+ l1: options.l1
8467
8558
  });
8468
8559
  return { success: true, sphere, mnemonic };
8469
8560
  }
@@ -8492,7 +8583,8 @@ var Sphere = class _Sphere {
8492
8583
  transport: options.transport,
8493
8584
  oracle: options.oracle,
8494
8585
  tokenStorage: options.tokenStorage,
8495
- nametag: options.nametag
8586
+ nametag: options.nametag,
8587
+ l1: options.l1
8496
8588
  });
8497
8589
  return { success: true, sphere };
8498
8590
  }
@@ -8523,7 +8615,8 @@ var Sphere = class _Sphere {
8523
8615
  transport: options.transport,
8524
8616
  oracle: options.oracle,
8525
8617
  tokenStorage: options.tokenStorage,
8526
- nametag: options.nametag
8618
+ nametag: options.nametag,
8619
+ l1: options.l1
8527
8620
  });
8528
8621
  return { success: true, sphere };
8529
8622
  }
@@ -8542,7 +8635,8 @@ var Sphere = class _Sphere {
8542
8635
  storage: options.storage,
8543
8636
  transport: options.transport,
8544
8637
  oracle: options.oracle,
8545
- tokenStorage: options.tokenStorage
8638
+ tokenStorage: options.tokenStorage,
8639
+ l1: options.l1
8546
8640
  });
8547
8641
  if (result.success) {
8548
8642
  const sphere2 = _Sphere.getInstance();
@@ -8591,7 +8685,8 @@ var Sphere = class _Sphere {
8591
8685
  transport: options.transport,
8592
8686
  oracle: options.oracle,
8593
8687
  tokenStorage: options.tokenStorage,
8594
- nametag: options.nametag
8688
+ nametag: options.nametag,
8689
+ l1: options.l1
8595
8690
  });
8596
8691
  return { success: true, sphere: sphere2, mnemonic };
8597
8692
  }
@@ -8604,7 +8699,8 @@ var Sphere = class _Sphere {
8604
8699
  transport: options.transport,
8605
8700
  oracle: options.oracle,
8606
8701
  tokenStorage: options.tokenStorage,
8607
- nametag: options.nametag
8702
+ nametag: options.nametag,
8703
+ l1: options.l1
8608
8704
  });
8609
8705
  return { success: true, sphere };
8610
8706
  }
@@ -9467,35 +9563,40 @@ var Sphere = class _Sphere {
9467
9563
  if (this._identity?.nametag) {
9468
9564
  return;
9469
9565
  }
9470
- if (!this._transport.recoverNametag) {
9566
+ let recoveredNametag = null;
9567
+ if (this._transport.recoverNametag) {
9568
+ try {
9569
+ recoveredNametag = await this._transport.recoverNametag();
9570
+ } catch {
9571
+ }
9572
+ }
9573
+ if (!recoveredNametag && this._transport.resolveAddressInfo && this._identity?.l1Address) {
9574
+ try {
9575
+ const info = await this._transport.resolveAddressInfo(this._identity.l1Address);
9576
+ if (info?.nametag) {
9577
+ recoveredNametag = info.nametag;
9578
+ }
9579
+ } catch {
9580
+ }
9581
+ }
9582
+ if (!recoveredNametag) {
9471
9583
  return;
9472
9584
  }
9473
9585
  try {
9474
- const recoveredNametag = await this._transport.recoverNametag();
9475
- if (recoveredNametag) {
9476
- if (this._identity) {
9477
- this._identity.nametag = recoveredNametag;
9478
- await this._updateCachedProxyAddress();
9479
- }
9480
- const entry = await this.ensureAddressTracked(this._currentAddressIndex);
9481
- let nametags = this._addressNametags.get(entry.addressId);
9482
- if (!nametags) {
9483
- nametags = /* @__PURE__ */ new Map();
9484
- this._addressNametags.set(entry.addressId, nametags);
9485
- }
9486
- const nextIndex = nametags.size;
9487
- nametags.set(nextIndex, recoveredNametag);
9488
- await this.persistAddressNametags();
9489
- if (this._transport.publishIdentityBinding) {
9490
- await this._transport.publishIdentityBinding(
9491
- this._identity.chainPubkey,
9492
- this._identity.l1Address,
9493
- this._identity.directAddress || "",
9494
- recoveredNametag
9495
- );
9496
- }
9497
- this.emitEvent("nametag:recovered", { nametag: recoveredNametag });
9586
+ if (this._identity) {
9587
+ this._identity.nametag = recoveredNametag;
9588
+ await this._updateCachedProxyAddress();
9498
9589
  }
9590
+ const entry = await this.ensureAddressTracked(this._currentAddressIndex);
9591
+ let nametags = this._addressNametags.get(entry.addressId);
9592
+ if (!nametags) {
9593
+ nametags = /* @__PURE__ */ new Map();
9594
+ this._addressNametags.set(entry.addressId, nametags);
9595
+ }
9596
+ const nextIndex = nametags.size;
9597
+ nametags.set(nextIndex, recoveredNametag);
9598
+ await this.persistAddressNametags();
9599
+ this.emitEvent("nametag:recovered", { nametag: recoveredNametag });
9499
9600
  } catch {
9500
9601
  }
9501
9602
  }
@@ -9704,8 +9805,12 @@ var Sphere = class _Sphere {
9704
9805
  for (const provider of this._tokenStorageProviders.values()) {
9705
9806
  provider.setIdentity(this._identity);
9706
9807
  }
9707
- await this._storage.connect();
9708
- await this._transport.connect();
9808
+ if (!this._storage.isConnected()) {
9809
+ await this._storage.connect();
9810
+ }
9811
+ if (!this._transport.isConnected()) {
9812
+ await this._transport.connect();
9813
+ }
9709
9814
  await this._oracle.initialize();
9710
9815
  for (const provider of this._tokenStorageProviders.values()) {
9711
9816
  await provider.initialize();