@unicitylabs/sphere-sdk 0.2.3 → 0.3.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.
@@ -27,7 +27,17 @@ var STORAGE_KEYS_GLOBAL = {
27
27
  /** Active addresses registry (JSON: TrackedAddressesStorage) */
28
28
  TRACKED_ADDRESSES: "tracked_addresses",
29
29
  /** Last processed Nostr wallet event timestamp (unix seconds), keyed per pubkey */
30
- LAST_WALLET_EVENT_TS: "last_wallet_event_ts"
30
+ LAST_WALLET_EVENT_TS: "last_wallet_event_ts",
31
+ /** Group chat: joined groups */
32
+ GROUP_CHAT_GROUPS: "group_chat_groups",
33
+ /** Group chat: messages */
34
+ GROUP_CHAT_MESSAGES: "group_chat_messages",
35
+ /** Group chat: members */
36
+ GROUP_CHAT_MEMBERS: "group_chat_members",
37
+ /** Group chat: processed event IDs for deduplication */
38
+ GROUP_CHAT_PROCESSED_EVENTS: "group_chat_processed_events",
39
+ /** Group chat: last used relay URL (stale data detection) */
40
+ GROUP_CHAT_RELAY_URL: "group_chat_relay_url"
31
41
  };
32
42
  var STORAGE_KEYS_ADDRESS = {
33
43
  /** Pending transfers for this address */
@@ -39,7 +49,9 @@ var STORAGE_KEYS_ADDRESS = {
39
49
  /** Messages for this address */
40
50
  MESSAGES: "messages",
41
51
  /** Transaction history for this address */
42
- TRANSACTION_HISTORY: "transaction_history"
52
+ TRANSACTION_HISTORY: "transaction_history",
53
+ /** Pending V5 finalization tokens (unconfirmed instant split tokens) */
54
+ PENDING_V5_TOKENS: "pending_v5_tokens"
43
55
  };
44
56
  var STORAGE_KEYS = {
45
57
  ...STORAGE_KEYS_GLOBAL,
@@ -86,6 +98,19 @@ var DEFAULT_IPFS_GATEWAYS = [
86
98
  "https://dweb.link",
87
99
  "https://ipfs.io"
88
100
  ];
101
+ var UNICITY_IPFS_NODES = [
102
+ {
103
+ host: "unicity-ipfs1.dyndns.org",
104
+ peerId: "12D3KooWDKJqEMAhH4nsSSiKtK1VLcas5coUqSPZAfbWbZpxtL4u",
105
+ httpPort: 9080,
106
+ httpsPort: 443
107
+ }
108
+ ];
109
+ function getIpfsGatewayUrls(isSecure) {
110
+ return UNICITY_IPFS_NODES.map(
111
+ (node) => isSecure !== false ? `https://${node.host}` : `http://${node.host}:${node.httpPort}`
112
+ );
113
+ }
89
114
  var DEFAULT_BASE_PATH = "m/44'/0'/0'";
90
115
  var DEFAULT_DERIVATION_PATH = `${DEFAULT_BASE_PATH}/0/0`;
91
116
  var DEFAULT_ELECTRUM_URL = "wss://fulcrum.alpha.unicity.network:50004";
@@ -93,27 +118,33 @@ var TEST_ELECTRUM_URL = "wss://fulcrum.alpha.testnet.unicity.network:50004";
93
118
  var TEST_NOSTR_RELAYS = [
94
119
  "wss://nostr-relay.testnet.unicity.network"
95
120
  ];
121
+ var DEFAULT_GROUP_RELAYS = [
122
+ "wss://sphere-relay.unicity.network"
123
+ ];
96
124
  var NETWORKS = {
97
125
  mainnet: {
98
126
  name: "Mainnet",
99
127
  aggregatorUrl: DEFAULT_AGGREGATOR_URL,
100
128
  nostrRelays: DEFAULT_NOSTR_RELAYS,
101
129
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
102
- electrumUrl: DEFAULT_ELECTRUM_URL
130
+ electrumUrl: DEFAULT_ELECTRUM_URL,
131
+ groupRelays: DEFAULT_GROUP_RELAYS
103
132
  },
104
133
  testnet: {
105
134
  name: "Testnet",
106
135
  aggregatorUrl: TEST_AGGREGATOR_URL,
107
136
  nostrRelays: TEST_NOSTR_RELAYS,
108
137
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
109
- electrumUrl: TEST_ELECTRUM_URL
138
+ electrumUrl: TEST_ELECTRUM_URL,
139
+ groupRelays: DEFAULT_GROUP_RELAYS
110
140
  },
111
141
  dev: {
112
142
  name: "Development",
113
143
  aggregatorUrl: DEV_AGGREGATOR_URL,
114
144
  nostrRelays: TEST_NOSTR_RELAYS,
115
145
  ipfsGateways: DEFAULT_IPFS_GATEWAYS,
116
- electrumUrl: TEST_ELECTRUM_URL
146
+ electrumUrl: TEST_ELECTRUM_URL,
147
+ groupRelays: DEFAULT_GROUP_RELAYS
117
148
  }
118
149
  };
119
150
  var TIMEOUTS = {
@@ -430,34 +461,6 @@ var FileTokenStorageProvider = class {
430
461
  return false;
431
462
  }
432
463
  }
433
- async deleteToken(tokenId) {
434
- const filePath = path2.join(this.tokensDir, `${tokenId}.json`);
435
- if (fs2.existsSync(filePath)) {
436
- fs2.unlinkSync(filePath);
437
- }
438
- }
439
- async saveToken(tokenId, tokenData) {
440
- fs2.writeFileSync(
441
- path2.join(this.tokensDir, `${tokenId}.json`),
442
- JSON.stringify(tokenData, null, 2)
443
- );
444
- }
445
- async getToken(tokenId) {
446
- const filePath = path2.join(this.tokensDir, `${tokenId}.json`);
447
- if (!fs2.existsSync(filePath)) {
448
- return null;
449
- }
450
- try {
451
- const content = fs2.readFileSync(filePath, "utf-8");
452
- return JSON.parse(content);
453
- } catch {
454
- return null;
455
- }
456
- }
457
- async listTokenIds() {
458
- const files = fs2.readdirSync(this.tokensDir).filter((f) => f.endsWith(".json") && f !== "_meta.json");
459
- return files.map((f) => path2.basename(f, ".json"));
460
- }
461
464
  };
462
465
  function createFileTokenStorageProvider(config) {
463
466
  return new FileTokenStorageProvider(config);
@@ -1025,8 +1028,21 @@ function publicKeyToAddress(publicKey, prefix = "alpha", witnessVersion = 0) {
1025
1028
  const programBytes = hash160ToBytes(pubKeyHash);
1026
1029
  return encodeBech32(prefix, witnessVersion, programBytes);
1027
1030
  }
1031
+ function hexToBytes(hex) {
1032
+ const matches = hex.match(/../g);
1033
+ if (!matches) {
1034
+ return new Uint8Array(0);
1035
+ }
1036
+ return Uint8Array.from(matches.map((x) => parseInt(x, 16)));
1037
+ }
1028
1038
 
1029
1039
  // transport/websocket.ts
1040
+ var WebSocketReadyState = {
1041
+ CONNECTING: 0,
1042
+ OPEN: 1,
1043
+ CLOSING: 2,
1044
+ CLOSED: 3
1045
+ };
1030
1046
  function defaultUUIDGenerator() {
1031
1047
  if (typeof crypto !== "undefined" && crypto.randomUUID) {
1032
1048
  return crypto.randomUUID();
@@ -1114,6 +1130,7 @@ var NostrTransportProvider = class {
1114
1130
  nostrClient = null;
1115
1131
  mainSubscriptionId = null;
1116
1132
  // Event handlers
1133
+ processedEventIds = /* @__PURE__ */ new Set();
1117
1134
  messageHandlers = /* @__PURE__ */ new Set();
1118
1135
  transferHandlers = /* @__PURE__ */ new Set();
1119
1136
  paymentRequestHandlers = /* @__PURE__ */ new Set();
@@ -1854,6 +1871,12 @@ var NostrTransportProvider = class {
1854
1871
  // Private: Message Handling
1855
1872
  // ===========================================================================
1856
1873
  async handleEvent(event) {
1874
+ if (event.id && this.processedEventIds.has(event.id)) {
1875
+ return;
1876
+ }
1877
+ if (event.id) {
1878
+ this.processedEventIds.add(event.id);
1879
+ }
1857
1880
  this.log("Processing event kind:", event.kind, "id:", event.id?.slice(0, 12));
1858
1881
  try {
1859
1882
  switch (event.kind) {
@@ -1966,7 +1989,7 @@ var NostrTransportProvider = class {
1966
1989
  this.emitEvent({ type: "transfer:received", timestamp: Date.now() });
1967
1990
  for (const handler of this.transferHandlers) {
1968
1991
  try {
1969
- handler(transfer);
1992
+ await handler(transfer);
1970
1993
  } catch (error) {
1971
1994
  this.log("Transfer handler error:", error);
1972
1995
  }
@@ -2096,6 +2119,49 @@ var NostrTransportProvider = class {
2096
2119
  const sdkEvent = NostrEventClass.fromJSON(event);
2097
2120
  await this.nostrClient.publishEvent(sdkEvent);
2098
2121
  }
2122
+ async fetchPendingEvents() {
2123
+ if (!this.nostrClient?.isConnected() || !this.keyManager) {
2124
+ throw new Error("Transport not connected");
2125
+ }
2126
+ const nostrPubkey = this.keyManager.getPublicKeyHex();
2127
+ const walletFilter = new Filter();
2128
+ walletFilter.kinds = [
2129
+ EVENT_KINDS.DIRECT_MESSAGE,
2130
+ EVENT_KINDS.TOKEN_TRANSFER,
2131
+ EVENT_KINDS.PAYMENT_REQUEST,
2132
+ EVENT_KINDS.PAYMENT_REQUEST_RESPONSE
2133
+ ];
2134
+ walletFilter["#p"] = [nostrPubkey];
2135
+ walletFilter.since = Math.floor(Date.now() / 1e3) - 86400;
2136
+ const events = [];
2137
+ await new Promise((resolve) => {
2138
+ const timeout = setTimeout(() => {
2139
+ if (subId) this.nostrClient?.unsubscribe(subId);
2140
+ resolve();
2141
+ }, 5e3);
2142
+ const subId = this.nostrClient.subscribe(walletFilter, {
2143
+ onEvent: (event) => {
2144
+ events.push({
2145
+ id: event.id,
2146
+ kind: event.kind,
2147
+ content: event.content,
2148
+ tags: event.tags,
2149
+ pubkey: event.pubkey,
2150
+ created_at: event.created_at,
2151
+ sig: event.sig
2152
+ });
2153
+ },
2154
+ onEndOfStoredEvents: () => {
2155
+ clearTimeout(timeout);
2156
+ this.nostrClient?.unsubscribe(subId);
2157
+ resolve();
2158
+ }
2159
+ });
2160
+ });
2161
+ for (const event of events) {
2162
+ await this.handleEvent(event);
2163
+ }
2164
+ }
2099
2165
  async queryEvents(filterObj) {
2100
2166
  if (!this.nostrClient || !this.nostrClient.isConnected()) {
2101
2167
  throw new Error("No connected relays");
@@ -2805,172 +2871,2028 @@ function createUnicityAggregatorProvider(config) {
2805
2871
  }
2806
2872
  var createUnicityOracleProvider = createUnicityAggregatorProvider;
2807
2873
 
2808
- // price/CoinGeckoPriceProvider.ts
2809
- var CoinGeckoPriceProvider = class {
2810
- platform = "coingecko";
2811
- cache = /* @__PURE__ */ new Map();
2812
- apiKey;
2813
- cacheTtlMs;
2814
- timeout;
2815
- debug;
2816
- baseUrl;
2817
- constructor(config) {
2818
- this.apiKey = config?.apiKey;
2819
- this.cacheTtlMs = config?.cacheTtlMs ?? 6e4;
2820
- this.timeout = config?.timeout ?? 1e4;
2821
- this.debug = config?.debug ?? false;
2822
- this.baseUrl = config?.baseUrl ?? (this.apiKey ? "https://pro-api.coingecko.com/api/v3" : "https://api.coingecko.com/api/v3");
2874
+ // impl/shared/ipfs/ipfs-error-types.ts
2875
+ var IpfsError = class extends Error {
2876
+ category;
2877
+ gateway;
2878
+ cause;
2879
+ constructor(message, category, gateway, cause) {
2880
+ super(message);
2881
+ this.name = "IpfsError";
2882
+ this.category = category;
2883
+ this.gateway = gateway;
2884
+ this.cause = cause;
2885
+ }
2886
+ /** Whether this error should trigger the circuit breaker */
2887
+ get shouldTriggerCircuitBreaker() {
2888
+ return this.category !== "NOT_FOUND" && this.category !== "SEQUENCE_DOWNGRADE";
2823
2889
  }
2824
- async getPrices(tokenNames) {
2825
- if (tokenNames.length === 0) {
2826
- return /* @__PURE__ */ new Map();
2827
- }
2828
- const now = Date.now();
2829
- const result = /* @__PURE__ */ new Map();
2830
- const uncachedNames = [];
2831
- for (const name of tokenNames) {
2832
- const cached = this.cache.get(name);
2833
- if (cached && cached.expiresAt > now) {
2834
- if (cached.price !== null) {
2835
- result.set(name, cached.price);
2836
- }
2837
- } else {
2838
- uncachedNames.push(name);
2839
- }
2840
- }
2841
- if (uncachedNames.length === 0) {
2842
- return result;
2843
- }
2844
- try {
2845
- const ids = uncachedNames.join(",");
2846
- const url = `${this.baseUrl}/simple/price?ids=${encodeURIComponent(ids)}&vs_currencies=usd,eur&include_24hr_change=true`;
2847
- const headers = { Accept: "application/json" };
2848
- if (this.apiKey) {
2849
- headers["x-cg-pro-api-key"] = this.apiKey;
2850
- }
2851
- if (this.debug) {
2852
- console.log(`[CoinGecko] Fetching prices for: ${uncachedNames.join(", ")}`);
2853
- }
2854
- const response = await fetch(url, {
2855
- headers,
2856
- signal: AbortSignal.timeout(this.timeout)
2857
- });
2858
- if (!response.ok) {
2859
- throw new Error(`CoinGecko API error: ${response.status} ${response.statusText}`);
2860
- }
2861
- const data = await response.json();
2862
- for (const [name, values] of Object.entries(data)) {
2863
- if (values && typeof values === "object") {
2864
- const price = {
2865
- tokenName: name,
2866
- priceUsd: values.usd ?? 0,
2867
- priceEur: values.eur,
2868
- change24h: values.usd_24h_change,
2869
- timestamp: now
2870
- };
2871
- this.cache.set(name, { price, expiresAt: now + this.cacheTtlMs });
2872
- result.set(name, price);
2873
- }
2874
- }
2875
- for (const name of uncachedNames) {
2876
- if (!result.has(name)) {
2877
- this.cache.set(name, { price: null, expiresAt: now + this.cacheTtlMs });
2878
- }
2879
- }
2880
- if (this.debug) {
2881
- console.log(`[CoinGecko] Fetched ${result.size} prices`);
2882
- }
2883
- } catch (error) {
2884
- if (this.debug) {
2885
- console.warn("[CoinGecko] Fetch failed, using stale cache:", error);
2886
- }
2887
- for (const name of uncachedNames) {
2888
- const stale = this.cache.get(name);
2889
- if (stale?.price) {
2890
- result.set(name, stale.price);
2891
- }
2892
- }
2890
+ };
2891
+ function classifyFetchError(error) {
2892
+ if (error instanceof DOMException && error.name === "AbortError") {
2893
+ return "TIMEOUT";
2894
+ }
2895
+ if (error instanceof TypeError) {
2896
+ return "NETWORK_ERROR";
2897
+ }
2898
+ if (error instanceof Error && error.name === "TimeoutError") {
2899
+ return "TIMEOUT";
2900
+ }
2901
+ return "NETWORK_ERROR";
2902
+ }
2903
+ function classifyHttpStatus(status, responseBody) {
2904
+ if (status === 404) {
2905
+ return "NOT_FOUND";
2906
+ }
2907
+ if (status === 500 && responseBody) {
2908
+ if (/routing:\s*not\s*found/i.test(responseBody)) {
2909
+ return "NOT_FOUND";
2893
2910
  }
2894
- return result;
2895
2911
  }
2896
- async getPrice(tokenName) {
2897
- const prices = await this.getPrices([tokenName]);
2898
- return prices.get(tokenName) ?? null;
2912
+ if (status >= 500) {
2913
+ return "GATEWAY_ERROR";
2899
2914
  }
2900
- clearCache() {
2901
- this.cache.clear();
2915
+ if (status >= 400) {
2916
+ return "GATEWAY_ERROR";
2902
2917
  }
2903
- };
2918
+ return "GATEWAY_ERROR";
2919
+ }
2904
2920
 
2905
- // price/index.ts
2906
- function createPriceProvider(config) {
2907
- switch (config.platform) {
2908
- case "coingecko":
2909
- return new CoinGeckoPriceProvider(config);
2910
- default:
2911
- throw new Error(`Unsupported price platform: ${String(config.platform)}`);
2921
+ // impl/shared/ipfs/ipfs-state-persistence.ts
2922
+ var InMemoryIpfsStatePersistence = class {
2923
+ states = /* @__PURE__ */ new Map();
2924
+ async load(ipnsName) {
2925
+ return this.states.get(ipnsName) ?? null;
2912
2926
  }
2913
- }
2927
+ async save(ipnsName, state) {
2928
+ this.states.set(ipnsName, { ...state });
2929
+ }
2930
+ async clear(ipnsName) {
2931
+ this.states.delete(ipnsName);
2932
+ }
2933
+ };
2914
2934
 
2915
- // impl/shared/resolvers.ts
2916
- function getNetworkConfig(network = "mainnet") {
2917
- return NETWORKS[network];
2918
- }
2919
- function resolveTransportConfig(network, config) {
2920
- const networkConfig = getNetworkConfig(network);
2921
- let relays;
2922
- if (config?.relays) {
2923
- relays = config.relays;
2924
- } else {
2925
- relays = [...networkConfig.nostrRelays];
2926
- if (config?.additionalRelays) {
2927
- relays = [...relays, ...config.additionalRelays];
2928
- }
2935
+ // impl/shared/ipfs/ipns-key-derivation.ts
2936
+ var IPNS_HKDF_INFO = "ipfs-storage-ed25519-v1";
2937
+ var libp2pCryptoModule = null;
2938
+ var libp2pPeerIdModule = null;
2939
+ async function loadLibp2pModules() {
2940
+ if (!libp2pCryptoModule) {
2941
+ [libp2pCryptoModule, libp2pPeerIdModule] = await Promise.all([
2942
+ import("@libp2p/crypto/keys"),
2943
+ import("@libp2p/peer-id")
2944
+ ]);
2929
2945
  }
2930
2946
  return {
2931
- relays,
2932
- timeout: config?.timeout,
2933
- autoReconnect: config?.autoReconnect,
2934
- debug: config?.debug,
2935
- // Browser-specific
2936
- reconnectDelay: config?.reconnectDelay,
2937
- maxReconnectAttempts: config?.maxReconnectAttempts
2947
+ generateKeyPairFromSeed: libp2pCryptoModule.generateKeyPairFromSeed,
2948
+ peerIdFromPrivateKey: libp2pPeerIdModule.peerIdFromPrivateKey
2938
2949
  };
2939
2950
  }
2940
- function resolveOracleConfig(network, config) {
2941
- const networkConfig = getNetworkConfig(network);
2951
+ function deriveEd25519KeyMaterial(privateKeyHex, info = IPNS_HKDF_INFO) {
2952
+ const walletSecret = hexToBytes(privateKeyHex);
2953
+ const infoBytes = new TextEncoder().encode(info);
2954
+ return hkdf(sha256, walletSecret, void 0, infoBytes, 32);
2955
+ }
2956
+ async function deriveIpnsIdentity(privateKeyHex) {
2957
+ const { generateKeyPairFromSeed, peerIdFromPrivateKey } = await loadLibp2pModules();
2958
+ const derivedKey = deriveEd25519KeyMaterial(privateKeyHex);
2959
+ const keyPair = await generateKeyPairFromSeed("Ed25519", derivedKey);
2960
+ const peerId = peerIdFromPrivateKey(keyPair);
2942
2961
  return {
2943
- url: config?.url ?? networkConfig.aggregatorUrl,
2944
- apiKey: config?.apiKey ?? DEFAULT_AGGREGATOR_API_KEY,
2945
- timeout: config?.timeout,
2946
- skipVerification: config?.skipVerification,
2947
- debug: config?.debug,
2948
- // Node.js-specific
2949
- trustBasePath: config?.trustBasePath
2962
+ keyPair,
2963
+ ipnsName: peerId.toString()
2950
2964
  };
2951
2965
  }
2952
- function resolveL1Config(network, config) {
2953
- if (config === void 0) {
2954
- return void 0;
2966
+
2967
+ // impl/shared/ipfs/ipns-record-manager.ts
2968
+ var DEFAULT_LIFETIME_MS = 99 * 365 * 24 * 60 * 60 * 1e3;
2969
+ var ipnsModule = null;
2970
+ async function loadIpnsModule() {
2971
+ if (!ipnsModule) {
2972
+ const mod = await import("ipns");
2973
+ ipnsModule = {
2974
+ createIPNSRecord: mod.createIPNSRecord,
2975
+ marshalIPNSRecord: mod.marshalIPNSRecord,
2976
+ unmarshalIPNSRecord: mod.unmarshalIPNSRecord
2977
+ };
2955
2978
  }
2956
- const networkConfig = getNetworkConfig(network);
2957
- return {
2958
- electrumUrl: config.electrumUrl ?? networkConfig.electrumUrl,
2959
- defaultFeeRate: config.defaultFeeRate,
2960
- enableVesting: config.enableVesting
2961
- };
2979
+ return ipnsModule;
2962
2980
  }
2963
- function resolvePriceConfig(config) {
2964
- if (config === void 0) {
2965
- return void 0;
2981
+ async function createSignedRecord(keyPair, cid, sequenceNumber, lifetimeMs = DEFAULT_LIFETIME_MS) {
2982
+ const { createIPNSRecord, marshalIPNSRecord } = await loadIpnsModule();
2983
+ const record = await createIPNSRecord(
2984
+ keyPair,
2985
+ `/ipfs/${cid}`,
2986
+ sequenceNumber,
2987
+ lifetimeMs
2988
+ );
2989
+ return marshalIPNSRecord(record);
2990
+ }
2991
+ async function parseRoutingApiResponse(responseText) {
2992
+ const { unmarshalIPNSRecord } = await loadIpnsModule();
2993
+ const lines = responseText.trim().split("\n");
2994
+ for (const line of lines) {
2995
+ if (!line.trim()) continue;
2996
+ try {
2997
+ const obj = JSON.parse(line);
2998
+ if (obj.Extra) {
2999
+ const recordData = base64ToUint8Array(obj.Extra);
3000
+ const record = unmarshalIPNSRecord(recordData);
3001
+ const valueBytes = typeof record.value === "string" ? new TextEncoder().encode(record.value) : record.value;
3002
+ const valueStr = new TextDecoder().decode(valueBytes);
3003
+ const cidMatch = valueStr.match(/\/ipfs\/([a-zA-Z0-9]+)/);
3004
+ if (cidMatch) {
3005
+ return {
3006
+ cid: cidMatch[1],
3007
+ sequence: record.sequence,
3008
+ recordData
3009
+ };
3010
+ }
3011
+ }
3012
+ } catch {
3013
+ continue;
3014
+ }
2966
3015
  }
2967
- return {
2968
- platform: config.platform ?? "coingecko",
2969
- apiKey: config.apiKey,
2970
- baseUrl: config.baseUrl,
2971
- cacheTtlMs: config.cacheTtlMs,
2972
- timeout: config.timeout,
2973
- debug: config.debug
3016
+ return null;
3017
+ }
3018
+ function base64ToUint8Array(base64) {
3019
+ const binary = atob(base64);
3020
+ const bytes = new Uint8Array(binary.length);
3021
+ for (let i = 0; i < binary.length; i++) {
3022
+ bytes[i] = binary.charCodeAt(i);
3023
+ }
3024
+ return bytes;
3025
+ }
3026
+
3027
+ // impl/shared/ipfs/ipfs-cache.ts
3028
+ var DEFAULT_IPNS_TTL_MS = 6e4;
3029
+ var DEFAULT_FAILURE_COOLDOWN_MS = 6e4;
3030
+ var DEFAULT_FAILURE_THRESHOLD = 3;
3031
+ var DEFAULT_KNOWN_FRESH_WINDOW_MS = 3e4;
3032
+ var IpfsCache = class {
3033
+ ipnsRecords = /* @__PURE__ */ new Map();
3034
+ content = /* @__PURE__ */ new Map();
3035
+ gatewayFailures = /* @__PURE__ */ new Map();
3036
+ knownFreshTimestamps = /* @__PURE__ */ new Map();
3037
+ ipnsTtlMs;
3038
+ failureCooldownMs;
3039
+ failureThreshold;
3040
+ knownFreshWindowMs;
3041
+ constructor(config) {
3042
+ this.ipnsTtlMs = config?.ipnsTtlMs ?? DEFAULT_IPNS_TTL_MS;
3043
+ this.failureCooldownMs = config?.failureCooldownMs ?? DEFAULT_FAILURE_COOLDOWN_MS;
3044
+ this.failureThreshold = config?.failureThreshold ?? DEFAULT_FAILURE_THRESHOLD;
3045
+ this.knownFreshWindowMs = config?.knownFreshWindowMs ?? DEFAULT_KNOWN_FRESH_WINDOW_MS;
3046
+ }
3047
+ // ---------------------------------------------------------------------------
3048
+ // IPNS Record Cache (60s TTL)
3049
+ // ---------------------------------------------------------------------------
3050
+ getIpnsRecord(ipnsName) {
3051
+ const entry = this.ipnsRecords.get(ipnsName);
3052
+ if (!entry) return null;
3053
+ if (Date.now() - entry.timestamp > this.ipnsTtlMs) {
3054
+ this.ipnsRecords.delete(ipnsName);
3055
+ return null;
3056
+ }
3057
+ return entry.data;
3058
+ }
3059
+ /**
3060
+ * Get cached IPNS record ignoring TTL (for known-fresh optimization).
3061
+ */
3062
+ getIpnsRecordIgnoreTtl(ipnsName) {
3063
+ const entry = this.ipnsRecords.get(ipnsName);
3064
+ return entry?.data ?? null;
3065
+ }
3066
+ setIpnsRecord(ipnsName, result) {
3067
+ this.ipnsRecords.set(ipnsName, {
3068
+ data: result,
3069
+ timestamp: Date.now()
3070
+ });
3071
+ }
3072
+ invalidateIpns(ipnsName) {
3073
+ this.ipnsRecords.delete(ipnsName);
3074
+ }
3075
+ // ---------------------------------------------------------------------------
3076
+ // Content Cache (infinite TTL - content is immutable by CID)
3077
+ // ---------------------------------------------------------------------------
3078
+ getContent(cid) {
3079
+ const entry = this.content.get(cid);
3080
+ return entry?.data ?? null;
3081
+ }
3082
+ setContent(cid, data) {
3083
+ this.content.set(cid, {
3084
+ data,
3085
+ timestamp: Date.now()
3086
+ });
3087
+ }
3088
+ // ---------------------------------------------------------------------------
3089
+ // Gateway Failure Tracking (Circuit Breaker)
3090
+ // ---------------------------------------------------------------------------
3091
+ /**
3092
+ * Record a gateway failure. After threshold consecutive failures,
3093
+ * the gateway enters cooldown and is considered unhealthy.
3094
+ */
3095
+ recordGatewayFailure(gateway) {
3096
+ const existing = this.gatewayFailures.get(gateway);
3097
+ this.gatewayFailures.set(gateway, {
3098
+ count: (existing?.count ?? 0) + 1,
3099
+ lastFailure: Date.now()
3100
+ });
3101
+ }
3102
+ /** Reset failure count for a gateway (on successful request) */
3103
+ recordGatewaySuccess(gateway) {
3104
+ this.gatewayFailures.delete(gateway);
3105
+ }
3106
+ /**
3107
+ * Check if a gateway is currently in circuit breaker cooldown.
3108
+ * A gateway is considered unhealthy if it has had >= threshold
3109
+ * consecutive failures and the cooldown period hasn't elapsed.
3110
+ */
3111
+ isGatewayInCooldown(gateway) {
3112
+ const failure = this.gatewayFailures.get(gateway);
3113
+ if (!failure) return false;
3114
+ if (failure.count < this.failureThreshold) return false;
3115
+ const elapsed = Date.now() - failure.lastFailure;
3116
+ if (elapsed >= this.failureCooldownMs) {
3117
+ this.gatewayFailures.delete(gateway);
3118
+ return false;
3119
+ }
3120
+ return true;
3121
+ }
3122
+ // ---------------------------------------------------------------------------
3123
+ // Known-Fresh Flag (FAST mode optimization)
3124
+ // ---------------------------------------------------------------------------
3125
+ /**
3126
+ * Mark IPNS cache as "known-fresh" (after local publish or push notification).
3127
+ * Within the fresh window, we can skip network resolution.
3128
+ */
3129
+ markIpnsFresh(ipnsName) {
3130
+ this.knownFreshTimestamps.set(ipnsName, Date.now());
3131
+ }
3132
+ /**
3133
+ * Check if the cache is known-fresh (within the fresh window).
3134
+ */
3135
+ isIpnsKnownFresh(ipnsName) {
3136
+ const timestamp = this.knownFreshTimestamps.get(ipnsName);
3137
+ if (!timestamp) return false;
3138
+ if (Date.now() - timestamp > this.knownFreshWindowMs) {
3139
+ this.knownFreshTimestamps.delete(ipnsName);
3140
+ return false;
3141
+ }
3142
+ return true;
3143
+ }
3144
+ // ---------------------------------------------------------------------------
3145
+ // Cache Management
3146
+ // ---------------------------------------------------------------------------
3147
+ clear() {
3148
+ this.ipnsRecords.clear();
3149
+ this.content.clear();
3150
+ this.gatewayFailures.clear();
3151
+ this.knownFreshTimestamps.clear();
3152
+ }
3153
+ };
3154
+
3155
+ // impl/shared/ipfs/ipfs-http-client.ts
3156
+ var DEFAULT_CONNECTIVITY_TIMEOUT_MS = 5e3;
3157
+ var DEFAULT_FETCH_TIMEOUT_MS = 15e3;
3158
+ var DEFAULT_RESOLVE_TIMEOUT_MS = 1e4;
3159
+ var DEFAULT_PUBLISH_TIMEOUT_MS = 3e4;
3160
+ var DEFAULT_GATEWAY_PATH_TIMEOUT_MS = 3e3;
3161
+ var DEFAULT_ROUTING_API_TIMEOUT_MS = 2e3;
3162
+ var IpfsHttpClient = class {
3163
+ gateways;
3164
+ fetchTimeoutMs;
3165
+ resolveTimeoutMs;
3166
+ publishTimeoutMs;
3167
+ connectivityTimeoutMs;
3168
+ debug;
3169
+ cache;
3170
+ constructor(config, cache) {
3171
+ this.gateways = config.gateways;
3172
+ this.fetchTimeoutMs = config.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
3173
+ this.resolveTimeoutMs = config.resolveTimeoutMs ?? DEFAULT_RESOLVE_TIMEOUT_MS;
3174
+ this.publishTimeoutMs = config.publishTimeoutMs ?? DEFAULT_PUBLISH_TIMEOUT_MS;
3175
+ this.connectivityTimeoutMs = config.connectivityTimeoutMs ?? DEFAULT_CONNECTIVITY_TIMEOUT_MS;
3176
+ this.debug = config.debug ?? false;
3177
+ this.cache = cache;
3178
+ }
3179
+ // ---------------------------------------------------------------------------
3180
+ // Public Accessors
3181
+ // ---------------------------------------------------------------------------
3182
+ /**
3183
+ * Get configured gateway URLs.
3184
+ */
3185
+ getGateways() {
3186
+ return [...this.gateways];
3187
+ }
3188
+ // ---------------------------------------------------------------------------
3189
+ // Gateway Health
3190
+ // ---------------------------------------------------------------------------
3191
+ /**
3192
+ * Test connectivity to a single gateway.
3193
+ */
3194
+ async testConnectivity(gateway) {
3195
+ const start = Date.now();
3196
+ try {
3197
+ const response = await this.fetchWithTimeout(
3198
+ `${gateway}/api/v0/version`,
3199
+ this.connectivityTimeoutMs,
3200
+ { method: "POST" }
3201
+ );
3202
+ if (!response.ok) {
3203
+ return { gateway, healthy: false, error: `HTTP ${response.status}` };
3204
+ }
3205
+ return {
3206
+ gateway,
3207
+ healthy: true,
3208
+ responseTimeMs: Date.now() - start
3209
+ };
3210
+ } catch (error) {
3211
+ return {
3212
+ gateway,
3213
+ healthy: false,
3214
+ error: error instanceof Error ? error.message : String(error)
3215
+ };
3216
+ }
3217
+ }
3218
+ /**
3219
+ * Find healthy gateways from the configured list.
3220
+ */
3221
+ async findHealthyGateways() {
3222
+ const results = await Promise.allSettled(
3223
+ this.gateways.map((gw) => this.testConnectivity(gw))
3224
+ );
3225
+ return results.filter((r) => r.status === "fulfilled" && r.value.healthy).map((r) => r.value.gateway);
3226
+ }
3227
+ /**
3228
+ * Get gateways that are not in circuit breaker cooldown.
3229
+ */
3230
+ getAvailableGateways() {
3231
+ return this.gateways.filter((gw) => !this.cache.isGatewayInCooldown(gw));
3232
+ }
3233
+ // ---------------------------------------------------------------------------
3234
+ // Content Upload
3235
+ // ---------------------------------------------------------------------------
3236
+ /**
3237
+ * Upload JSON content to IPFS.
3238
+ * Tries all gateways in parallel, returns first success.
3239
+ */
3240
+ async upload(data, gateways) {
3241
+ const targets = gateways ?? this.getAvailableGateways();
3242
+ if (targets.length === 0) {
3243
+ throw new IpfsError("No gateways available for upload", "NETWORK_ERROR");
3244
+ }
3245
+ const jsonBytes = new TextEncoder().encode(JSON.stringify(data));
3246
+ const promises = targets.map(async (gateway) => {
3247
+ try {
3248
+ const formData = new FormData();
3249
+ formData.append("file", new Blob([jsonBytes], { type: "application/json" }), "data.json");
3250
+ const response = await this.fetchWithTimeout(
3251
+ `${gateway}/api/v0/add?pin=true&cid-version=1`,
3252
+ this.publishTimeoutMs,
3253
+ { method: "POST", body: formData }
3254
+ );
3255
+ if (!response.ok) {
3256
+ throw new IpfsError(
3257
+ `Upload failed: HTTP ${response.status}`,
3258
+ classifyHttpStatus(response.status),
3259
+ gateway
3260
+ );
3261
+ }
3262
+ const result = await response.json();
3263
+ this.cache.recordGatewaySuccess(gateway);
3264
+ this.log(`Uploaded to ${gateway}: CID=${result.Hash}`);
3265
+ return { cid: result.Hash, gateway };
3266
+ } catch (error) {
3267
+ if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
3268
+ this.cache.recordGatewayFailure(gateway);
3269
+ }
3270
+ throw error;
3271
+ }
3272
+ });
3273
+ try {
3274
+ const result = await Promise.any(promises);
3275
+ return { cid: result.cid };
3276
+ } catch (error) {
3277
+ if (error instanceof AggregateError) {
3278
+ throw new IpfsError(
3279
+ `Upload failed on all gateways: ${error.errors.map((e) => e.message).join("; ")}`,
3280
+ "NETWORK_ERROR"
3281
+ );
3282
+ }
3283
+ throw error;
3284
+ }
3285
+ }
3286
+ // ---------------------------------------------------------------------------
3287
+ // Content Fetch
3288
+ // ---------------------------------------------------------------------------
3289
+ /**
3290
+ * Fetch content by CID from IPFS gateways.
3291
+ * Checks content cache first. Races all gateways for fastest response.
3292
+ */
3293
+ async fetchContent(cid, gateways) {
3294
+ const cached = this.cache.getContent(cid);
3295
+ if (cached) {
3296
+ this.log(`Content cache hit for CID=${cid}`);
3297
+ return cached;
3298
+ }
3299
+ const targets = gateways ?? this.getAvailableGateways();
3300
+ if (targets.length === 0) {
3301
+ throw new IpfsError("No gateways available for fetch", "NETWORK_ERROR");
3302
+ }
3303
+ const promises = targets.map(async (gateway) => {
3304
+ try {
3305
+ const response = await this.fetchWithTimeout(
3306
+ `${gateway}/ipfs/${cid}`,
3307
+ this.fetchTimeoutMs,
3308
+ { headers: { Accept: "application/octet-stream" } }
3309
+ );
3310
+ if (!response.ok) {
3311
+ const body = await response.text().catch(() => "");
3312
+ throw new IpfsError(
3313
+ `Fetch failed: HTTP ${response.status}`,
3314
+ classifyHttpStatus(response.status, body),
3315
+ gateway
3316
+ );
3317
+ }
3318
+ const data = await response.json();
3319
+ this.cache.recordGatewaySuccess(gateway);
3320
+ this.cache.setContent(cid, data);
3321
+ this.log(`Fetched from ${gateway}: CID=${cid}`);
3322
+ return data;
3323
+ } catch (error) {
3324
+ if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
3325
+ this.cache.recordGatewayFailure(gateway);
3326
+ }
3327
+ throw error;
3328
+ }
3329
+ });
3330
+ try {
3331
+ return await Promise.any(promises);
3332
+ } catch (error) {
3333
+ if (error instanceof AggregateError) {
3334
+ throw new IpfsError(
3335
+ `Fetch failed on all gateways for CID=${cid}`,
3336
+ "NETWORK_ERROR"
3337
+ );
3338
+ }
3339
+ throw error;
3340
+ }
3341
+ }
3342
+ // ---------------------------------------------------------------------------
3343
+ // IPNS Resolution
3344
+ // ---------------------------------------------------------------------------
3345
+ /**
3346
+ * Resolve IPNS via Routing API (returns record with sequence number).
3347
+ * POST /api/v0/routing/get?arg=/ipns/{name}
3348
+ */
3349
+ async resolveIpnsViaRoutingApi(gateway, ipnsName, timeoutMs = DEFAULT_ROUTING_API_TIMEOUT_MS) {
3350
+ try {
3351
+ const response = await this.fetchWithTimeout(
3352
+ `${gateway}/api/v0/routing/get?arg=/ipns/${ipnsName}`,
3353
+ timeoutMs,
3354
+ { method: "POST" }
3355
+ );
3356
+ if (!response.ok) {
3357
+ const body = await response.text().catch(() => "");
3358
+ const category = classifyHttpStatus(response.status, body);
3359
+ if (category === "NOT_FOUND") return null;
3360
+ throw new IpfsError(`Routing API: HTTP ${response.status}`, category, gateway);
3361
+ }
3362
+ const text = await response.text();
3363
+ const parsed = await parseRoutingApiResponse(text);
3364
+ if (!parsed) return null;
3365
+ this.cache.recordGatewaySuccess(gateway);
3366
+ return {
3367
+ cid: parsed.cid,
3368
+ sequence: parsed.sequence,
3369
+ gateway,
3370
+ recordData: parsed.recordData
3371
+ };
3372
+ } catch (error) {
3373
+ if (error instanceof IpfsError) throw error;
3374
+ const category = classifyFetchError(error);
3375
+ if (category !== "NOT_FOUND") {
3376
+ this.cache.recordGatewayFailure(gateway);
3377
+ }
3378
+ return null;
3379
+ }
3380
+ }
3381
+ /**
3382
+ * Resolve IPNS via gateway path (simpler, no sequence number).
3383
+ * GET /ipns/{name}?format=dag-json
3384
+ */
3385
+ async resolveIpnsViaGatewayPath(gateway, ipnsName, timeoutMs = DEFAULT_GATEWAY_PATH_TIMEOUT_MS) {
3386
+ try {
3387
+ const response = await this.fetchWithTimeout(
3388
+ `${gateway}/ipns/${ipnsName}`,
3389
+ timeoutMs,
3390
+ { headers: { Accept: "application/json" } }
3391
+ );
3392
+ if (!response.ok) return null;
3393
+ const content = await response.json();
3394
+ const cidHeader = response.headers.get("X-Ipfs-Path");
3395
+ if (cidHeader) {
3396
+ const match = cidHeader.match(/\/ipfs\/([a-zA-Z0-9]+)/);
3397
+ if (match) {
3398
+ this.cache.recordGatewaySuccess(gateway);
3399
+ return { cid: match[1], content };
3400
+ }
3401
+ }
3402
+ return { cid: "", content };
3403
+ } catch {
3404
+ return null;
3405
+ }
3406
+ }
3407
+ /**
3408
+ * Progressive IPNS resolution across all gateways.
3409
+ * Queries all gateways in parallel, returns highest sequence number.
3410
+ */
3411
+ async resolveIpns(ipnsName, gateways) {
3412
+ const targets = gateways ?? this.getAvailableGateways();
3413
+ if (targets.length === 0) {
3414
+ return { best: null, allResults: [], respondedCount: 0, totalGateways: 0 };
3415
+ }
3416
+ const results = [];
3417
+ let respondedCount = 0;
3418
+ const promises = targets.map(async (gateway) => {
3419
+ const result = await this.resolveIpnsViaRoutingApi(
3420
+ gateway,
3421
+ ipnsName,
3422
+ this.resolveTimeoutMs
3423
+ );
3424
+ if (result) results.push(result);
3425
+ respondedCount++;
3426
+ return result;
3427
+ });
3428
+ await Promise.race([
3429
+ Promise.allSettled(promises),
3430
+ new Promise((resolve) => setTimeout(resolve, this.resolveTimeoutMs + 1e3))
3431
+ ]);
3432
+ let best = null;
3433
+ for (const result of results) {
3434
+ if (!best || result.sequence > best.sequence) {
3435
+ best = result;
3436
+ }
3437
+ }
3438
+ if (best) {
3439
+ this.cache.setIpnsRecord(ipnsName, best);
3440
+ }
3441
+ return {
3442
+ best,
3443
+ allResults: results,
3444
+ respondedCount,
3445
+ totalGateways: targets.length
3446
+ };
3447
+ }
3448
+ // ---------------------------------------------------------------------------
3449
+ // IPNS Publishing
3450
+ // ---------------------------------------------------------------------------
3451
+ /**
3452
+ * Publish IPNS record to a single gateway via routing API.
3453
+ */
3454
+ async publishIpnsViaRoutingApi(gateway, ipnsName, marshalledRecord, timeoutMs = DEFAULT_PUBLISH_TIMEOUT_MS) {
3455
+ try {
3456
+ const formData = new FormData();
3457
+ formData.append(
3458
+ "file",
3459
+ new Blob([new Uint8Array(marshalledRecord)]),
3460
+ "record"
3461
+ );
3462
+ const response = await this.fetchWithTimeout(
3463
+ `${gateway}/api/v0/routing/put?arg=/ipns/${ipnsName}&allow-offline=true`,
3464
+ timeoutMs,
3465
+ { method: "POST", body: formData }
3466
+ );
3467
+ if (!response.ok) {
3468
+ const errorText = await response.text().catch(() => "");
3469
+ throw new IpfsError(
3470
+ `IPNS publish: HTTP ${response.status}: ${errorText.slice(0, 100)}`,
3471
+ classifyHttpStatus(response.status, errorText),
3472
+ gateway
3473
+ );
3474
+ }
3475
+ this.cache.recordGatewaySuccess(gateway);
3476
+ this.log(`IPNS published to ${gateway}: ${ipnsName}`);
3477
+ return true;
3478
+ } catch (error) {
3479
+ if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
3480
+ this.cache.recordGatewayFailure(gateway);
3481
+ }
3482
+ this.log(`IPNS publish to ${gateway} failed: ${error}`);
3483
+ return false;
3484
+ }
3485
+ }
3486
+ /**
3487
+ * Publish IPNS record to all gateways in parallel.
3488
+ */
3489
+ async publishIpns(ipnsName, marshalledRecord, gateways) {
3490
+ const targets = gateways ?? this.getAvailableGateways();
3491
+ if (targets.length === 0) {
3492
+ return { success: false, error: "No gateways available" };
3493
+ }
3494
+ const results = await Promise.allSettled(
3495
+ targets.map((gw) => this.publishIpnsViaRoutingApi(gw, ipnsName, marshalledRecord, this.publishTimeoutMs))
3496
+ );
3497
+ const successfulGateways = [];
3498
+ results.forEach((result, index) => {
3499
+ if (result.status === "fulfilled" && result.value) {
3500
+ successfulGateways.push(targets[index]);
3501
+ }
3502
+ });
3503
+ return {
3504
+ success: successfulGateways.length > 0,
3505
+ ipnsName,
3506
+ successfulGateways,
3507
+ error: successfulGateways.length === 0 ? "All gateways failed" : void 0
3508
+ };
3509
+ }
3510
+ // ---------------------------------------------------------------------------
3511
+ // IPNS Verification
3512
+ // ---------------------------------------------------------------------------
3513
+ /**
3514
+ * Verify IPNS record persistence after publishing.
3515
+ * Retries resolution to confirm the record was accepted.
3516
+ */
3517
+ async verifyIpnsRecord(ipnsName, expectedSeq, expectedCid, retries = 3, delayMs = 1e3) {
3518
+ for (let i = 0; i < retries; i++) {
3519
+ if (i > 0) {
3520
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
3521
+ }
3522
+ const { best } = await this.resolveIpns(ipnsName);
3523
+ if (best && best.sequence >= expectedSeq && best.cid === expectedCid) {
3524
+ return true;
3525
+ }
3526
+ }
3527
+ return false;
3528
+ }
3529
+ // ---------------------------------------------------------------------------
3530
+ // Helpers
3531
+ // ---------------------------------------------------------------------------
3532
+ async fetchWithTimeout(url, timeoutMs, options) {
3533
+ const controller = new AbortController();
3534
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
3535
+ try {
3536
+ return await fetch(url, {
3537
+ ...options,
3538
+ signal: controller.signal
3539
+ });
3540
+ } finally {
3541
+ clearTimeout(timer);
3542
+ }
3543
+ }
3544
+ log(message) {
3545
+ if (this.debug) {
3546
+ console.log(`[IPFS-HTTP] ${message}`);
3547
+ }
3548
+ }
3549
+ };
3550
+
3551
+ // impl/shared/ipfs/txf-merge.ts
3552
+ function mergeTxfData(local, remote) {
3553
+ let added = 0;
3554
+ let removed = 0;
3555
+ let conflicts = 0;
3556
+ const localVersion = local._meta?.version ?? 0;
3557
+ const remoteVersion = remote._meta?.version ?? 0;
3558
+ const baseMeta = localVersion >= remoteVersion ? local._meta : remote._meta;
3559
+ const mergedMeta = {
3560
+ ...baseMeta,
3561
+ version: Math.max(localVersion, remoteVersion) + 1,
3562
+ updatedAt: Date.now()
3563
+ };
3564
+ const mergedTombstones = mergeTombstones(
3565
+ local._tombstones ?? [],
3566
+ remote._tombstones ?? []
3567
+ );
3568
+ const tombstoneKeys = new Set(
3569
+ mergedTombstones.map((t) => `${t.tokenId}:${t.stateHash}`)
3570
+ );
3571
+ const localTokenKeys = getTokenKeys(local);
3572
+ const remoteTokenKeys = getTokenKeys(remote);
3573
+ const allTokenKeys = /* @__PURE__ */ new Set([...localTokenKeys, ...remoteTokenKeys]);
3574
+ const mergedTokens = {};
3575
+ for (const key of allTokenKeys) {
3576
+ const tokenId = key.startsWith("_") ? key.slice(1) : key;
3577
+ const localToken = local[key];
3578
+ const remoteToken = remote[key];
3579
+ if (isTokenTombstoned(tokenId, localToken, remoteToken, tombstoneKeys)) {
3580
+ if (localTokenKeys.has(key)) removed++;
3581
+ continue;
3582
+ }
3583
+ if (localToken && !remoteToken) {
3584
+ mergedTokens[key] = localToken;
3585
+ } else if (!localToken && remoteToken) {
3586
+ mergedTokens[key] = remoteToken;
3587
+ added++;
3588
+ } else if (localToken && remoteToken) {
3589
+ mergedTokens[key] = localToken;
3590
+ conflicts++;
3591
+ }
3592
+ }
3593
+ const mergedOutbox = mergeArrayById(
3594
+ local._outbox ?? [],
3595
+ remote._outbox ?? [],
3596
+ "id"
3597
+ );
3598
+ const mergedSent = mergeArrayById(
3599
+ local._sent ?? [],
3600
+ remote._sent ?? [],
3601
+ "tokenId"
3602
+ );
3603
+ const mergedInvalid = mergeArrayById(
3604
+ local._invalid ?? [],
3605
+ remote._invalid ?? [],
3606
+ "tokenId"
3607
+ );
3608
+ const localNametags = local._nametags ?? [];
3609
+ const remoteNametags = remote._nametags ?? [];
3610
+ const mergedNametags = mergeNametagsByName(localNametags, remoteNametags);
3611
+ const merged = {
3612
+ _meta: mergedMeta,
3613
+ _tombstones: mergedTombstones.length > 0 ? mergedTombstones : void 0,
3614
+ _nametags: mergedNametags.length > 0 ? mergedNametags : void 0,
3615
+ _outbox: mergedOutbox.length > 0 ? mergedOutbox : void 0,
3616
+ _sent: mergedSent.length > 0 ? mergedSent : void 0,
3617
+ _invalid: mergedInvalid.length > 0 ? mergedInvalid : void 0,
3618
+ ...mergedTokens
3619
+ };
3620
+ return { merged, added, removed, conflicts };
3621
+ }
3622
+ function mergeTombstones(local, remote) {
3623
+ const merged = /* @__PURE__ */ new Map();
3624
+ for (const tombstone of [...local, ...remote]) {
3625
+ const key = `${tombstone.tokenId}:${tombstone.stateHash}`;
3626
+ const existing = merged.get(key);
3627
+ if (!existing || tombstone.timestamp > existing.timestamp) {
3628
+ merged.set(key, tombstone);
3629
+ }
3630
+ }
3631
+ return Array.from(merged.values());
3632
+ }
3633
+ function getTokenKeys(data) {
3634
+ const reservedKeys = /* @__PURE__ */ new Set([
3635
+ "_meta",
3636
+ "_tombstones",
3637
+ "_outbox",
3638
+ "_sent",
3639
+ "_invalid",
3640
+ "_nametag",
3641
+ "_nametags",
3642
+ "_mintOutbox",
3643
+ "_invalidatedNametags",
3644
+ "_integrity"
3645
+ ]);
3646
+ const keys = /* @__PURE__ */ new Set();
3647
+ for (const key of Object.keys(data)) {
3648
+ if (reservedKeys.has(key)) continue;
3649
+ if (key.startsWith("archived-") || key.startsWith("_forked_")) continue;
3650
+ keys.add(key);
3651
+ }
3652
+ return keys;
3653
+ }
3654
+ function isTokenTombstoned(tokenId, localToken, remoteToken, tombstoneKeys) {
3655
+ for (const key of tombstoneKeys) {
3656
+ if (key.startsWith(`${tokenId}:`)) {
3657
+ return true;
3658
+ }
3659
+ }
3660
+ void localToken;
3661
+ void remoteToken;
3662
+ return false;
3663
+ }
3664
+ function mergeNametagsByName(local, remote) {
3665
+ const seen = /* @__PURE__ */ new Map();
3666
+ for (const item of local) {
3667
+ if (item.name) seen.set(item.name, item);
3668
+ }
3669
+ for (const item of remote) {
3670
+ if (item.name && !seen.has(item.name)) {
3671
+ seen.set(item.name, item);
3672
+ }
3673
+ }
3674
+ return Array.from(seen.values());
3675
+ }
3676
+ function mergeArrayById(local, remote, idField) {
3677
+ const seen = /* @__PURE__ */ new Map();
3678
+ for (const item of local) {
3679
+ const id = item[idField];
3680
+ if (id !== void 0) {
3681
+ seen.set(id, item);
3682
+ }
3683
+ }
3684
+ for (const item of remote) {
3685
+ const id = item[idField];
3686
+ if (id !== void 0 && !seen.has(id)) {
3687
+ seen.set(id, item);
3688
+ }
3689
+ }
3690
+ return Array.from(seen.values());
3691
+ }
3692
+
3693
+ // impl/shared/ipfs/ipns-subscription-client.ts
3694
+ var IpnsSubscriptionClient = class {
3695
+ ws = null;
3696
+ subscriptions = /* @__PURE__ */ new Map();
3697
+ reconnectTimeout = null;
3698
+ pingInterval = null;
3699
+ fallbackPollInterval = null;
3700
+ wsUrl;
3701
+ createWebSocket;
3702
+ pingIntervalMs;
3703
+ initialReconnectDelayMs;
3704
+ maxReconnectDelayMs;
3705
+ debugEnabled;
3706
+ reconnectAttempts = 0;
3707
+ isConnecting = false;
3708
+ connectionOpenedAt = 0;
3709
+ destroyed = false;
3710
+ /** Minimum stable connection time before resetting backoff (30 seconds) */
3711
+ minStableConnectionMs = 3e4;
3712
+ fallbackPollFn = null;
3713
+ fallbackPollIntervalMs = 0;
3714
+ constructor(config) {
3715
+ this.wsUrl = config.wsUrl;
3716
+ this.createWebSocket = config.createWebSocket;
3717
+ this.pingIntervalMs = config.pingIntervalMs ?? 3e4;
3718
+ this.initialReconnectDelayMs = config.reconnectDelayMs ?? 5e3;
3719
+ this.maxReconnectDelayMs = config.maxReconnectDelayMs ?? 6e4;
3720
+ this.debugEnabled = config.debug ?? false;
3721
+ }
3722
+ // ---------------------------------------------------------------------------
3723
+ // Public API
3724
+ // ---------------------------------------------------------------------------
3725
+ /**
3726
+ * Subscribe to IPNS updates for a specific name.
3727
+ * Automatically connects the WebSocket if not already connected.
3728
+ * If WebSocket is connecting, the name will be subscribed once connected.
3729
+ */
3730
+ subscribe(ipnsName, callback) {
3731
+ if (!ipnsName || typeof ipnsName !== "string") {
3732
+ this.log("Invalid IPNS name for subscription");
3733
+ return () => {
3734
+ };
3735
+ }
3736
+ const isNewSubscription = !this.subscriptions.has(ipnsName);
3737
+ if (isNewSubscription) {
3738
+ this.subscriptions.set(ipnsName, /* @__PURE__ */ new Set());
3739
+ }
3740
+ this.subscriptions.get(ipnsName).add(callback);
3741
+ if (isNewSubscription && this.ws?.readyState === WebSocketReadyState.OPEN) {
3742
+ this.sendSubscribe([ipnsName]);
3743
+ }
3744
+ if (!this.ws || this.ws.readyState !== WebSocketReadyState.OPEN) {
3745
+ this.connect();
3746
+ }
3747
+ return () => {
3748
+ const callbacks = this.subscriptions.get(ipnsName);
3749
+ if (callbacks) {
3750
+ callbacks.delete(callback);
3751
+ if (callbacks.size === 0) {
3752
+ this.subscriptions.delete(ipnsName);
3753
+ if (this.ws?.readyState === WebSocketReadyState.OPEN) {
3754
+ this.sendUnsubscribe([ipnsName]);
3755
+ }
3756
+ if (this.subscriptions.size === 0) {
3757
+ this.disconnect();
3758
+ }
3759
+ }
3760
+ }
3761
+ };
3762
+ }
3763
+ /**
3764
+ * Register a convenience update callback for all subscriptions.
3765
+ * Returns an unsubscribe function.
3766
+ */
3767
+ onUpdate(callback) {
3768
+ if (!this.subscriptions.has("*")) {
3769
+ this.subscriptions.set("*", /* @__PURE__ */ new Set());
3770
+ }
3771
+ this.subscriptions.get("*").add(callback);
3772
+ return () => {
3773
+ const callbacks = this.subscriptions.get("*");
3774
+ if (callbacks) {
3775
+ callbacks.delete(callback);
3776
+ if (callbacks.size === 0) {
3777
+ this.subscriptions.delete("*");
3778
+ }
3779
+ }
3780
+ };
3781
+ }
3782
+ /**
3783
+ * Set a fallback poll function to use when WebSocket is disconnected.
3784
+ * The poll function will be called at the specified interval while WS is down.
3785
+ */
3786
+ setFallbackPoll(fn, intervalMs) {
3787
+ this.fallbackPollFn = fn;
3788
+ this.fallbackPollIntervalMs = intervalMs;
3789
+ if (!this.isConnected()) {
3790
+ this.startFallbackPolling();
3791
+ }
3792
+ }
3793
+ /**
3794
+ * Connect to the WebSocket server.
3795
+ */
3796
+ connect() {
3797
+ if (this.destroyed) return;
3798
+ if (this.ws?.readyState === WebSocketReadyState.OPEN || this.isConnecting) {
3799
+ return;
3800
+ }
3801
+ this.isConnecting = true;
3802
+ try {
3803
+ this.log(`Connecting to ${this.wsUrl}...`);
3804
+ this.ws = this.createWebSocket(this.wsUrl);
3805
+ this.ws.onopen = () => {
3806
+ this.log("WebSocket connected");
3807
+ this.isConnecting = false;
3808
+ this.connectionOpenedAt = Date.now();
3809
+ const names = Array.from(this.subscriptions.keys()).filter((n) => n !== "*");
3810
+ if (names.length > 0) {
3811
+ this.sendSubscribe(names);
3812
+ }
3813
+ this.startPingInterval();
3814
+ this.stopFallbackPolling();
3815
+ };
3816
+ this.ws.onmessage = (event) => {
3817
+ this.handleMessage(event.data);
3818
+ };
3819
+ this.ws.onclose = () => {
3820
+ const connectionDuration = this.connectionOpenedAt > 0 ? Date.now() - this.connectionOpenedAt : 0;
3821
+ const wasStable = connectionDuration >= this.minStableConnectionMs;
3822
+ this.log(`WebSocket closed (duration: ${Math.round(connectionDuration / 1e3)}s)`);
3823
+ this.isConnecting = false;
3824
+ this.connectionOpenedAt = 0;
3825
+ this.stopPingInterval();
3826
+ if (wasStable) {
3827
+ this.reconnectAttempts = 0;
3828
+ }
3829
+ this.startFallbackPolling();
3830
+ this.scheduleReconnect();
3831
+ };
3832
+ this.ws.onerror = () => {
3833
+ this.log("WebSocket error");
3834
+ this.isConnecting = false;
3835
+ };
3836
+ } catch (e) {
3837
+ this.log(`Failed to connect: ${e}`);
3838
+ this.isConnecting = false;
3839
+ this.startFallbackPolling();
3840
+ this.scheduleReconnect();
3841
+ }
3842
+ }
3843
+ /**
3844
+ * Disconnect from the WebSocket server and clean up.
3845
+ */
3846
+ disconnect() {
3847
+ this.destroyed = true;
3848
+ if (this.reconnectTimeout) {
3849
+ clearTimeout(this.reconnectTimeout);
3850
+ this.reconnectTimeout = null;
3851
+ }
3852
+ this.stopPingInterval();
3853
+ this.stopFallbackPolling();
3854
+ if (this.ws) {
3855
+ this.ws.onopen = null;
3856
+ this.ws.onclose = null;
3857
+ this.ws.onerror = null;
3858
+ this.ws.onmessage = null;
3859
+ this.ws.close();
3860
+ this.ws = null;
3861
+ }
3862
+ this.isConnecting = false;
3863
+ this.reconnectAttempts = 0;
3864
+ }
3865
+ /**
3866
+ * Check if connected to the WebSocket server.
3867
+ */
3868
+ isConnected() {
3869
+ return this.ws?.readyState === WebSocketReadyState.OPEN;
3870
+ }
3871
+ // ---------------------------------------------------------------------------
3872
+ // Internal: Message Handling
3873
+ // ---------------------------------------------------------------------------
3874
+ handleMessage(data) {
3875
+ try {
3876
+ const message = JSON.parse(data);
3877
+ switch (message.type) {
3878
+ case "update":
3879
+ if (message.name && message.sequence !== void 0) {
3880
+ this.notifySubscribers({
3881
+ type: "update",
3882
+ name: message.name,
3883
+ sequence: message.sequence,
3884
+ cid: message.cid ?? "",
3885
+ timestamp: message.timestamp || (/* @__PURE__ */ new Date()).toISOString()
3886
+ });
3887
+ }
3888
+ break;
3889
+ case "subscribed":
3890
+ this.log(`Subscribed to ${message.names?.length || 0} names`);
3891
+ break;
3892
+ case "unsubscribed":
3893
+ this.log(`Unsubscribed from ${message.names?.length || 0} names`);
3894
+ break;
3895
+ case "pong":
3896
+ break;
3897
+ case "error":
3898
+ this.log(`Server error: ${message.message}`);
3899
+ break;
3900
+ default:
3901
+ break;
3902
+ }
3903
+ } catch {
3904
+ this.log("Failed to parse message");
3905
+ }
3906
+ }
3907
+ notifySubscribers(update) {
3908
+ const callbacks = this.subscriptions.get(update.name);
3909
+ if (callbacks) {
3910
+ this.log(`Update: ${update.name.slice(0, 16)}... seq=${update.sequence}`);
3911
+ for (const callback of callbacks) {
3912
+ try {
3913
+ callback(update);
3914
+ } catch {
3915
+ }
3916
+ }
3917
+ }
3918
+ const globalCallbacks = this.subscriptions.get("*");
3919
+ if (globalCallbacks) {
3920
+ for (const callback of globalCallbacks) {
3921
+ try {
3922
+ callback(update);
3923
+ } catch {
3924
+ }
3925
+ }
3926
+ }
3927
+ }
3928
+ // ---------------------------------------------------------------------------
3929
+ // Internal: WebSocket Send
3930
+ // ---------------------------------------------------------------------------
3931
+ sendSubscribe(names) {
3932
+ if (this.ws?.readyState === WebSocketReadyState.OPEN) {
3933
+ this.ws.send(JSON.stringify({ action: "subscribe", names }));
3934
+ }
3935
+ }
3936
+ sendUnsubscribe(names) {
3937
+ if (this.ws?.readyState === WebSocketReadyState.OPEN) {
3938
+ this.ws.send(JSON.stringify({ action: "unsubscribe", names }));
3939
+ }
3940
+ }
3941
+ // ---------------------------------------------------------------------------
3942
+ // Internal: Reconnection
3943
+ // ---------------------------------------------------------------------------
3944
+ /**
3945
+ * Schedule reconnection with exponential backoff.
3946
+ * Sequence: 5s, 10s, 20s, 40s, 60s (capped)
3947
+ */
3948
+ scheduleReconnect() {
3949
+ if (this.destroyed || this.reconnectTimeout) return;
3950
+ const realSubscriptions = Array.from(this.subscriptions.keys()).filter((n) => n !== "*");
3951
+ if (realSubscriptions.length === 0) return;
3952
+ this.reconnectAttempts++;
3953
+ const delay = Math.min(
3954
+ this.initialReconnectDelayMs * Math.pow(2, this.reconnectAttempts - 1),
3955
+ this.maxReconnectDelayMs
3956
+ );
3957
+ this.log(`Reconnecting in ${(delay / 1e3).toFixed(1)}s (attempt ${this.reconnectAttempts})...`);
3958
+ this.reconnectTimeout = setTimeout(() => {
3959
+ this.reconnectTimeout = null;
3960
+ this.connect();
3961
+ }, delay);
3962
+ }
3963
+ // ---------------------------------------------------------------------------
3964
+ // Internal: Keepalive
3965
+ // ---------------------------------------------------------------------------
3966
+ startPingInterval() {
3967
+ this.stopPingInterval();
3968
+ this.pingInterval = setInterval(() => {
3969
+ if (this.ws?.readyState === WebSocketReadyState.OPEN) {
3970
+ this.ws.send(JSON.stringify({ action: "ping" }));
3971
+ }
3972
+ }, this.pingIntervalMs);
3973
+ }
3974
+ stopPingInterval() {
3975
+ if (this.pingInterval) {
3976
+ clearInterval(this.pingInterval);
3977
+ this.pingInterval = null;
3978
+ }
3979
+ }
3980
+ // ---------------------------------------------------------------------------
3981
+ // Internal: Fallback Polling
3982
+ // ---------------------------------------------------------------------------
3983
+ startFallbackPolling() {
3984
+ if (this.fallbackPollInterval || !this.fallbackPollFn || this.destroyed) return;
3985
+ this.log(`Starting fallback polling (${this.fallbackPollIntervalMs / 1e3}s interval)`);
3986
+ this.fallbackPollFn().catch(() => {
3987
+ });
3988
+ this.fallbackPollInterval = setInterval(() => {
3989
+ this.fallbackPollFn?.().catch(() => {
3990
+ });
3991
+ }, this.fallbackPollIntervalMs);
3992
+ }
3993
+ stopFallbackPolling() {
3994
+ if (this.fallbackPollInterval) {
3995
+ clearInterval(this.fallbackPollInterval);
3996
+ this.fallbackPollInterval = null;
3997
+ }
3998
+ }
3999
+ // ---------------------------------------------------------------------------
4000
+ // Internal: Logging
4001
+ // ---------------------------------------------------------------------------
4002
+ log(message) {
4003
+ if (this.debugEnabled) {
4004
+ console.log(`[IPNS-WS] ${message}`);
4005
+ }
4006
+ }
4007
+ };
4008
+
4009
+ // impl/shared/ipfs/write-behind-buffer.ts
4010
+ var AsyncSerialQueue = class {
4011
+ tail = Promise.resolve();
4012
+ /** Enqueue an async operation. Returns when it completes. */
4013
+ enqueue(fn) {
4014
+ let resolve;
4015
+ let reject;
4016
+ const promise = new Promise((res, rej) => {
4017
+ resolve = res;
4018
+ reject = rej;
4019
+ });
4020
+ this.tail = this.tail.then(
4021
+ () => fn().then(resolve, reject),
4022
+ () => fn().then(resolve, reject)
4023
+ );
4024
+ return promise;
4025
+ }
4026
+ };
4027
+ var WriteBuffer = class {
4028
+ /** Full TXF data from save() calls — latest wins */
4029
+ txfData = null;
4030
+ get isEmpty() {
4031
+ return this.txfData === null;
4032
+ }
4033
+ clear() {
4034
+ this.txfData = null;
4035
+ }
4036
+ /**
4037
+ * Merge another buffer's contents into this one (for rollback).
4038
+ * Existing (newer) mutations in `this` take precedence over `other`.
4039
+ */
4040
+ mergeFrom(other) {
4041
+ if (other.txfData && !this.txfData) {
4042
+ this.txfData = other.txfData;
4043
+ }
4044
+ }
4045
+ };
4046
+
4047
+ // impl/shared/ipfs/ipfs-storage-provider.ts
4048
+ var IpfsStorageProvider = class {
4049
+ id = "ipfs";
4050
+ name = "IPFS Storage";
4051
+ type = "p2p";
4052
+ status = "disconnected";
4053
+ identity = null;
4054
+ ipnsKeyPair = null;
4055
+ ipnsName = null;
4056
+ ipnsSequenceNumber = 0n;
4057
+ lastCid = null;
4058
+ lastKnownRemoteSequence = 0n;
4059
+ dataVersion = 0;
4060
+ /**
4061
+ * The CID currently stored on the sidecar for this IPNS name.
4062
+ * Used as `_meta.lastCid` in the next save to satisfy chain validation.
4063
+ * - null for bootstrap (first-ever save)
4064
+ * - set after every successful save() or load()
4065
+ */
4066
+ remoteCid = null;
4067
+ cache;
4068
+ httpClient;
4069
+ statePersistence;
4070
+ eventCallbacks = /* @__PURE__ */ new Set();
4071
+ debug;
4072
+ ipnsLifetimeMs;
4073
+ /** WebSocket factory for push subscriptions */
4074
+ createWebSocket;
4075
+ /** Override WS URL */
4076
+ wsUrl;
4077
+ /** Fallback poll interval (default: 90000) */
4078
+ fallbackPollIntervalMs;
4079
+ /** IPNS subscription client for push notifications */
4080
+ subscriptionClient = null;
4081
+ /** Unsubscribe function from subscription client */
4082
+ subscriptionUnsubscribe = null;
4083
+ /** Write-behind buffer: serializes flush / sync / shutdown */
4084
+ flushQueue = new AsyncSerialQueue();
4085
+ /** Pending mutations not yet flushed to IPFS */
4086
+ pendingBuffer = new WriteBuffer();
4087
+ /** Debounce timer for background flush */
4088
+ flushTimer = null;
4089
+ /** Debounce interval in ms */
4090
+ flushDebounceMs;
4091
+ /** Set to true during shutdown to prevent new flushes */
4092
+ isShuttingDown = false;
4093
+ constructor(config, statePersistence) {
4094
+ const gateways = config?.gateways ?? getIpfsGatewayUrls();
4095
+ this.debug = config?.debug ?? false;
4096
+ this.ipnsLifetimeMs = config?.ipnsLifetimeMs ?? 99 * 365 * 24 * 60 * 60 * 1e3;
4097
+ this.flushDebounceMs = config?.flushDebounceMs ?? 2e3;
4098
+ this.cache = new IpfsCache({
4099
+ ipnsTtlMs: config?.ipnsCacheTtlMs,
4100
+ failureCooldownMs: config?.circuitBreakerCooldownMs,
4101
+ failureThreshold: config?.circuitBreakerThreshold,
4102
+ knownFreshWindowMs: config?.knownFreshWindowMs
4103
+ });
4104
+ this.httpClient = new IpfsHttpClient({
4105
+ gateways,
4106
+ fetchTimeoutMs: config?.fetchTimeoutMs,
4107
+ resolveTimeoutMs: config?.resolveTimeoutMs,
4108
+ publishTimeoutMs: config?.publishTimeoutMs,
4109
+ connectivityTimeoutMs: config?.connectivityTimeoutMs,
4110
+ debug: this.debug
4111
+ }, this.cache);
4112
+ this.statePersistence = statePersistence ?? new InMemoryIpfsStatePersistence();
4113
+ this.createWebSocket = config?.createWebSocket;
4114
+ this.wsUrl = config?.wsUrl;
4115
+ this.fallbackPollIntervalMs = config?.fallbackPollIntervalMs ?? 9e4;
4116
+ }
4117
+ // ---------------------------------------------------------------------------
4118
+ // BaseProvider interface
4119
+ // ---------------------------------------------------------------------------
4120
+ async connect() {
4121
+ await this.initialize();
4122
+ }
4123
+ async disconnect() {
4124
+ await this.shutdown();
4125
+ }
4126
+ isConnected() {
4127
+ return this.status === "connected";
4128
+ }
4129
+ getStatus() {
4130
+ return this.status;
4131
+ }
4132
+ // ---------------------------------------------------------------------------
4133
+ // Identity & Initialization
4134
+ // ---------------------------------------------------------------------------
4135
+ setIdentity(identity) {
4136
+ this.identity = identity;
4137
+ }
4138
+ async initialize() {
4139
+ if (!this.identity) {
4140
+ this.log("Cannot initialize: no identity set");
4141
+ return false;
4142
+ }
4143
+ this.status = "connecting";
4144
+ this.emitEvent({ type: "storage:loading", timestamp: Date.now() });
4145
+ try {
4146
+ const { keyPair, ipnsName } = await deriveIpnsIdentity(this.identity.privateKey);
4147
+ this.ipnsKeyPair = keyPair;
4148
+ this.ipnsName = ipnsName;
4149
+ this.log(`IPNS name derived: ${ipnsName}`);
4150
+ const persisted = await this.statePersistence.load(ipnsName);
4151
+ if (persisted) {
4152
+ this.ipnsSequenceNumber = BigInt(persisted.sequenceNumber);
4153
+ this.lastCid = persisted.lastCid;
4154
+ this.remoteCid = persisted.lastCid;
4155
+ this.dataVersion = persisted.version;
4156
+ this.log(`Loaded persisted state: seq=${this.ipnsSequenceNumber}, cid=${this.lastCid}`);
4157
+ }
4158
+ if (this.createWebSocket) {
4159
+ try {
4160
+ const wsUrlFinal = this.wsUrl ?? this.deriveWsUrl();
4161
+ if (wsUrlFinal) {
4162
+ this.subscriptionClient = new IpnsSubscriptionClient({
4163
+ wsUrl: wsUrlFinal,
4164
+ createWebSocket: this.createWebSocket,
4165
+ debug: this.debug
4166
+ });
4167
+ this.subscriptionUnsubscribe = this.subscriptionClient.subscribe(
4168
+ ipnsName,
4169
+ (update) => {
4170
+ this.log(`Push update: seq=${update.sequence}, cid=${update.cid}`);
4171
+ this.emitEvent({
4172
+ type: "storage:remote-updated",
4173
+ timestamp: Date.now(),
4174
+ data: { name: update.name, sequence: update.sequence, cid: update.cid }
4175
+ });
4176
+ }
4177
+ );
4178
+ this.subscriptionClient.setFallbackPoll(
4179
+ () => this.pollForRemoteChanges(),
4180
+ this.fallbackPollIntervalMs
4181
+ );
4182
+ this.subscriptionClient.connect();
4183
+ }
4184
+ } catch (wsError) {
4185
+ this.log(`Failed to set up IPNS subscription: ${wsError}`);
4186
+ }
4187
+ }
4188
+ this.httpClient.findHealthyGateways().then((healthy) => {
4189
+ if (healthy.length > 0) {
4190
+ this.log(`${healthy.length} healthy gateway(s) found`);
4191
+ } else {
4192
+ this.log("Warning: no healthy gateways found");
4193
+ }
4194
+ }).catch(() => {
4195
+ });
4196
+ this.isShuttingDown = false;
4197
+ this.status = "connected";
4198
+ this.emitEvent({ type: "storage:loaded", timestamp: Date.now() });
4199
+ return true;
4200
+ } catch (error) {
4201
+ this.status = "error";
4202
+ this.emitEvent({
4203
+ type: "storage:error",
4204
+ timestamp: Date.now(),
4205
+ error: error instanceof Error ? error.message : String(error)
4206
+ });
4207
+ return false;
4208
+ }
4209
+ }
4210
+ async shutdown() {
4211
+ this.isShuttingDown = true;
4212
+ if (this.flushTimer) {
4213
+ clearTimeout(this.flushTimer);
4214
+ this.flushTimer = null;
4215
+ }
4216
+ await this.flushQueue.enqueue(async () => {
4217
+ if (!this.pendingBuffer.isEmpty) {
4218
+ try {
4219
+ await this.executeFlush();
4220
+ } catch {
4221
+ this.log("Final flush on shutdown failed (data may be lost)");
4222
+ }
4223
+ }
4224
+ });
4225
+ if (this.subscriptionUnsubscribe) {
4226
+ this.subscriptionUnsubscribe();
4227
+ this.subscriptionUnsubscribe = null;
4228
+ }
4229
+ if (this.subscriptionClient) {
4230
+ this.subscriptionClient.disconnect();
4231
+ this.subscriptionClient = null;
4232
+ }
4233
+ this.cache.clear();
4234
+ this.status = "disconnected";
4235
+ }
4236
+ // ---------------------------------------------------------------------------
4237
+ // Save (non-blocking — buffers data for async flush)
4238
+ // ---------------------------------------------------------------------------
4239
+ async save(data) {
4240
+ if (!this.ipnsKeyPair || !this.ipnsName) {
4241
+ return { success: false, error: "Not initialized", timestamp: Date.now() };
4242
+ }
4243
+ this.pendingBuffer.txfData = data;
4244
+ this.scheduleFlush();
4245
+ return { success: true, timestamp: Date.now() };
4246
+ }
4247
+ // ---------------------------------------------------------------------------
4248
+ // Internal: Blocking save (used by sync and executeFlush)
4249
+ // ---------------------------------------------------------------------------
4250
+ /**
4251
+ * Perform the actual upload + IPNS publish synchronously.
4252
+ * Called by executeFlush() and sync() — never by public save().
4253
+ */
4254
+ async _doSave(data) {
4255
+ if (!this.ipnsKeyPair || !this.ipnsName) {
4256
+ return { success: false, error: "Not initialized", timestamp: Date.now() };
4257
+ }
4258
+ this.emitEvent({ type: "storage:saving", timestamp: Date.now() });
4259
+ try {
4260
+ this.dataVersion++;
4261
+ const metaUpdate = {
4262
+ ...data._meta,
4263
+ version: this.dataVersion,
4264
+ ipnsName: this.ipnsName,
4265
+ updatedAt: Date.now()
4266
+ };
4267
+ if (this.remoteCid) {
4268
+ metaUpdate.lastCid = this.remoteCid;
4269
+ }
4270
+ const updatedData = { ...data, _meta: metaUpdate };
4271
+ const { cid } = await this.httpClient.upload(updatedData);
4272
+ this.log(`Content uploaded: CID=${cid}`);
4273
+ const baseSeq = this.ipnsSequenceNumber > this.lastKnownRemoteSequence ? this.ipnsSequenceNumber : this.lastKnownRemoteSequence;
4274
+ const newSeq = baseSeq + 1n;
4275
+ const marshalledRecord = await createSignedRecord(
4276
+ this.ipnsKeyPair,
4277
+ cid,
4278
+ newSeq,
4279
+ this.ipnsLifetimeMs
4280
+ );
4281
+ const publishResult = await this.httpClient.publishIpns(
4282
+ this.ipnsName,
4283
+ marshalledRecord
4284
+ );
4285
+ if (!publishResult.success) {
4286
+ this.dataVersion--;
4287
+ this.log(`IPNS publish failed: ${publishResult.error}`);
4288
+ return {
4289
+ success: false,
4290
+ error: publishResult.error ?? "IPNS publish failed",
4291
+ timestamp: Date.now()
4292
+ };
4293
+ }
4294
+ this.ipnsSequenceNumber = newSeq;
4295
+ this.lastCid = cid;
4296
+ this.remoteCid = cid;
4297
+ this.cache.setIpnsRecord(this.ipnsName, {
4298
+ cid,
4299
+ sequence: newSeq,
4300
+ gateway: "local"
4301
+ });
4302
+ this.cache.setContent(cid, updatedData);
4303
+ this.cache.markIpnsFresh(this.ipnsName);
4304
+ await this.statePersistence.save(this.ipnsName, {
4305
+ sequenceNumber: newSeq.toString(),
4306
+ lastCid: cid,
4307
+ version: this.dataVersion
4308
+ });
4309
+ this.emitEvent({
4310
+ type: "storage:saved",
4311
+ timestamp: Date.now(),
4312
+ data: { cid, sequence: newSeq.toString() }
4313
+ });
4314
+ this.log(`Saved: CID=${cid}, seq=${newSeq}`);
4315
+ return { success: true, cid, timestamp: Date.now() };
4316
+ } catch (error) {
4317
+ this.dataVersion--;
4318
+ const errorMessage = error instanceof Error ? error.message : String(error);
4319
+ this.emitEvent({
4320
+ type: "storage:error",
4321
+ timestamp: Date.now(),
4322
+ error: errorMessage
4323
+ });
4324
+ return { success: false, error: errorMessage, timestamp: Date.now() };
4325
+ }
4326
+ }
4327
+ // ---------------------------------------------------------------------------
4328
+ // Write-behind buffer: scheduling and flushing
4329
+ // ---------------------------------------------------------------------------
4330
+ /**
4331
+ * Schedule a debounced background flush.
4332
+ * Resets the timer on each call so rapid mutations coalesce.
4333
+ */
4334
+ scheduleFlush() {
4335
+ if (this.isShuttingDown) return;
4336
+ if (this.flushTimer) clearTimeout(this.flushTimer);
4337
+ this.flushTimer = setTimeout(() => {
4338
+ this.flushTimer = null;
4339
+ this.flushQueue.enqueue(() => this.executeFlush()).catch((err) => {
4340
+ this.log(`Background flush failed: ${err}`);
4341
+ });
4342
+ }, this.flushDebounceMs);
4343
+ }
4344
+ /**
4345
+ * Execute a flush of the pending buffer to IPFS.
4346
+ * Runs inside AsyncSerialQueue for concurrency safety.
4347
+ */
4348
+ async executeFlush() {
4349
+ if (this.pendingBuffer.isEmpty) return;
4350
+ const active = this.pendingBuffer;
4351
+ this.pendingBuffer = new WriteBuffer();
4352
+ try {
4353
+ const baseData = active.txfData ?? {
4354
+ _meta: { version: 0, address: this.identity?.directAddress ?? "", formatVersion: "2.0", updatedAt: 0 }
4355
+ };
4356
+ const result = await this._doSave(baseData);
4357
+ if (!result.success) {
4358
+ throw new Error(result.error ?? "Save failed");
4359
+ }
4360
+ this.log(`Flushed successfully: CID=${result.cid}`);
4361
+ } catch (error) {
4362
+ this.pendingBuffer.mergeFrom(active);
4363
+ const msg = error instanceof Error ? error.message : String(error);
4364
+ this.log(`Flush failed (will retry): ${msg}`);
4365
+ this.scheduleFlush();
4366
+ throw error;
4367
+ }
4368
+ }
4369
+ // ---------------------------------------------------------------------------
4370
+ // Load
4371
+ // ---------------------------------------------------------------------------
4372
+ async load(identifier) {
4373
+ if (!this.ipnsName && !identifier) {
4374
+ return { success: false, error: "Not initialized", source: "local", timestamp: Date.now() };
4375
+ }
4376
+ this.emitEvent({ type: "storage:loading", timestamp: Date.now() });
4377
+ try {
4378
+ if (identifier) {
4379
+ const data2 = await this.httpClient.fetchContent(identifier);
4380
+ return { success: true, data: data2, source: "remote", timestamp: Date.now() };
4381
+ }
4382
+ const ipnsName = this.ipnsName;
4383
+ if (this.cache.isIpnsKnownFresh(ipnsName)) {
4384
+ const cached = this.cache.getIpnsRecordIgnoreTtl(ipnsName);
4385
+ if (cached) {
4386
+ const content = this.cache.getContent(cached.cid);
4387
+ if (content) {
4388
+ this.log("Using known-fresh cached data");
4389
+ return { success: true, data: content, source: "cache", timestamp: Date.now() };
4390
+ }
4391
+ }
4392
+ }
4393
+ const cachedRecord = this.cache.getIpnsRecord(ipnsName);
4394
+ if (cachedRecord) {
4395
+ const content = this.cache.getContent(cachedRecord.cid);
4396
+ if (content) {
4397
+ this.log("IPNS cache hit");
4398
+ return { success: true, data: content, source: "cache", timestamp: Date.now() };
4399
+ }
4400
+ try {
4401
+ const data2 = await this.httpClient.fetchContent(cachedRecord.cid);
4402
+ return { success: true, data: data2, source: "remote", timestamp: Date.now() };
4403
+ } catch {
4404
+ }
4405
+ }
4406
+ const { best } = await this.httpClient.resolveIpns(ipnsName);
4407
+ if (!best) {
4408
+ this.log("IPNS record not found (new wallet?)");
4409
+ return { success: false, error: "IPNS record not found", source: "remote", timestamp: Date.now() };
4410
+ }
4411
+ if (best.sequence > this.lastKnownRemoteSequence) {
4412
+ this.lastKnownRemoteSequence = best.sequence;
4413
+ }
4414
+ this.remoteCid = best.cid;
4415
+ const data = await this.httpClient.fetchContent(best.cid);
4416
+ const remoteVersion = data?._meta?.version;
4417
+ if (typeof remoteVersion === "number" && remoteVersion > this.dataVersion) {
4418
+ this.dataVersion = remoteVersion;
4419
+ }
4420
+ this.emitEvent({
4421
+ type: "storage:loaded",
4422
+ timestamp: Date.now(),
4423
+ data: { cid: best.cid, sequence: best.sequence.toString() }
4424
+ });
4425
+ return { success: true, data, source: "remote", timestamp: Date.now() };
4426
+ } catch (error) {
4427
+ if (this.ipnsName) {
4428
+ const cached = this.cache.getIpnsRecordIgnoreTtl(this.ipnsName);
4429
+ if (cached) {
4430
+ const content = this.cache.getContent(cached.cid);
4431
+ if (content) {
4432
+ this.log("Network error, returning stale cache");
4433
+ return { success: true, data: content, source: "cache", timestamp: Date.now() };
4434
+ }
4435
+ }
4436
+ }
4437
+ const errorMessage = error instanceof Error ? error.message : String(error);
4438
+ this.emitEvent({
4439
+ type: "storage:error",
4440
+ timestamp: Date.now(),
4441
+ error: errorMessage
4442
+ });
4443
+ return { success: false, error: errorMessage, source: "remote", timestamp: Date.now() };
4444
+ }
4445
+ }
4446
+ // ---------------------------------------------------------------------------
4447
+ // Sync (enters serial queue to avoid concurrent IPNS conflicts)
4448
+ // ---------------------------------------------------------------------------
4449
+ async sync(localData) {
4450
+ return this.flushQueue.enqueue(async () => {
4451
+ if (this.flushTimer) {
4452
+ clearTimeout(this.flushTimer);
4453
+ this.flushTimer = null;
4454
+ }
4455
+ this.emitEvent({ type: "sync:started", timestamp: Date.now() });
4456
+ try {
4457
+ this.pendingBuffer.clear();
4458
+ const remoteResult = await this.load();
4459
+ if (!remoteResult.success || !remoteResult.data) {
4460
+ this.log("No remote data found, uploading local data");
4461
+ const saveResult2 = await this._doSave(localData);
4462
+ this.emitEvent({ type: "sync:completed", timestamp: Date.now() });
4463
+ return {
4464
+ success: saveResult2.success,
4465
+ merged: localData,
4466
+ added: 0,
4467
+ removed: 0,
4468
+ conflicts: 0,
4469
+ error: saveResult2.error
4470
+ };
4471
+ }
4472
+ const remoteData = remoteResult.data;
4473
+ const localVersion = localData._meta?.version ?? 0;
4474
+ const remoteVersion = remoteData._meta?.version ?? 0;
4475
+ if (localVersion === remoteVersion && this.lastCid) {
4476
+ this.log("Data is in sync (same version)");
4477
+ this.emitEvent({ type: "sync:completed", timestamp: Date.now() });
4478
+ return {
4479
+ success: true,
4480
+ merged: localData,
4481
+ added: 0,
4482
+ removed: 0,
4483
+ conflicts: 0
4484
+ };
4485
+ }
4486
+ this.log(`Merging: local v${localVersion} <-> remote v${remoteVersion}`);
4487
+ const { merged, added, removed, conflicts } = mergeTxfData(localData, remoteData);
4488
+ if (conflicts > 0) {
4489
+ this.emitEvent({
4490
+ type: "sync:conflict",
4491
+ timestamp: Date.now(),
4492
+ data: { conflicts }
4493
+ });
4494
+ }
4495
+ const saveResult = await this._doSave(merged);
4496
+ this.emitEvent({
4497
+ type: "sync:completed",
4498
+ timestamp: Date.now(),
4499
+ data: { added, removed, conflicts }
4500
+ });
4501
+ return {
4502
+ success: saveResult.success,
4503
+ merged,
4504
+ added,
4505
+ removed,
4506
+ conflicts,
4507
+ error: saveResult.error
4508
+ };
4509
+ } catch (error) {
4510
+ const errorMessage = error instanceof Error ? error.message : String(error);
4511
+ this.emitEvent({
4512
+ type: "sync:error",
4513
+ timestamp: Date.now(),
4514
+ error: errorMessage
4515
+ });
4516
+ return {
4517
+ success: false,
4518
+ added: 0,
4519
+ removed: 0,
4520
+ conflicts: 0,
4521
+ error: errorMessage
4522
+ };
4523
+ }
4524
+ });
4525
+ }
4526
+ // ---------------------------------------------------------------------------
4527
+ // Private Helpers
4528
+ // ---------------------------------------------------------------------------
4529
+ // ---------------------------------------------------------------------------
4530
+ // Optional Methods
4531
+ // ---------------------------------------------------------------------------
4532
+ async exists() {
4533
+ if (!this.ipnsName) return false;
4534
+ const cached = this.cache.getIpnsRecord(this.ipnsName);
4535
+ if (cached) return true;
4536
+ const { best } = await this.httpClient.resolveIpns(this.ipnsName);
4537
+ return best !== null;
4538
+ }
4539
+ async clear() {
4540
+ if (!this.ipnsKeyPair || !this.ipnsName) return false;
4541
+ this.pendingBuffer.clear();
4542
+ if (this.flushTimer) {
4543
+ clearTimeout(this.flushTimer);
4544
+ this.flushTimer = null;
4545
+ }
4546
+ const emptyData = {
4547
+ _meta: {
4548
+ version: 0,
4549
+ address: this.identity?.directAddress ?? "",
4550
+ ipnsName: this.ipnsName,
4551
+ formatVersion: "2.0",
4552
+ updatedAt: Date.now()
4553
+ }
4554
+ };
4555
+ const result = await this._doSave(emptyData);
4556
+ if (result.success) {
4557
+ this.cache.clear();
4558
+ await this.statePersistence.clear(this.ipnsName);
4559
+ }
4560
+ return result.success;
4561
+ }
4562
+ onEvent(callback) {
4563
+ this.eventCallbacks.add(callback);
4564
+ return () => {
4565
+ this.eventCallbacks.delete(callback);
4566
+ };
4567
+ }
4568
+ // ---------------------------------------------------------------------------
4569
+ // Public Accessors
4570
+ // ---------------------------------------------------------------------------
4571
+ getIpnsName() {
4572
+ return this.ipnsName;
4573
+ }
4574
+ getLastCid() {
4575
+ return this.lastCid;
4576
+ }
4577
+ getSequenceNumber() {
4578
+ return this.ipnsSequenceNumber;
4579
+ }
4580
+ getDataVersion() {
4581
+ return this.dataVersion;
4582
+ }
4583
+ getRemoteCid() {
4584
+ return this.remoteCid;
4585
+ }
4586
+ // ---------------------------------------------------------------------------
4587
+ // Testing helper: wait for pending flush to complete
4588
+ // ---------------------------------------------------------------------------
4589
+ /**
4590
+ * Wait for the pending flush timer to fire and the flush operation to
4591
+ * complete. Useful in tests to await background writes.
4592
+ * Returns immediately if no flush is pending.
4593
+ */
4594
+ async waitForFlush() {
4595
+ if (this.flushTimer) {
4596
+ clearTimeout(this.flushTimer);
4597
+ this.flushTimer = null;
4598
+ await this.flushQueue.enqueue(() => this.executeFlush()).catch(() => {
4599
+ });
4600
+ } else if (!this.pendingBuffer.isEmpty) {
4601
+ await this.flushQueue.enqueue(() => this.executeFlush()).catch(() => {
4602
+ });
4603
+ } else {
4604
+ await this.flushQueue.enqueue(async () => {
4605
+ });
4606
+ }
4607
+ }
4608
+ // ---------------------------------------------------------------------------
4609
+ // Internal: Push Subscription Helpers
4610
+ // ---------------------------------------------------------------------------
4611
+ /**
4612
+ * Derive WebSocket URL from the first configured gateway.
4613
+ * Converts https://host → wss://host/ws/ipns
4614
+ */
4615
+ deriveWsUrl() {
4616
+ const gateways = this.httpClient.getGateways();
4617
+ if (gateways.length === 0) return null;
4618
+ const gateway = gateways[0];
4619
+ const wsProtocol = gateway.startsWith("https://") ? "wss://" : "ws://";
4620
+ const host = gateway.replace(/^https?:\/\//, "");
4621
+ return `${wsProtocol}${host}/ws/ipns`;
4622
+ }
4623
+ /**
4624
+ * Poll for remote IPNS changes (fallback when WS is unavailable).
4625
+ * Compares remote sequence number with last known and emits event if changed.
4626
+ */
4627
+ async pollForRemoteChanges() {
4628
+ if (!this.ipnsName) return;
4629
+ try {
4630
+ const { best } = await this.httpClient.resolveIpns(this.ipnsName);
4631
+ if (best && best.sequence > this.lastKnownRemoteSequence) {
4632
+ this.log(`Poll detected remote change: seq=${best.sequence} (was ${this.lastKnownRemoteSequence})`);
4633
+ this.lastKnownRemoteSequence = best.sequence;
4634
+ this.emitEvent({
4635
+ type: "storage:remote-updated",
4636
+ timestamp: Date.now(),
4637
+ data: { name: this.ipnsName, sequence: Number(best.sequence), cid: best.cid }
4638
+ });
4639
+ }
4640
+ } catch {
4641
+ }
4642
+ }
4643
+ // ---------------------------------------------------------------------------
4644
+ // Internal
4645
+ // ---------------------------------------------------------------------------
4646
+ emitEvent(event) {
4647
+ for (const callback of this.eventCallbacks) {
4648
+ try {
4649
+ callback(event);
4650
+ } catch {
4651
+ }
4652
+ }
4653
+ }
4654
+ log(message) {
4655
+ if (this.debug) {
4656
+ console.log(`[IPFS-Storage] ${message}`);
4657
+ }
4658
+ }
4659
+ };
4660
+
4661
+ // impl/nodejs/ipfs/nodejs-ipfs-state-persistence.ts
4662
+ var KEY_PREFIX = "sphere_ipfs_";
4663
+ function seqKey(ipnsName) {
4664
+ return `${KEY_PREFIX}seq_${ipnsName}`;
4665
+ }
4666
+ function cidKey(ipnsName) {
4667
+ return `${KEY_PREFIX}cid_${ipnsName}`;
4668
+ }
4669
+ function verKey(ipnsName) {
4670
+ return `${KEY_PREFIX}ver_${ipnsName}`;
4671
+ }
4672
+ var NodejsIpfsStatePersistence = class {
4673
+ constructor(storage) {
4674
+ this.storage = storage;
4675
+ }
4676
+ async load(ipnsName) {
4677
+ try {
4678
+ const seq = await this.storage.get(seqKey(ipnsName));
4679
+ if (!seq) return null;
4680
+ const cid = await this.storage.get(cidKey(ipnsName));
4681
+ const ver = await this.storage.get(verKey(ipnsName));
4682
+ return {
4683
+ sequenceNumber: seq,
4684
+ lastCid: cid,
4685
+ version: parseInt(ver ?? "0", 10)
4686
+ };
4687
+ } catch {
4688
+ return null;
4689
+ }
4690
+ }
4691
+ async save(ipnsName, state) {
4692
+ await this.storage.set(seqKey(ipnsName), state.sequenceNumber);
4693
+ if (state.lastCid) {
4694
+ await this.storage.set(cidKey(ipnsName), state.lastCid);
4695
+ } else {
4696
+ await this.storage.remove(cidKey(ipnsName));
4697
+ }
4698
+ await this.storage.set(verKey(ipnsName), String(state.version));
4699
+ }
4700
+ async clear(ipnsName) {
4701
+ await this.storage.remove(seqKey(ipnsName));
4702
+ await this.storage.remove(cidKey(ipnsName));
4703
+ await this.storage.remove(verKey(ipnsName));
4704
+ }
4705
+ };
4706
+
4707
+ // impl/nodejs/ipfs/index.ts
4708
+ function createNodeIpfsStorageProvider(config, storageProvider) {
4709
+ const persistence = storageProvider ? new NodejsIpfsStatePersistence(storageProvider) : void 0;
4710
+ return new IpfsStorageProvider(
4711
+ { ...config, createWebSocket: config?.createWebSocket ?? createNodeWebSocketFactory() },
4712
+ persistence
4713
+ );
4714
+ }
4715
+
4716
+ // price/CoinGeckoPriceProvider.ts
4717
+ var CoinGeckoPriceProvider = class {
4718
+ platform = "coingecko";
4719
+ cache = /* @__PURE__ */ new Map();
4720
+ apiKey;
4721
+ cacheTtlMs;
4722
+ timeout;
4723
+ debug;
4724
+ baseUrl;
4725
+ constructor(config) {
4726
+ this.apiKey = config?.apiKey;
4727
+ this.cacheTtlMs = config?.cacheTtlMs ?? 6e4;
4728
+ this.timeout = config?.timeout ?? 1e4;
4729
+ this.debug = config?.debug ?? false;
4730
+ this.baseUrl = config?.baseUrl ?? (this.apiKey ? "https://pro-api.coingecko.com/api/v3" : "https://api.coingecko.com/api/v3");
4731
+ }
4732
+ async getPrices(tokenNames) {
4733
+ if (tokenNames.length === 0) {
4734
+ return /* @__PURE__ */ new Map();
4735
+ }
4736
+ const now = Date.now();
4737
+ const result = /* @__PURE__ */ new Map();
4738
+ const uncachedNames = [];
4739
+ for (const name of tokenNames) {
4740
+ const cached = this.cache.get(name);
4741
+ if (cached && cached.expiresAt > now) {
4742
+ if (cached.price !== null) {
4743
+ result.set(name, cached.price);
4744
+ }
4745
+ } else {
4746
+ uncachedNames.push(name);
4747
+ }
4748
+ }
4749
+ if (uncachedNames.length === 0) {
4750
+ return result;
4751
+ }
4752
+ try {
4753
+ const ids = uncachedNames.join(",");
4754
+ const url = `${this.baseUrl}/simple/price?ids=${encodeURIComponent(ids)}&vs_currencies=usd,eur&include_24hr_change=true`;
4755
+ const headers = { Accept: "application/json" };
4756
+ if (this.apiKey) {
4757
+ headers["x-cg-pro-api-key"] = this.apiKey;
4758
+ }
4759
+ if (this.debug) {
4760
+ console.log(`[CoinGecko] Fetching prices for: ${uncachedNames.join(", ")}`);
4761
+ }
4762
+ const response = await fetch(url, {
4763
+ headers,
4764
+ signal: AbortSignal.timeout(this.timeout)
4765
+ });
4766
+ if (!response.ok) {
4767
+ throw new Error(`CoinGecko API error: ${response.status} ${response.statusText}`);
4768
+ }
4769
+ const data = await response.json();
4770
+ for (const [name, values] of Object.entries(data)) {
4771
+ if (values && typeof values === "object") {
4772
+ const price = {
4773
+ tokenName: name,
4774
+ priceUsd: values.usd ?? 0,
4775
+ priceEur: values.eur,
4776
+ change24h: values.usd_24h_change,
4777
+ timestamp: now
4778
+ };
4779
+ this.cache.set(name, { price, expiresAt: now + this.cacheTtlMs });
4780
+ result.set(name, price);
4781
+ }
4782
+ }
4783
+ for (const name of uncachedNames) {
4784
+ if (!result.has(name)) {
4785
+ this.cache.set(name, { price: null, expiresAt: now + this.cacheTtlMs });
4786
+ }
4787
+ }
4788
+ if (this.debug) {
4789
+ console.log(`[CoinGecko] Fetched ${result.size} prices`);
4790
+ }
4791
+ } catch (error) {
4792
+ if (this.debug) {
4793
+ console.warn("[CoinGecko] Fetch failed, using stale cache:", error);
4794
+ }
4795
+ for (const name of uncachedNames) {
4796
+ const stale = this.cache.get(name);
4797
+ if (stale?.price) {
4798
+ result.set(name, stale.price);
4799
+ }
4800
+ }
4801
+ }
4802
+ return result;
4803
+ }
4804
+ async getPrice(tokenName) {
4805
+ const prices = await this.getPrices([tokenName]);
4806
+ return prices.get(tokenName) ?? null;
4807
+ }
4808
+ clearCache() {
4809
+ this.cache.clear();
4810
+ }
4811
+ };
4812
+
4813
+ // price/index.ts
4814
+ function createPriceProvider(config) {
4815
+ switch (config.platform) {
4816
+ case "coingecko":
4817
+ return new CoinGeckoPriceProvider(config);
4818
+ default:
4819
+ throw new Error(`Unsupported price platform: ${String(config.platform)}`);
4820
+ }
4821
+ }
4822
+
4823
+ // impl/shared/resolvers.ts
4824
+ function getNetworkConfig(network = "mainnet") {
4825
+ return NETWORKS[network];
4826
+ }
4827
+ function resolveTransportConfig(network, config) {
4828
+ const networkConfig = getNetworkConfig(network);
4829
+ let relays;
4830
+ if (config?.relays) {
4831
+ relays = config.relays;
4832
+ } else {
4833
+ relays = [...networkConfig.nostrRelays];
4834
+ if (config?.additionalRelays) {
4835
+ relays = [...relays, ...config.additionalRelays];
4836
+ }
4837
+ }
4838
+ return {
4839
+ relays,
4840
+ timeout: config?.timeout,
4841
+ autoReconnect: config?.autoReconnect,
4842
+ debug: config?.debug,
4843
+ // Browser-specific
4844
+ reconnectDelay: config?.reconnectDelay,
4845
+ maxReconnectAttempts: config?.maxReconnectAttempts
4846
+ };
4847
+ }
4848
+ function resolveOracleConfig(network, config) {
4849
+ const networkConfig = getNetworkConfig(network);
4850
+ return {
4851
+ url: config?.url ?? networkConfig.aggregatorUrl,
4852
+ apiKey: config?.apiKey ?? DEFAULT_AGGREGATOR_API_KEY,
4853
+ timeout: config?.timeout,
4854
+ skipVerification: config?.skipVerification,
4855
+ debug: config?.debug,
4856
+ // Node.js-specific
4857
+ trustBasePath: config?.trustBasePath
4858
+ };
4859
+ }
4860
+ function resolveL1Config(network, config) {
4861
+ if (config === void 0) {
4862
+ return void 0;
4863
+ }
4864
+ const networkConfig = getNetworkConfig(network);
4865
+ return {
4866
+ electrumUrl: config.electrumUrl ?? networkConfig.electrumUrl,
4867
+ defaultFeeRate: config.defaultFeeRate,
4868
+ enableVesting: config.enableVesting
4869
+ };
4870
+ }
4871
+ function resolvePriceConfig(config) {
4872
+ if (config === void 0) {
4873
+ return void 0;
4874
+ }
4875
+ return {
4876
+ platform: config.platform ?? "coingecko",
4877
+ apiKey: config.apiKey,
4878
+ baseUrl: config.baseUrl,
4879
+ cacheTtlMs: config.cacheTtlMs,
4880
+ timeout: config.timeout,
4881
+ debug: config.debug
4882
+ };
4883
+ }
4884
+ function resolveGroupChatConfig(network, config) {
4885
+ if (!config) return void 0;
4886
+ if (config === true) {
4887
+ const netConfig2 = getNetworkConfig(network);
4888
+ return { relays: [...netConfig2.groupRelays] };
4889
+ }
4890
+ if (typeof config === "object" && config.enabled === false) {
4891
+ return void 0;
4892
+ }
4893
+ const netConfig = getNetworkConfig(network);
4894
+ return {
4895
+ relays: config.relays ?? [...netConfig.groupRelays]
2974
4896
  };
2975
4897
  }
2976
4898
 
@@ -2984,8 +4906,12 @@ function createNodeProviders(config) {
2984
4906
  const storage = createFileStorageProvider({
2985
4907
  dataDir: config?.dataDir ?? "./sphere-data"
2986
4908
  });
4909
+ const ipfsSync = config?.tokenSync?.ipfs;
4910
+ const ipfsTokenStorage = ipfsSync?.enabled ? createNodeIpfsStorageProvider(ipfsSync.config, storage) : void 0;
4911
+ const groupChat = resolveGroupChatConfig(network, config?.groupChat);
2987
4912
  return {
2988
4913
  storage,
4914
+ groupChat,
2989
4915
  tokenStorage: createFileTokenStorageProvider({
2990
4916
  tokensDir: config?.tokensDir ?? "./sphere-tokens"
2991
4917
  }),
@@ -3006,7 +4932,8 @@ function createNodeProviders(config) {
3006
4932
  network
3007
4933
  }),
3008
4934
  l1: l1Config,
3009
- price: priceConfig ? createPriceProvider(priceConfig) : void 0
4935
+ price: priceConfig ? createPriceProvider(priceConfig) : void 0,
4936
+ ipfsTokenStorage
3010
4937
  };
3011
4938
  }
3012
4939
  export {