@unicitylabs/sphere-sdk 0.3.4 → 0.3.6

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.
@@ -86,7 +86,11 @@ var STORAGE_KEYS_GLOBAL = {
86
86
  /** Group chat: processed event IDs for deduplication */
87
87
  GROUP_CHAT_PROCESSED_EVENTS: "group_chat_processed_events",
88
88
  /** Group chat: last used relay URL (stale data detection) */
89
- GROUP_CHAT_RELAY_URL: "group_chat_relay_url"
89
+ GROUP_CHAT_RELAY_URL: "group_chat_relay_url",
90
+ /** Cached token registry JSON (fetched from remote) */
91
+ TOKEN_REGISTRY_CACHE: "token_registry_cache",
92
+ /** Timestamp of last token registry cache update (ms since epoch) */
93
+ TOKEN_REGISTRY_CACHE_TS: "token_registry_cache_ts"
90
94
  };
91
95
  var STORAGE_KEYS_ADDRESS = {
92
96
  /** Pending transfers for this address */
@@ -162,6 +166,8 @@ var DEFAULT_BASE_PATH = "m/44'/0'/0'";
162
166
  var DEFAULT_DERIVATION_PATH = `${DEFAULT_BASE_PATH}/0/0`;
163
167
  var DEFAULT_ELECTRUM_URL = "wss://fulcrum.alpha.unicity.network:50004";
164
168
  var TEST_ELECTRUM_URL = "wss://fulcrum.alpha.testnet.unicity.network:50004";
169
+ var TOKEN_REGISTRY_URL = "https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/unicity-ids.testnet.json";
170
+ var TOKEN_REGISTRY_REFRESH_INTERVAL = 36e5;
165
171
  var TEST_NOSTR_RELAYS = [
166
172
  "wss://nostr-relay.testnet.unicity.network"
167
173
  ];
@@ -175,7 +181,8 @@ var NETWORKS = {
175
181
  nostrRelays: DEFAULT_NOSTR_RELAYS,
176
182
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
177
183
  electrumUrl: DEFAULT_ELECTRUM_URL,
178
- groupRelays: DEFAULT_GROUP_RELAYS
184
+ groupRelays: DEFAULT_GROUP_RELAYS,
185
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
179
186
  },
180
187
  testnet: {
181
188
  name: "Testnet",
@@ -183,7 +190,8 @@ var NETWORKS = {
183
190
  nostrRelays: TEST_NOSTR_RELAYS,
184
191
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
185
192
  electrumUrl: TEST_ELECTRUM_URL,
186
- groupRelays: DEFAULT_GROUP_RELAYS
193
+ groupRelays: DEFAULT_GROUP_RELAYS,
194
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
187
195
  },
188
196
  dev: {
189
197
  name: "Development",
@@ -191,7 +199,8 @@ var NETWORKS = {
191
199
  nostrRelays: TEST_NOSTR_RELAYS,
192
200
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
193
201
  electrumUrl: TEST_ELECTRUM_URL,
194
- groupRelays: DEFAULT_GROUP_RELAYS
202
+ groupRelays: DEFAULT_GROUP_RELAYS,
203
+ tokenRegistryUrl: TOKEN_REGISTRY_URL
195
204
  }
196
205
  };
197
206
  var TIMEOUTS = {
@@ -206,6 +215,7 @@ var TIMEOUTS = {
206
215
  /** Sync interval */
207
216
  SYNC_INTERVAL: 6e4
208
217
  };
218
+ var DEFAULT_MARKET_API_URL = "https://market-api.unicity.network";
209
219
 
210
220
  // impl/nodejs/storage/FileStorageProvider.ts
211
221
  var FileStorageProvider = class {
@@ -4871,6 +4881,363 @@ function createPriceProvider(config) {
4871
4881
  }
4872
4882
  }
4873
4883
 
4884
+ // registry/TokenRegistry.ts
4885
+ var FETCH_TIMEOUT_MS = 1e4;
4886
+ var TokenRegistry = class _TokenRegistry {
4887
+ static instance = null;
4888
+ definitionsById;
4889
+ definitionsBySymbol;
4890
+ definitionsByName;
4891
+ // Remote refresh state
4892
+ remoteUrl = null;
4893
+ storage = null;
4894
+ refreshIntervalMs = TOKEN_REGISTRY_REFRESH_INTERVAL;
4895
+ refreshTimer = null;
4896
+ lastRefreshAt = 0;
4897
+ refreshPromise = null;
4898
+ constructor() {
4899
+ this.definitionsById = /* @__PURE__ */ new Map();
4900
+ this.definitionsBySymbol = /* @__PURE__ */ new Map();
4901
+ this.definitionsByName = /* @__PURE__ */ new Map();
4902
+ }
4903
+ /**
4904
+ * Get singleton instance of TokenRegistry
4905
+ */
4906
+ static getInstance() {
4907
+ if (!_TokenRegistry.instance) {
4908
+ _TokenRegistry.instance = new _TokenRegistry();
4909
+ }
4910
+ return _TokenRegistry.instance;
4911
+ }
4912
+ /**
4913
+ * Configure remote registry refresh with persistent caching.
4914
+ *
4915
+ * On first call:
4916
+ * 1. Loads cached data from StorageProvider (if available and fresh)
4917
+ * 2. Starts periodic remote fetch (if autoRefresh is true, which is default)
4918
+ *
4919
+ * @param options - Configuration options
4920
+ * @param options.remoteUrl - Remote URL to fetch definitions from
4921
+ * @param options.storage - StorageProvider for persistent caching
4922
+ * @param options.refreshIntervalMs - Refresh interval in ms (default: 1 hour)
4923
+ * @param options.autoRefresh - Start auto-refresh immediately (default: true)
4924
+ */
4925
+ static configure(options) {
4926
+ const instance = _TokenRegistry.getInstance();
4927
+ if (options.remoteUrl !== void 0) {
4928
+ instance.remoteUrl = options.remoteUrl;
4929
+ }
4930
+ if (options.storage !== void 0) {
4931
+ instance.storage = options.storage;
4932
+ }
4933
+ if (options.refreshIntervalMs !== void 0) {
4934
+ instance.refreshIntervalMs = options.refreshIntervalMs;
4935
+ }
4936
+ if (instance.storage) {
4937
+ instance.loadFromCache();
4938
+ }
4939
+ const autoRefresh = options.autoRefresh ?? true;
4940
+ if (autoRefresh && instance.remoteUrl) {
4941
+ instance.startAutoRefresh();
4942
+ }
4943
+ }
4944
+ /**
4945
+ * Reset the singleton instance (useful for testing).
4946
+ * Stops auto-refresh if running.
4947
+ */
4948
+ static resetInstance() {
4949
+ if (_TokenRegistry.instance) {
4950
+ _TokenRegistry.instance.stopAutoRefresh();
4951
+ }
4952
+ _TokenRegistry.instance = null;
4953
+ }
4954
+ /**
4955
+ * Destroy the singleton: stop auto-refresh and reset.
4956
+ */
4957
+ static destroy() {
4958
+ _TokenRegistry.resetInstance();
4959
+ }
4960
+ // ===========================================================================
4961
+ // Cache (StorageProvider)
4962
+ // ===========================================================================
4963
+ /**
4964
+ * Load definitions from StorageProvider cache.
4965
+ * Only applies if cache exists and is fresh (within refreshIntervalMs).
4966
+ */
4967
+ async loadFromCache() {
4968
+ if (!this.storage) return false;
4969
+ try {
4970
+ const [cached, cachedTs] = await Promise.all([
4971
+ this.storage.get(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE),
4972
+ this.storage.get(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE_TS)
4973
+ ]);
4974
+ if (!cached || !cachedTs) return false;
4975
+ const ts = parseInt(cachedTs, 10);
4976
+ if (isNaN(ts)) return false;
4977
+ const age = Date.now() - ts;
4978
+ if (age > this.refreshIntervalMs) return false;
4979
+ if (this.lastRefreshAt > ts) return false;
4980
+ const data = JSON.parse(cached);
4981
+ if (!this.isValidDefinitionsArray(data)) return false;
4982
+ this.applyDefinitions(data);
4983
+ this.lastRefreshAt = ts;
4984
+ return true;
4985
+ } catch {
4986
+ return false;
4987
+ }
4988
+ }
4989
+ /**
4990
+ * Save definitions to StorageProvider cache.
4991
+ */
4992
+ async saveToCache(definitions) {
4993
+ if (!this.storage) return;
4994
+ try {
4995
+ await Promise.all([
4996
+ this.storage.set(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE, JSON.stringify(definitions)),
4997
+ this.storage.set(STORAGE_KEYS_GLOBAL.TOKEN_REGISTRY_CACHE_TS, String(Date.now()))
4998
+ ]);
4999
+ } catch {
5000
+ }
5001
+ }
5002
+ // ===========================================================================
5003
+ // Remote Refresh
5004
+ // ===========================================================================
5005
+ /**
5006
+ * Apply an array of token definitions to the internal maps.
5007
+ * Clears existing data before applying.
5008
+ */
5009
+ applyDefinitions(definitions) {
5010
+ this.definitionsById.clear();
5011
+ this.definitionsBySymbol.clear();
5012
+ this.definitionsByName.clear();
5013
+ for (const def of definitions) {
5014
+ const idLower = def.id.toLowerCase();
5015
+ this.definitionsById.set(idLower, def);
5016
+ if (def.symbol) {
5017
+ this.definitionsBySymbol.set(def.symbol.toUpperCase(), def);
5018
+ }
5019
+ this.definitionsByName.set(def.name.toLowerCase(), def);
5020
+ }
5021
+ }
5022
+ /**
5023
+ * Validate that data is an array of objects with 'id' field
5024
+ */
5025
+ isValidDefinitionsArray(data) {
5026
+ return Array.isArray(data) && data.every((item) => item && typeof item === "object" && "id" in item);
5027
+ }
5028
+ /**
5029
+ * Fetch token definitions from the remote URL and update the registry.
5030
+ * On success, also persists to StorageProvider cache.
5031
+ * Returns true on success, false on failure. On failure, existing data is preserved.
5032
+ * Concurrent calls are deduplicated — only one fetch runs at a time.
5033
+ */
5034
+ async refreshFromRemote() {
5035
+ if (!this.remoteUrl) {
5036
+ return false;
5037
+ }
5038
+ if (this.refreshPromise) {
5039
+ return this.refreshPromise;
5040
+ }
5041
+ this.refreshPromise = this.doRefresh();
5042
+ try {
5043
+ return await this.refreshPromise;
5044
+ } finally {
5045
+ this.refreshPromise = null;
5046
+ }
5047
+ }
5048
+ async doRefresh() {
5049
+ try {
5050
+ const controller = new AbortController();
5051
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
5052
+ let response;
5053
+ try {
5054
+ response = await fetch(this.remoteUrl, {
5055
+ headers: { Accept: "application/json" },
5056
+ signal: controller.signal
5057
+ });
5058
+ } finally {
5059
+ clearTimeout(timer);
5060
+ }
5061
+ if (!response.ok) {
5062
+ console.warn(
5063
+ `[TokenRegistry] Remote fetch failed: HTTP ${response.status} ${response.statusText}`
5064
+ );
5065
+ return false;
5066
+ }
5067
+ const data = await response.json();
5068
+ if (!this.isValidDefinitionsArray(data)) {
5069
+ console.warn("[TokenRegistry] Remote data is not a valid token definitions array");
5070
+ return false;
5071
+ }
5072
+ const definitions = data;
5073
+ this.applyDefinitions(definitions);
5074
+ this.lastRefreshAt = Date.now();
5075
+ this.saveToCache(definitions);
5076
+ return true;
5077
+ } catch (error) {
5078
+ const message = error instanceof Error ? error.message : String(error);
5079
+ console.warn(`[TokenRegistry] Remote refresh failed: ${message}`);
5080
+ return false;
5081
+ }
5082
+ }
5083
+ /**
5084
+ * Start periodic auto-refresh from the remote URL.
5085
+ * Does an immediate fetch, then repeats at the configured interval.
5086
+ */
5087
+ startAutoRefresh(intervalMs) {
5088
+ this.stopAutoRefresh();
5089
+ if (intervalMs !== void 0) {
5090
+ this.refreshIntervalMs = intervalMs;
5091
+ }
5092
+ this.refreshFromRemote();
5093
+ this.refreshTimer = setInterval(() => {
5094
+ this.refreshFromRemote();
5095
+ }, this.refreshIntervalMs);
5096
+ }
5097
+ /**
5098
+ * Stop periodic auto-refresh
5099
+ */
5100
+ stopAutoRefresh() {
5101
+ if (this.refreshTimer !== null) {
5102
+ clearInterval(this.refreshTimer);
5103
+ this.refreshTimer = null;
5104
+ }
5105
+ }
5106
+ /**
5107
+ * Timestamp of the last successful remote refresh (0 if never refreshed)
5108
+ */
5109
+ getLastRefreshAt() {
5110
+ return this.lastRefreshAt;
5111
+ }
5112
+ // ===========================================================================
5113
+ // Lookup Methods
5114
+ // ===========================================================================
5115
+ /**
5116
+ * Get token definition by hex coin ID
5117
+ * @param coinId - 64-character hex string
5118
+ * @returns Token definition or undefined if not found
5119
+ */
5120
+ getDefinition(coinId) {
5121
+ if (!coinId) return void 0;
5122
+ return this.definitionsById.get(coinId.toLowerCase());
5123
+ }
5124
+ /**
5125
+ * Get token definition by symbol (e.g., "UCT", "BTC")
5126
+ * @param symbol - Token symbol (case-insensitive)
5127
+ * @returns Token definition or undefined if not found
5128
+ */
5129
+ getDefinitionBySymbol(symbol) {
5130
+ if (!symbol) return void 0;
5131
+ return this.definitionsBySymbol.get(symbol.toUpperCase());
5132
+ }
5133
+ /**
5134
+ * Get token definition by name (e.g., "bitcoin", "ethereum")
5135
+ * @param name - Token name (case-insensitive)
5136
+ * @returns Token definition or undefined if not found
5137
+ */
5138
+ getDefinitionByName(name) {
5139
+ if (!name) return void 0;
5140
+ return this.definitionsByName.get(name.toLowerCase());
5141
+ }
5142
+ /**
5143
+ * Get token symbol for a coin ID
5144
+ * @param coinId - 64-character hex string
5145
+ * @returns Symbol (e.g., "UCT") or truncated ID if not found
5146
+ */
5147
+ getSymbol(coinId) {
5148
+ const def = this.getDefinition(coinId);
5149
+ if (def?.symbol) {
5150
+ return def.symbol;
5151
+ }
5152
+ return coinId.slice(0, 6).toUpperCase();
5153
+ }
5154
+ /**
5155
+ * Get token name for a coin ID
5156
+ * @param coinId - 64-character hex string
5157
+ * @returns Name (e.g., "Bitcoin") or coin ID if not found
5158
+ */
5159
+ getName(coinId) {
5160
+ const def = this.getDefinition(coinId);
5161
+ if (def?.name) {
5162
+ return def.name.charAt(0).toUpperCase() + def.name.slice(1);
5163
+ }
5164
+ return coinId;
5165
+ }
5166
+ /**
5167
+ * Get decimal places for a coin ID
5168
+ * @param coinId - 64-character hex string
5169
+ * @returns Decimals or 0 if not found
5170
+ */
5171
+ getDecimals(coinId) {
5172
+ const def = this.getDefinition(coinId);
5173
+ return def?.decimals ?? 0;
5174
+ }
5175
+ /**
5176
+ * Get icon URL for a coin ID
5177
+ * @param coinId - 64-character hex string
5178
+ * @param preferPng - Prefer PNG format over SVG
5179
+ * @returns Icon URL or null if not found
5180
+ */
5181
+ getIconUrl(coinId, preferPng = true) {
5182
+ const def = this.getDefinition(coinId);
5183
+ if (!def?.icons || def.icons.length === 0) {
5184
+ return null;
5185
+ }
5186
+ if (preferPng) {
5187
+ const pngIcon = def.icons.find((i) => i.url.toLowerCase().includes(".png"));
5188
+ if (pngIcon) return pngIcon.url;
5189
+ }
5190
+ return def.icons[0].url;
5191
+ }
5192
+ /**
5193
+ * Check if a coin ID is known in the registry
5194
+ * @param coinId - 64-character hex string
5195
+ * @returns true if the coin is in the registry
5196
+ */
5197
+ isKnown(coinId) {
5198
+ return this.definitionsById.has(coinId.toLowerCase());
5199
+ }
5200
+ /**
5201
+ * Get all token definitions
5202
+ * @returns Array of all token definitions
5203
+ */
5204
+ getAllDefinitions() {
5205
+ return Array.from(this.definitionsById.values());
5206
+ }
5207
+ /**
5208
+ * Get all fungible token definitions
5209
+ * @returns Array of fungible token definitions
5210
+ */
5211
+ getFungibleTokens() {
5212
+ return this.getAllDefinitions().filter((def) => def.assetKind === "fungible");
5213
+ }
5214
+ /**
5215
+ * Get all non-fungible token definitions
5216
+ * @returns Array of non-fungible token definitions
5217
+ */
5218
+ getNonFungibleTokens() {
5219
+ return this.getAllDefinitions().filter((def) => def.assetKind === "non-fungible");
5220
+ }
5221
+ /**
5222
+ * Get coin ID by symbol
5223
+ * @param symbol - Token symbol (e.g., "UCT")
5224
+ * @returns Coin ID hex string or undefined if not found
5225
+ */
5226
+ getCoinIdBySymbol(symbol) {
5227
+ const def = this.getDefinitionBySymbol(symbol);
5228
+ return def?.id;
5229
+ }
5230
+ /**
5231
+ * Get coin ID by name
5232
+ * @param name - Token name (e.g., "bitcoin")
5233
+ * @returns Coin ID hex string or undefined if not found
5234
+ */
5235
+ getCoinIdByName(name) {
5236
+ const def = this.getDefinitionByName(name);
5237
+ return def?.id;
5238
+ }
5239
+ };
5240
+
4874
5241
  // impl/shared/resolvers.ts
4875
5242
  function getNetworkConfig(network = "mainnet") {
4876
5243
  return NETWORKS[network];
@@ -4946,6 +5313,16 @@ function resolveGroupChatConfig(network, config) {
4946
5313
  relays: config.relays ?? [...netConfig.groupRelays]
4947
5314
  };
4948
5315
  }
5316
+ function resolveMarketConfig(config) {
5317
+ if (!config) return void 0;
5318
+ if (config === true) {
5319
+ return { apiUrl: DEFAULT_MARKET_API_URL };
5320
+ }
5321
+ return {
5322
+ apiUrl: config.apiUrl ?? DEFAULT_MARKET_API_URL,
5323
+ timeout: config.timeout
5324
+ };
5325
+ }
4949
5326
 
4950
5327
  // impl/nodejs/index.ts
4951
5328
  function createNodeProviders(config) {
@@ -4961,9 +5338,13 @@ function createNodeProviders(config) {
4961
5338
  const ipfsSync = config?.tokenSync?.ipfs;
4962
5339
  const ipfsTokenStorage = ipfsSync?.enabled ? createNodeIpfsStorageProvider(ipfsSync.config, storage) : void 0;
4963
5340
  const groupChat = resolveGroupChatConfig(network, config?.groupChat);
5341
+ const networkConfig = getNetworkConfig(network);
5342
+ TokenRegistry.configure({ remoteUrl: networkConfig.tokenRegistryUrl, storage });
5343
+ const market = resolveMarketConfig(config?.market);
4964
5344
  return {
4965
5345
  storage,
4966
5346
  groupChat,
5347
+ market,
4967
5348
  tokenStorage: createFileTokenStorageProvider({
4968
5349
  tokensDir: config?.tokensDir ?? "./sphere-tokens"
4969
5350
  }),