@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.
- package/README.md +61 -20
- package/dist/core/index.cjs +5764 -3576
- package/dist/core/index.cjs.map +1 -1
- package/dist/core/index.d.cts +648 -256
- package/dist/core/index.d.ts +648 -256
- package/dist/core/index.js +5767 -3576
- package/dist/core/index.js.map +1 -1
- package/dist/impl/browser/index.cjs +2118 -185
- package/dist/impl/browser/index.cjs.map +1 -1
- package/dist/impl/browser/index.js +2118 -185
- package/dist/impl/browser/index.js.map +1 -1
- package/dist/impl/browser/ipfs.cjs +1823 -513
- package/dist/impl/browser/ipfs.cjs.map +1 -1
- package/dist/impl/browser/ipfs.js +1823 -513
- package/dist/impl/browser/ipfs.js.map +1 -1
- package/dist/impl/nodejs/index.cjs +2110 -183
- package/dist/impl/nodejs/index.cjs.map +1 -1
- package/dist/impl/nodejs/index.d.cts +86 -23
- package/dist/impl/nodejs/index.d.ts +86 -23
- package/dist/impl/nodejs/index.js +2110 -183
- package/dist/impl/nodejs/index.js.map +1 -1
- package/dist/index.cjs +5782 -3603
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +719 -105
- package/dist/index.d.ts +719 -105
- package/dist/index.js +5780 -3603
- package/dist/index.js.map +1 -1
- package/package.json +28 -6
|
@@ -84,7 +84,17 @@ var STORAGE_KEYS_GLOBAL = {
|
|
|
84
84
|
/** Active addresses registry (JSON: TrackedAddressesStorage) */
|
|
85
85
|
TRACKED_ADDRESSES: "tracked_addresses",
|
|
86
86
|
/** Last processed Nostr wallet event timestamp (unix seconds), keyed per pubkey */
|
|
87
|
-
LAST_WALLET_EVENT_TS: "last_wallet_event_ts"
|
|
87
|
+
LAST_WALLET_EVENT_TS: "last_wallet_event_ts",
|
|
88
|
+
/** Group chat: joined groups */
|
|
89
|
+
GROUP_CHAT_GROUPS: "group_chat_groups",
|
|
90
|
+
/** Group chat: messages */
|
|
91
|
+
GROUP_CHAT_MESSAGES: "group_chat_messages",
|
|
92
|
+
/** Group chat: members */
|
|
93
|
+
GROUP_CHAT_MEMBERS: "group_chat_members",
|
|
94
|
+
/** Group chat: processed event IDs for deduplication */
|
|
95
|
+
GROUP_CHAT_PROCESSED_EVENTS: "group_chat_processed_events",
|
|
96
|
+
/** Group chat: last used relay URL (stale data detection) */
|
|
97
|
+
GROUP_CHAT_RELAY_URL: "group_chat_relay_url"
|
|
88
98
|
};
|
|
89
99
|
var STORAGE_KEYS_ADDRESS = {
|
|
90
100
|
/** Pending transfers for this address */
|
|
@@ -96,7 +106,9 @@ var STORAGE_KEYS_ADDRESS = {
|
|
|
96
106
|
/** Messages for this address */
|
|
97
107
|
MESSAGES: "messages",
|
|
98
108
|
/** Transaction history for this address */
|
|
99
|
-
TRANSACTION_HISTORY: "transaction_history"
|
|
109
|
+
TRANSACTION_HISTORY: "transaction_history",
|
|
110
|
+
/** Pending V5 finalization tokens (unconfirmed instant split tokens) */
|
|
111
|
+
PENDING_V5_TOKENS: "pending_v5_tokens"
|
|
100
112
|
};
|
|
101
113
|
var STORAGE_KEYS = {
|
|
102
114
|
...STORAGE_KEYS_GLOBAL,
|
|
@@ -143,6 +155,19 @@ var DEFAULT_IPFS_GATEWAYS = [
|
|
|
143
155
|
"https://dweb.link",
|
|
144
156
|
"https://ipfs.io"
|
|
145
157
|
];
|
|
158
|
+
var UNICITY_IPFS_NODES = [
|
|
159
|
+
{
|
|
160
|
+
host: "unicity-ipfs1.dyndns.org",
|
|
161
|
+
peerId: "12D3KooWDKJqEMAhH4nsSSiKtK1VLcas5coUqSPZAfbWbZpxtL4u",
|
|
162
|
+
httpPort: 9080,
|
|
163
|
+
httpsPort: 443
|
|
164
|
+
}
|
|
165
|
+
];
|
|
166
|
+
function getIpfsGatewayUrls(isSecure) {
|
|
167
|
+
return UNICITY_IPFS_NODES.map(
|
|
168
|
+
(node) => isSecure !== false ? `https://${node.host}` : `http://${node.host}:${node.httpPort}`
|
|
169
|
+
);
|
|
170
|
+
}
|
|
146
171
|
var DEFAULT_BASE_PATH = "m/44'/0'/0'";
|
|
147
172
|
var DEFAULT_DERIVATION_PATH = `${DEFAULT_BASE_PATH}/0/0`;
|
|
148
173
|
var DEFAULT_ELECTRUM_URL = "wss://fulcrum.alpha.unicity.network:50004";
|
|
@@ -150,27 +175,33 @@ var TEST_ELECTRUM_URL = "wss://fulcrum.alpha.testnet.unicity.network:50004";
|
|
|
150
175
|
var TEST_NOSTR_RELAYS = [
|
|
151
176
|
"wss://nostr-relay.testnet.unicity.network"
|
|
152
177
|
];
|
|
178
|
+
var DEFAULT_GROUP_RELAYS = [
|
|
179
|
+
"wss://sphere-relay.unicity.network"
|
|
180
|
+
];
|
|
153
181
|
var NETWORKS = {
|
|
154
182
|
mainnet: {
|
|
155
183
|
name: "Mainnet",
|
|
156
184
|
aggregatorUrl: DEFAULT_AGGREGATOR_URL,
|
|
157
185
|
nostrRelays: DEFAULT_NOSTR_RELAYS,
|
|
158
186
|
ipfsGateways: DEFAULT_IPFS_GATEWAYS,
|
|
159
|
-
electrumUrl: DEFAULT_ELECTRUM_URL
|
|
187
|
+
electrumUrl: DEFAULT_ELECTRUM_URL,
|
|
188
|
+
groupRelays: DEFAULT_GROUP_RELAYS
|
|
160
189
|
},
|
|
161
190
|
testnet: {
|
|
162
191
|
name: "Testnet",
|
|
163
192
|
aggregatorUrl: TEST_AGGREGATOR_URL,
|
|
164
193
|
nostrRelays: TEST_NOSTR_RELAYS,
|
|
165
194
|
ipfsGateways: DEFAULT_IPFS_GATEWAYS,
|
|
166
|
-
electrumUrl: TEST_ELECTRUM_URL
|
|
195
|
+
electrumUrl: TEST_ELECTRUM_URL,
|
|
196
|
+
groupRelays: DEFAULT_GROUP_RELAYS
|
|
167
197
|
},
|
|
168
198
|
dev: {
|
|
169
199
|
name: "Development",
|
|
170
200
|
aggregatorUrl: DEV_AGGREGATOR_URL,
|
|
171
201
|
nostrRelays: TEST_NOSTR_RELAYS,
|
|
172
202
|
ipfsGateways: DEFAULT_IPFS_GATEWAYS,
|
|
173
|
-
electrumUrl: TEST_ELECTRUM_URL
|
|
203
|
+
electrumUrl: TEST_ELECTRUM_URL,
|
|
204
|
+
groupRelays: DEFAULT_GROUP_RELAYS
|
|
174
205
|
}
|
|
175
206
|
};
|
|
176
207
|
var TIMEOUTS = {
|
|
@@ -590,29 +621,6 @@ var IndexedDBTokenStorageProvider = class {
|
|
|
590
621
|
}
|
|
591
622
|
}
|
|
592
623
|
// =========================================================================
|
|
593
|
-
// Helper methods for individual token operations
|
|
594
|
-
// =========================================================================
|
|
595
|
-
async deleteToken(tokenId) {
|
|
596
|
-
if (this.db) {
|
|
597
|
-
await this.deleteFromStore(STORE_TOKENS, tokenId);
|
|
598
|
-
}
|
|
599
|
-
}
|
|
600
|
-
async saveToken(tokenId, tokenData) {
|
|
601
|
-
if (this.db) {
|
|
602
|
-
await this.putToStore(STORE_TOKENS, tokenId, { id: tokenId, data: tokenData });
|
|
603
|
-
}
|
|
604
|
-
}
|
|
605
|
-
async getToken(tokenId) {
|
|
606
|
-
if (!this.db) return null;
|
|
607
|
-
const result = await this.getFromStore(STORE_TOKENS, tokenId);
|
|
608
|
-
return result?.data ?? null;
|
|
609
|
-
}
|
|
610
|
-
async listTokenIds() {
|
|
611
|
-
if (!this.db) return [];
|
|
612
|
-
const tokens = await this.getAllFromStore(STORE_TOKENS);
|
|
613
|
-
return tokens.map((t) => t.id);
|
|
614
|
-
}
|
|
615
|
-
// =========================================================================
|
|
616
624
|
// Private IndexedDB helpers
|
|
617
625
|
// =========================================================================
|
|
618
626
|
openDatabase() {
|
|
@@ -1255,6 +1263,13 @@ function publicKeyToAddress(publicKey, prefix = "alpha", witnessVersion = 0) {
|
|
|
1255
1263
|
const programBytes = hash160ToBytes(pubKeyHash);
|
|
1256
1264
|
return encodeBech32(prefix, witnessVersion, programBytes);
|
|
1257
1265
|
}
|
|
1266
|
+
function hexToBytes(hex) {
|
|
1267
|
+
const matches = hex.match(/../g);
|
|
1268
|
+
if (!matches) {
|
|
1269
|
+
return new Uint8Array(0);
|
|
1270
|
+
}
|
|
1271
|
+
return Uint8Array.from(matches.map((x) => parseInt(x, 16)));
|
|
1272
|
+
}
|
|
1258
1273
|
|
|
1259
1274
|
// transport/websocket.ts
|
|
1260
1275
|
var WebSocketReadyState = {
|
|
@@ -1350,6 +1365,7 @@ var NostrTransportProvider = class {
|
|
|
1350
1365
|
nostrClient = null;
|
|
1351
1366
|
mainSubscriptionId = null;
|
|
1352
1367
|
// Event handlers
|
|
1368
|
+
processedEventIds = /* @__PURE__ */ new Set();
|
|
1353
1369
|
messageHandlers = /* @__PURE__ */ new Set();
|
|
1354
1370
|
transferHandlers = /* @__PURE__ */ new Set();
|
|
1355
1371
|
paymentRequestHandlers = /* @__PURE__ */ new Set();
|
|
@@ -2090,6 +2106,12 @@ var NostrTransportProvider = class {
|
|
|
2090
2106
|
// Private: Message Handling
|
|
2091
2107
|
// ===========================================================================
|
|
2092
2108
|
async handleEvent(event) {
|
|
2109
|
+
if (event.id && this.processedEventIds.has(event.id)) {
|
|
2110
|
+
return;
|
|
2111
|
+
}
|
|
2112
|
+
if (event.id) {
|
|
2113
|
+
this.processedEventIds.add(event.id);
|
|
2114
|
+
}
|
|
2093
2115
|
this.log("Processing event kind:", event.kind, "id:", event.id?.slice(0, 12));
|
|
2094
2116
|
try {
|
|
2095
2117
|
switch (event.kind) {
|
|
@@ -2202,7 +2224,7 @@ var NostrTransportProvider = class {
|
|
|
2202
2224
|
this.emitEvent({ type: "transfer:received", timestamp: Date.now() });
|
|
2203
2225
|
for (const handler of this.transferHandlers) {
|
|
2204
2226
|
try {
|
|
2205
|
-
handler(transfer);
|
|
2227
|
+
await handler(transfer);
|
|
2206
2228
|
} catch (error) {
|
|
2207
2229
|
this.log("Transfer handler error:", error);
|
|
2208
2230
|
}
|
|
@@ -2332,6 +2354,49 @@ var NostrTransportProvider = class {
|
|
|
2332
2354
|
const sdkEvent = import_nostr_js_sdk.Event.fromJSON(event);
|
|
2333
2355
|
await this.nostrClient.publishEvent(sdkEvent);
|
|
2334
2356
|
}
|
|
2357
|
+
async fetchPendingEvents() {
|
|
2358
|
+
if (!this.nostrClient?.isConnected() || !this.keyManager) {
|
|
2359
|
+
throw new Error("Transport not connected");
|
|
2360
|
+
}
|
|
2361
|
+
const nostrPubkey = this.keyManager.getPublicKeyHex();
|
|
2362
|
+
const walletFilter = new import_nostr_js_sdk.Filter();
|
|
2363
|
+
walletFilter.kinds = [
|
|
2364
|
+
EVENT_KINDS.DIRECT_MESSAGE,
|
|
2365
|
+
EVENT_KINDS.TOKEN_TRANSFER,
|
|
2366
|
+
EVENT_KINDS.PAYMENT_REQUEST,
|
|
2367
|
+
EVENT_KINDS.PAYMENT_REQUEST_RESPONSE
|
|
2368
|
+
];
|
|
2369
|
+
walletFilter["#p"] = [nostrPubkey];
|
|
2370
|
+
walletFilter.since = Math.floor(Date.now() / 1e3) - 86400;
|
|
2371
|
+
const events = [];
|
|
2372
|
+
await new Promise((resolve) => {
|
|
2373
|
+
const timeout = setTimeout(() => {
|
|
2374
|
+
if (subId) this.nostrClient?.unsubscribe(subId);
|
|
2375
|
+
resolve();
|
|
2376
|
+
}, 5e3);
|
|
2377
|
+
const subId = this.nostrClient.subscribe(walletFilter, {
|
|
2378
|
+
onEvent: (event) => {
|
|
2379
|
+
events.push({
|
|
2380
|
+
id: event.id,
|
|
2381
|
+
kind: event.kind,
|
|
2382
|
+
content: event.content,
|
|
2383
|
+
tags: event.tags,
|
|
2384
|
+
pubkey: event.pubkey,
|
|
2385
|
+
created_at: event.created_at,
|
|
2386
|
+
sig: event.sig
|
|
2387
|
+
});
|
|
2388
|
+
},
|
|
2389
|
+
onEndOfStoredEvents: () => {
|
|
2390
|
+
clearTimeout(timeout);
|
|
2391
|
+
this.nostrClient?.unsubscribe(subId);
|
|
2392
|
+
resolve();
|
|
2393
|
+
}
|
|
2394
|
+
});
|
|
2395
|
+
});
|
|
2396
|
+
for (const event of events) {
|
|
2397
|
+
await this.handleEvent(event);
|
|
2398
|
+
}
|
|
2399
|
+
}
|
|
2335
2400
|
async queryEvents(filterObj) {
|
|
2336
2401
|
if (!this.nostrClient || !this.nostrClient.isConnected()) {
|
|
2337
2402
|
throw new Error("No connected relays");
|
|
@@ -3094,183 +3159,2042 @@ async function readFileAsUint8Array(file) {
|
|
|
3094
3159
|
return new Uint8Array(buffer);
|
|
3095
3160
|
}
|
|
3096
3161
|
|
|
3097
|
-
//
|
|
3098
|
-
var
|
|
3099
|
-
|
|
3100
|
-
|
|
3101
|
-
|
|
3102
|
-
|
|
3103
|
-
|
|
3104
|
-
|
|
3105
|
-
|
|
3106
|
-
|
|
3107
|
-
this.
|
|
3108
|
-
|
|
3109
|
-
|
|
3110
|
-
|
|
3111
|
-
this.
|
|
3162
|
+
// impl/shared/ipfs/ipfs-error-types.ts
|
|
3163
|
+
var IpfsError = class extends Error {
|
|
3164
|
+
category;
|
|
3165
|
+
gateway;
|
|
3166
|
+
cause;
|
|
3167
|
+
constructor(message, category, gateway, cause) {
|
|
3168
|
+
super(message);
|
|
3169
|
+
this.name = "IpfsError";
|
|
3170
|
+
this.category = category;
|
|
3171
|
+
this.gateway = gateway;
|
|
3172
|
+
this.cause = cause;
|
|
3173
|
+
}
|
|
3174
|
+
/** Whether this error should trigger the circuit breaker */
|
|
3175
|
+
get shouldTriggerCircuitBreaker() {
|
|
3176
|
+
return this.category !== "NOT_FOUND" && this.category !== "SEQUENCE_DOWNGRADE";
|
|
3112
3177
|
}
|
|
3113
|
-
|
|
3114
|
-
|
|
3115
|
-
|
|
3116
|
-
|
|
3117
|
-
|
|
3118
|
-
|
|
3119
|
-
|
|
3120
|
-
|
|
3121
|
-
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
3125
|
-
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3132
|
-
|
|
3133
|
-
try {
|
|
3134
|
-
const ids = uncachedNames.join(",");
|
|
3135
|
-
const url = `${this.baseUrl}/simple/price?ids=${encodeURIComponent(ids)}&vs_currencies=usd,eur&include_24hr_change=true`;
|
|
3136
|
-
const headers = { Accept: "application/json" };
|
|
3137
|
-
if (this.apiKey) {
|
|
3138
|
-
headers["x-cg-pro-api-key"] = this.apiKey;
|
|
3139
|
-
}
|
|
3140
|
-
if (this.debug) {
|
|
3141
|
-
console.log(`[CoinGecko] Fetching prices for: ${uncachedNames.join(", ")}`);
|
|
3142
|
-
}
|
|
3143
|
-
const response = await fetch(url, {
|
|
3144
|
-
headers,
|
|
3145
|
-
signal: AbortSignal.timeout(this.timeout)
|
|
3146
|
-
});
|
|
3147
|
-
if (!response.ok) {
|
|
3148
|
-
throw new Error(`CoinGecko API error: ${response.status} ${response.statusText}`);
|
|
3149
|
-
}
|
|
3150
|
-
const data = await response.json();
|
|
3151
|
-
for (const [name, values] of Object.entries(data)) {
|
|
3152
|
-
if (values && typeof values === "object") {
|
|
3153
|
-
const price = {
|
|
3154
|
-
tokenName: name,
|
|
3155
|
-
priceUsd: values.usd ?? 0,
|
|
3156
|
-
priceEur: values.eur,
|
|
3157
|
-
change24h: values.usd_24h_change,
|
|
3158
|
-
timestamp: now
|
|
3159
|
-
};
|
|
3160
|
-
this.cache.set(name, { price, expiresAt: now + this.cacheTtlMs });
|
|
3161
|
-
result.set(name, price);
|
|
3162
|
-
}
|
|
3163
|
-
}
|
|
3164
|
-
for (const name of uncachedNames) {
|
|
3165
|
-
if (!result.has(name)) {
|
|
3166
|
-
this.cache.set(name, { price: null, expiresAt: now + this.cacheTtlMs });
|
|
3167
|
-
}
|
|
3168
|
-
}
|
|
3169
|
-
if (this.debug) {
|
|
3170
|
-
console.log(`[CoinGecko] Fetched ${result.size} prices`);
|
|
3171
|
-
}
|
|
3172
|
-
} catch (error) {
|
|
3173
|
-
if (this.debug) {
|
|
3174
|
-
console.warn("[CoinGecko] Fetch failed, using stale cache:", error);
|
|
3175
|
-
}
|
|
3176
|
-
for (const name of uncachedNames) {
|
|
3177
|
-
const stale = this.cache.get(name);
|
|
3178
|
-
if (stale?.price) {
|
|
3179
|
-
result.set(name, stale.price);
|
|
3180
|
-
}
|
|
3181
|
-
}
|
|
3178
|
+
};
|
|
3179
|
+
function classifyFetchError(error) {
|
|
3180
|
+
if (error instanceof DOMException && error.name === "AbortError") {
|
|
3181
|
+
return "TIMEOUT";
|
|
3182
|
+
}
|
|
3183
|
+
if (error instanceof TypeError) {
|
|
3184
|
+
return "NETWORK_ERROR";
|
|
3185
|
+
}
|
|
3186
|
+
if (error instanceof Error && error.name === "TimeoutError") {
|
|
3187
|
+
return "TIMEOUT";
|
|
3188
|
+
}
|
|
3189
|
+
return "NETWORK_ERROR";
|
|
3190
|
+
}
|
|
3191
|
+
function classifyHttpStatus(status, responseBody) {
|
|
3192
|
+
if (status === 404) {
|
|
3193
|
+
return "NOT_FOUND";
|
|
3194
|
+
}
|
|
3195
|
+
if (status === 500 && responseBody) {
|
|
3196
|
+
if (/routing:\s*not\s*found/i.test(responseBody)) {
|
|
3197
|
+
return "NOT_FOUND";
|
|
3182
3198
|
}
|
|
3183
|
-
return result;
|
|
3184
3199
|
}
|
|
3185
|
-
|
|
3186
|
-
|
|
3187
|
-
return prices.get(tokenName) ?? null;
|
|
3200
|
+
if (status >= 500) {
|
|
3201
|
+
return "GATEWAY_ERROR";
|
|
3188
3202
|
}
|
|
3189
|
-
|
|
3190
|
-
|
|
3203
|
+
if (status >= 400) {
|
|
3204
|
+
return "GATEWAY_ERROR";
|
|
3191
3205
|
}
|
|
3192
|
-
|
|
3206
|
+
return "GATEWAY_ERROR";
|
|
3207
|
+
}
|
|
3193
3208
|
|
|
3194
|
-
//
|
|
3195
|
-
|
|
3196
|
-
|
|
3197
|
-
|
|
3198
|
-
|
|
3199
|
-
default:
|
|
3200
|
-
throw new Error(`Unsupported price platform: ${String(config.platform)}`);
|
|
3209
|
+
// impl/shared/ipfs/ipfs-state-persistence.ts
|
|
3210
|
+
var InMemoryIpfsStatePersistence = class {
|
|
3211
|
+
states = /* @__PURE__ */ new Map();
|
|
3212
|
+
async load(ipnsName) {
|
|
3213
|
+
return this.states.get(ipnsName) ?? null;
|
|
3201
3214
|
}
|
|
3202
|
-
|
|
3215
|
+
async save(ipnsName, state) {
|
|
3216
|
+
this.states.set(ipnsName, { ...state });
|
|
3217
|
+
}
|
|
3218
|
+
async clear(ipnsName) {
|
|
3219
|
+
this.states.delete(ipnsName);
|
|
3220
|
+
}
|
|
3221
|
+
};
|
|
3203
3222
|
|
|
3204
|
-
// impl/shared/
|
|
3205
|
-
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
function
|
|
3209
|
-
|
|
3210
|
-
|
|
3211
|
-
|
|
3212
|
-
|
|
3213
|
-
|
|
3214
|
-
relays = [...networkConfig.nostrRelays];
|
|
3215
|
-
if (config?.additionalRelays) {
|
|
3216
|
-
relays = [...relays, ...config.additionalRelays];
|
|
3217
|
-
}
|
|
3223
|
+
// impl/shared/ipfs/ipns-key-derivation.ts
|
|
3224
|
+
var IPNS_HKDF_INFO = "ipfs-storage-ed25519-v1";
|
|
3225
|
+
var libp2pCryptoModule = null;
|
|
3226
|
+
var libp2pPeerIdModule = null;
|
|
3227
|
+
async function loadLibp2pModules() {
|
|
3228
|
+
if (!libp2pCryptoModule) {
|
|
3229
|
+
[libp2pCryptoModule, libp2pPeerIdModule] = await Promise.all([
|
|
3230
|
+
import("@libp2p/crypto/keys"),
|
|
3231
|
+
import("@libp2p/peer-id")
|
|
3232
|
+
]);
|
|
3218
3233
|
}
|
|
3219
3234
|
return {
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
autoReconnect: config?.autoReconnect,
|
|
3223
|
-
debug: config?.debug,
|
|
3224
|
-
// Browser-specific
|
|
3225
|
-
reconnectDelay: config?.reconnectDelay,
|
|
3226
|
-
maxReconnectAttempts: config?.maxReconnectAttempts
|
|
3235
|
+
generateKeyPairFromSeed: libp2pCryptoModule.generateKeyPairFromSeed,
|
|
3236
|
+
peerIdFromPrivateKey: libp2pPeerIdModule.peerIdFromPrivateKey
|
|
3227
3237
|
};
|
|
3228
3238
|
}
|
|
3229
|
-
function
|
|
3230
|
-
const
|
|
3239
|
+
function deriveEd25519KeyMaterial(privateKeyHex, info = IPNS_HKDF_INFO) {
|
|
3240
|
+
const walletSecret = hexToBytes(privateKeyHex);
|
|
3241
|
+
const infoBytes = new TextEncoder().encode(info);
|
|
3242
|
+
return hkdf(sha256, walletSecret, void 0, infoBytes, 32);
|
|
3243
|
+
}
|
|
3244
|
+
async function deriveIpnsIdentity(privateKeyHex) {
|
|
3245
|
+
const { generateKeyPairFromSeed, peerIdFromPrivateKey } = await loadLibp2pModules();
|
|
3246
|
+
const derivedKey = deriveEd25519KeyMaterial(privateKeyHex);
|
|
3247
|
+
const keyPair = await generateKeyPairFromSeed("Ed25519", derivedKey);
|
|
3248
|
+
const peerId = peerIdFromPrivateKey(keyPair);
|
|
3231
3249
|
return {
|
|
3232
|
-
|
|
3233
|
-
|
|
3234
|
-
timeout: config?.timeout,
|
|
3235
|
-
skipVerification: config?.skipVerification,
|
|
3236
|
-
debug: config?.debug,
|
|
3237
|
-
// Node.js-specific
|
|
3238
|
-
trustBasePath: config?.trustBasePath
|
|
3250
|
+
keyPair,
|
|
3251
|
+
ipnsName: peerId.toString()
|
|
3239
3252
|
};
|
|
3240
3253
|
}
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
|
|
3254
|
+
|
|
3255
|
+
// impl/shared/ipfs/ipns-record-manager.ts
|
|
3256
|
+
var DEFAULT_LIFETIME_MS = 99 * 365 * 24 * 60 * 60 * 1e3;
|
|
3257
|
+
var ipnsModule = null;
|
|
3258
|
+
async function loadIpnsModule() {
|
|
3259
|
+
if (!ipnsModule) {
|
|
3260
|
+
const mod = await import("ipns");
|
|
3261
|
+
ipnsModule = {
|
|
3262
|
+
createIPNSRecord: mod.createIPNSRecord,
|
|
3263
|
+
marshalIPNSRecord: mod.marshalIPNSRecord,
|
|
3264
|
+
unmarshalIPNSRecord: mod.unmarshalIPNSRecord
|
|
3265
|
+
};
|
|
3244
3266
|
}
|
|
3245
|
-
|
|
3246
|
-
return {
|
|
3247
|
-
electrumUrl: config.electrumUrl ?? networkConfig.electrumUrl,
|
|
3248
|
-
defaultFeeRate: config.defaultFeeRate,
|
|
3249
|
-
enableVesting: config.enableVesting
|
|
3250
|
-
};
|
|
3267
|
+
return ipnsModule;
|
|
3251
3268
|
}
|
|
3252
|
-
function
|
|
3253
|
-
|
|
3254
|
-
|
|
3269
|
+
async function createSignedRecord(keyPair, cid, sequenceNumber, lifetimeMs = DEFAULT_LIFETIME_MS) {
|
|
3270
|
+
const { createIPNSRecord, marshalIPNSRecord } = await loadIpnsModule();
|
|
3271
|
+
const record = await createIPNSRecord(
|
|
3272
|
+
keyPair,
|
|
3273
|
+
`/ipfs/${cid}`,
|
|
3274
|
+
sequenceNumber,
|
|
3275
|
+
lifetimeMs
|
|
3276
|
+
);
|
|
3277
|
+
return marshalIPNSRecord(record);
|
|
3278
|
+
}
|
|
3279
|
+
async function parseRoutingApiResponse(responseText) {
|
|
3280
|
+
const { unmarshalIPNSRecord } = await loadIpnsModule();
|
|
3281
|
+
const lines = responseText.trim().split("\n");
|
|
3282
|
+
for (const line of lines) {
|
|
3283
|
+
if (!line.trim()) continue;
|
|
3284
|
+
try {
|
|
3285
|
+
const obj = JSON.parse(line);
|
|
3286
|
+
if (obj.Extra) {
|
|
3287
|
+
const recordData = base64ToUint8Array(obj.Extra);
|
|
3288
|
+
const record = unmarshalIPNSRecord(recordData);
|
|
3289
|
+
const valueBytes = typeof record.value === "string" ? new TextEncoder().encode(record.value) : record.value;
|
|
3290
|
+
const valueStr = new TextDecoder().decode(valueBytes);
|
|
3291
|
+
const cidMatch = valueStr.match(/\/ipfs\/([a-zA-Z0-9]+)/);
|
|
3292
|
+
if (cidMatch) {
|
|
3293
|
+
return {
|
|
3294
|
+
cid: cidMatch[1],
|
|
3295
|
+
sequence: record.sequence,
|
|
3296
|
+
recordData
|
|
3297
|
+
};
|
|
3298
|
+
}
|
|
3299
|
+
}
|
|
3300
|
+
} catch {
|
|
3301
|
+
continue;
|
|
3302
|
+
}
|
|
3255
3303
|
}
|
|
3256
|
-
return
|
|
3257
|
-
platform: config.platform ?? "coingecko",
|
|
3258
|
-
apiKey: config.apiKey,
|
|
3259
|
-
baseUrl: config.baseUrl,
|
|
3260
|
-
cacheTtlMs: config.cacheTtlMs,
|
|
3261
|
-
timeout: config.timeout,
|
|
3262
|
-
debug: config.debug
|
|
3263
|
-
};
|
|
3304
|
+
return null;
|
|
3264
3305
|
}
|
|
3265
|
-
function
|
|
3266
|
-
|
|
3267
|
-
|
|
3306
|
+
function base64ToUint8Array(base64) {
|
|
3307
|
+
const binary = atob(base64);
|
|
3308
|
+
const bytes = new Uint8Array(binary.length);
|
|
3309
|
+
for (let i = 0; i < binary.length; i++) {
|
|
3310
|
+
bytes[i] = binary.charCodeAt(i);
|
|
3268
3311
|
}
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
|
|
3312
|
+
return bytes;
|
|
3313
|
+
}
|
|
3314
|
+
|
|
3315
|
+
// impl/shared/ipfs/ipfs-cache.ts
|
|
3316
|
+
var DEFAULT_IPNS_TTL_MS = 6e4;
|
|
3317
|
+
var DEFAULT_FAILURE_COOLDOWN_MS = 6e4;
|
|
3318
|
+
var DEFAULT_FAILURE_THRESHOLD = 3;
|
|
3319
|
+
var DEFAULT_KNOWN_FRESH_WINDOW_MS = 3e4;
|
|
3320
|
+
var IpfsCache = class {
|
|
3321
|
+
ipnsRecords = /* @__PURE__ */ new Map();
|
|
3322
|
+
content = /* @__PURE__ */ new Map();
|
|
3323
|
+
gatewayFailures = /* @__PURE__ */ new Map();
|
|
3324
|
+
knownFreshTimestamps = /* @__PURE__ */ new Map();
|
|
3325
|
+
ipnsTtlMs;
|
|
3326
|
+
failureCooldownMs;
|
|
3327
|
+
failureThreshold;
|
|
3328
|
+
knownFreshWindowMs;
|
|
3329
|
+
constructor(config) {
|
|
3330
|
+
this.ipnsTtlMs = config?.ipnsTtlMs ?? DEFAULT_IPNS_TTL_MS;
|
|
3331
|
+
this.failureCooldownMs = config?.failureCooldownMs ?? DEFAULT_FAILURE_COOLDOWN_MS;
|
|
3332
|
+
this.failureThreshold = config?.failureThreshold ?? DEFAULT_FAILURE_THRESHOLD;
|
|
3333
|
+
this.knownFreshWindowMs = config?.knownFreshWindowMs ?? DEFAULT_KNOWN_FRESH_WINDOW_MS;
|
|
3334
|
+
}
|
|
3335
|
+
// ---------------------------------------------------------------------------
|
|
3336
|
+
// IPNS Record Cache (60s TTL)
|
|
3337
|
+
// ---------------------------------------------------------------------------
|
|
3338
|
+
getIpnsRecord(ipnsName) {
|
|
3339
|
+
const entry = this.ipnsRecords.get(ipnsName);
|
|
3340
|
+
if (!entry) return null;
|
|
3341
|
+
if (Date.now() - entry.timestamp > this.ipnsTtlMs) {
|
|
3342
|
+
this.ipnsRecords.delete(ipnsName);
|
|
3343
|
+
return null;
|
|
3344
|
+
}
|
|
3345
|
+
return entry.data;
|
|
3272
3346
|
}
|
|
3273
|
-
|
|
3347
|
+
/**
|
|
3348
|
+
* Get cached IPNS record ignoring TTL (for known-fresh optimization).
|
|
3349
|
+
*/
|
|
3350
|
+
getIpnsRecordIgnoreTtl(ipnsName) {
|
|
3351
|
+
const entry = this.ipnsRecords.get(ipnsName);
|
|
3352
|
+
return entry?.data ?? null;
|
|
3353
|
+
}
|
|
3354
|
+
setIpnsRecord(ipnsName, result) {
|
|
3355
|
+
this.ipnsRecords.set(ipnsName, {
|
|
3356
|
+
data: result,
|
|
3357
|
+
timestamp: Date.now()
|
|
3358
|
+
});
|
|
3359
|
+
}
|
|
3360
|
+
invalidateIpns(ipnsName) {
|
|
3361
|
+
this.ipnsRecords.delete(ipnsName);
|
|
3362
|
+
}
|
|
3363
|
+
// ---------------------------------------------------------------------------
|
|
3364
|
+
// Content Cache (infinite TTL - content is immutable by CID)
|
|
3365
|
+
// ---------------------------------------------------------------------------
|
|
3366
|
+
getContent(cid) {
|
|
3367
|
+
const entry = this.content.get(cid);
|
|
3368
|
+
return entry?.data ?? null;
|
|
3369
|
+
}
|
|
3370
|
+
setContent(cid, data) {
|
|
3371
|
+
this.content.set(cid, {
|
|
3372
|
+
data,
|
|
3373
|
+
timestamp: Date.now()
|
|
3374
|
+
});
|
|
3375
|
+
}
|
|
3376
|
+
// ---------------------------------------------------------------------------
|
|
3377
|
+
// Gateway Failure Tracking (Circuit Breaker)
|
|
3378
|
+
// ---------------------------------------------------------------------------
|
|
3379
|
+
/**
|
|
3380
|
+
* Record a gateway failure. After threshold consecutive failures,
|
|
3381
|
+
* the gateway enters cooldown and is considered unhealthy.
|
|
3382
|
+
*/
|
|
3383
|
+
recordGatewayFailure(gateway) {
|
|
3384
|
+
const existing = this.gatewayFailures.get(gateway);
|
|
3385
|
+
this.gatewayFailures.set(gateway, {
|
|
3386
|
+
count: (existing?.count ?? 0) + 1,
|
|
3387
|
+
lastFailure: Date.now()
|
|
3388
|
+
});
|
|
3389
|
+
}
|
|
3390
|
+
/** Reset failure count for a gateway (on successful request) */
|
|
3391
|
+
recordGatewaySuccess(gateway) {
|
|
3392
|
+
this.gatewayFailures.delete(gateway);
|
|
3393
|
+
}
|
|
3394
|
+
/**
|
|
3395
|
+
* Check if a gateway is currently in circuit breaker cooldown.
|
|
3396
|
+
* A gateway is considered unhealthy if it has had >= threshold
|
|
3397
|
+
* consecutive failures and the cooldown period hasn't elapsed.
|
|
3398
|
+
*/
|
|
3399
|
+
isGatewayInCooldown(gateway) {
|
|
3400
|
+
const failure = this.gatewayFailures.get(gateway);
|
|
3401
|
+
if (!failure) return false;
|
|
3402
|
+
if (failure.count < this.failureThreshold) return false;
|
|
3403
|
+
const elapsed = Date.now() - failure.lastFailure;
|
|
3404
|
+
if (elapsed >= this.failureCooldownMs) {
|
|
3405
|
+
this.gatewayFailures.delete(gateway);
|
|
3406
|
+
return false;
|
|
3407
|
+
}
|
|
3408
|
+
return true;
|
|
3409
|
+
}
|
|
3410
|
+
// ---------------------------------------------------------------------------
|
|
3411
|
+
// Known-Fresh Flag (FAST mode optimization)
|
|
3412
|
+
// ---------------------------------------------------------------------------
|
|
3413
|
+
/**
|
|
3414
|
+
* Mark IPNS cache as "known-fresh" (after local publish or push notification).
|
|
3415
|
+
* Within the fresh window, we can skip network resolution.
|
|
3416
|
+
*/
|
|
3417
|
+
markIpnsFresh(ipnsName) {
|
|
3418
|
+
this.knownFreshTimestamps.set(ipnsName, Date.now());
|
|
3419
|
+
}
|
|
3420
|
+
/**
|
|
3421
|
+
* Check if the cache is known-fresh (within the fresh window).
|
|
3422
|
+
*/
|
|
3423
|
+
isIpnsKnownFresh(ipnsName) {
|
|
3424
|
+
const timestamp = this.knownFreshTimestamps.get(ipnsName);
|
|
3425
|
+
if (!timestamp) return false;
|
|
3426
|
+
if (Date.now() - timestamp > this.knownFreshWindowMs) {
|
|
3427
|
+
this.knownFreshTimestamps.delete(ipnsName);
|
|
3428
|
+
return false;
|
|
3429
|
+
}
|
|
3430
|
+
return true;
|
|
3431
|
+
}
|
|
3432
|
+
// ---------------------------------------------------------------------------
|
|
3433
|
+
// Cache Management
|
|
3434
|
+
// ---------------------------------------------------------------------------
|
|
3435
|
+
clear() {
|
|
3436
|
+
this.ipnsRecords.clear();
|
|
3437
|
+
this.content.clear();
|
|
3438
|
+
this.gatewayFailures.clear();
|
|
3439
|
+
this.knownFreshTimestamps.clear();
|
|
3440
|
+
}
|
|
3441
|
+
};
|
|
3442
|
+
|
|
3443
|
+
// impl/shared/ipfs/ipfs-http-client.ts
|
|
3444
|
+
var DEFAULT_CONNECTIVITY_TIMEOUT_MS = 5e3;
|
|
3445
|
+
var DEFAULT_FETCH_TIMEOUT_MS = 15e3;
|
|
3446
|
+
var DEFAULT_RESOLVE_TIMEOUT_MS = 1e4;
|
|
3447
|
+
var DEFAULT_PUBLISH_TIMEOUT_MS = 3e4;
|
|
3448
|
+
var DEFAULT_GATEWAY_PATH_TIMEOUT_MS = 3e3;
|
|
3449
|
+
var DEFAULT_ROUTING_API_TIMEOUT_MS = 2e3;
|
|
3450
|
+
var IpfsHttpClient = class {
|
|
3451
|
+
gateways;
|
|
3452
|
+
fetchTimeoutMs;
|
|
3453
|
+
resolveTimeoutMs;
|
|
3454
|
+
publishTimeoutMs;
|
|
3455
|
+
connectivityTimeoutMs;
|
|
3456
|
+
debug;
|
|
3457
|
+
cache;
|
|
3458
|
+
constructor(config, cache) {
|
|
3459
|
+
this.gateways = config.gateways;
|
|
3460
|
+
this.fetchTimeoutMs = config.fetchTimeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
|
|
3461
|
+
this.resolveTimeoutMs = config.resolveTimeoutMs ?? DEFAULT_RESOLVE_TIMEOUT_MS;
|
|
3462
|
+
this.publishTimeoutMs = config.publishTimeoutMs ?? DEFAULT_PUBLISH_TIMEOUT_MS;
|
|
3463
|
+
this.connectivityTimeoutMs = config.connectivityTimeoutMs ?? DEFAULT_CONNECTIVITY_TIMEOUT_MS;
|
|
3464
|
+
this.debug = config.debug ?? false;
|
|
3465
|
+
this.cache = cache;
|
|
3466
|
+
}
|
|
3467
|
+
// ---------------------------------------------------------------------------
|
|
3468
|
+
// Public Accessors
|
|
3469
|
+
// ---------------------------------------------------------------------------
|
|
3470
|
+
/**
|
|
3471
|
+
* Get configured gateway URLs.
|
|
3472
|
+
*/
|
|
3473
|
+
getGateways() {
|
|
3474
|
+
return [...this.gateways];
|
|
3475
|
+
}
|
|
3476
|
+
// ---------------------------------------------------------------------------
|
|
3477
|
+
// Gateway Health
|
|
3478
|
+
// ---------------------------------------------------------------------------
|
|
3479
|
+
/**
|
|
3480
|
+
* Test connectivity to a single gateway.
|
|
3481
|
+
*/
|
|
3482
|
+
async testConnectivity(gateway) {
|
|
3483
|
+
const start = Date.now();
|
|
3484
|
+
try {
|
|
3485
|
+
const response = await this.fetchWithTimeout(
|
|
3486
|
+
`${gateway}/api/v0/version`,
|
|
3487
|
+
this.connectivityTimeoutMs,
|
|
3488
|
+
{ method: "POST" }
|
|
3489
|
+
);
|
|
3490
|
+
if (!response.ok) {
|
|
3491
|
+
return { gateway, healthy: false, error: `HTTP ${response.status}` };
|
|
3492
|
+
}
|
|
3493
|
+
return {
|
|
3494
|
+
gateway,
|
|
3495
|
+
healthy: true,
|
|
3496
|
+
responseTimeMs: Date.now() - start
|
|
3497
|
+
};
|
|
3498
|
+
} catch (error) {
|
|
3499
|
+
return {
|
|
3500
|
+
gateway,
|
|
3501
|
+
healthy: false,
|
|
3502
|
+
error: error instanceof Error ? error.message : String(error)
|
|
3503
|
+
};
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
/**
|
|
3507
|
+
* Find healthy gateways from the configured list.
|
|
3508
|
+
*/
|
|
3509
|
+
async findHealthyGateways() {
|
|
3510
|
+
const results = await Promise.allSettled(
|
|
3511
|
+
this.gateways.map((gw) => this.testConnectivity(gw))
|
|
3512
|
+
);
|
|
3513
|
+
return results.filter((r) => r.status === "fulfilled" && r.value.healthy).map((r) => r.value.gateway);
|
|
3514
|
+
}
|
|
3515
|
+
/**
|
|
3516
|
+
* Get gateways that are not in circuit breaker cooldown.
|
|
3517
|
+
*/
|
|
3518
|
+
getAvailableGateways() {
|
|
3519
|
+
return this.gateways.filter((gw) => !this.cache.isGatewayInCooldown(gw));
|
|
3520
|
+
}
|
|
3521
|
+
// ---------------------------------------------------------------------------
|
|
3522
|
+
// Content Upload
|
|
3523
|
+
// ---------------------------------------------------------------------------
|
|
3524
|
+
/**
|
|
3525
|
+
* Upload JSON content to IPFS.
|
|
3526
|
+
* Tries all gateways in parallel, returns first success.
|
|
3527
|
+
*/
|
|
3528
|
+
async upload(data, gateways) {
|
|
3529
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
3530
|
+
if (targets.length === 0) {
|
|
3531
|
+
throw new IpfsError("No gateways available for upload", "NETWORK_ERROR");
|
|
3532
|
+
}
|
|
3533
|
+
const jsonBytes = new TextEncoder().encode(JSON.stringify(data));
|
|
3534
|
+
const promises = targets.map(async (gateway) => {
|
|
3535
|
+
try {
|
|
3536
|
+
const formData = new FormData();
|
|
3537
|
+
formData.append("file", new Blob([jsonBytes], { type: "application/json" }), "data.json");
|
|
3538
|
+
const response = await this.fetchWithTimeout(
|
|
3539
|
+
`${gateway}/api/v0/add?pin=true&cid-version=1`,
|
|
3540
|
+
this.publishTimeoutMs,
|
|
3541
|
+
{ method: "POST", body: formData }
|
|
3542
|
+
);
|
|
3543
|
+
if (!response.ok) {
|
|
3544
|
+
throw new IpfsError(
|
|
3545
|
+
`Upload failed: HTTP ${response.status}`,
|
|
3546
|
+
classifyHttpStatus(response.status),
|
|
3547
|
+
gateway
|
|
3548
|
+
);
|
|
3549
|
+
}
|
|
3550
|
+
const result = await response.json();
|
|
3551
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
3552
|
+
this.log(`Uploaded to ${gateway}: CID=${result.Hash}`);
|
|
3553
|
+
return { cid: result.Hash, gateway };
|
|
3554
|
+
} catch (error) {
|
|
3555
|
+
if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
|
|
3556
|
+
this.cache.recordGatewayFailure(gateway);
|
|
3557
|
+
}
|
|
3558
|
+
throw error;
|
|
3559
|
+
}
|
|
3560
|
+
});
|
|
3561
|
+
try {
|
|
3562
|
+
const result = await Promise.any(promises);
|
|
3563
|
+
return { cid: result.cid };
|
|
3564
|
+
} catch (error) {
|
|
3565
|
+
if (error instanceof AggregateError) {
|
|
3566
|
+
throw new IpfsError(
|
|
3567
|
+
`Upload failed on all gateways: ${error.errors.map((e) => e.message).join("; ")}`,
|
|
3568
|
+
"NETWORK_ERROR"
|
|
3569
|
+
);
|
|
3570
|
+
}
|
|
3571
|
+
throw error;
|
|
3572
|
+
}
|
|
3573
|
+
}
|
|
3574
|
+
// ---------------------------------------------------------------------------
|
|
3575
|
+
// Content Fetch
|
|
3576
|
+
// ---------------------------------------------------------------------------
|
|
3577
|
+
/**
|
|
3578
|
+
* Fetch content by CID from IPFS gateways.
|
|
3579
|
+
* Checks content cache first. Races all gateways for fastest response.
|
|
3580
|
+
*/
|
|
3581
|
+
async fetchContent(cid, gateways) {
|
|
3582
|
+
const cached = this.cache.getContent(cid);
|
|
3583
|
+
if (cached) {
|
|
3584
|
+
this.log(`Content cache hit for CID=${cid}`);
|
|
3585
|
+
return cached;
|
|
3586
|
+
}
|
|
3587
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
3588
|
+
if (targets.length === 0) {
|
|
3589
|
+
throw new IpfsError("No gateways available for fetch", "NETWORK_ERROR");
|
|
3590
|
+
}
|
|
3591
|
+
const promises = targets.map(async (gateway) => {
|
|
3592
|
+
try {
|
|
3593
|
+
const response = await this.fetchWithTimeout(
|
|
3594
|
+
`${gateway}/ipfs/${cid}`,
|
|
3595
|
+
this.fetchTimeoutMs,
|
|
3596
|
+
{ headers: { Accept: "application/octet-stream" } }
|
|
3597
|
+
);
|
|
3598
|
+
if (!response.ok) {
|
|
3599
|
+
const body = await response.text().catch(() => "");
|
|
3600
|
+
throw new IpfsError(
|
|
3601
|
+
`Fetch failed: HTTP ${response.status}`,
|
|
3602
|
+
classifyHttpStatus(response.status, body),
|
|
3603
|
+
gateway
|
|
3604
|
+
);
|
|
3605
|
+
}
|
|
3606
|
+
const data = await response.json();
|
|
3607
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
3608
|
+
this.cache.setContent(cid, data);
|
|
3609
|
+
this.log(`Fetched from ${gateway}: CID=${cid}`);
|
|
3610
|
+
return data;
|
|
3611
|
+
} catch (error) {
|
|
3612
|
+
if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
|
|
3613
|
+
this.cache.recordGatewayFailure(gateway);
|
|
3614
|
+
}
|
|
3615
|
+
throw error;
|
|
3616
|
+
}
|
|
3617
|
+
});
|
|
3618
|
+
try {
|
|
3619
|
+
return await Promise.any(promises);
|
|
3620
|
+
} catch (error) {
|
|
3621
|
+
if (error instanceof AggregateError) {
|
|
3622
|
+
throw new IpfsError(
|
|
3623
|
+
`Fetch failed on all gateways for CID=${cid}`,
|
|
3624
|
+
"NETWORK_ERROR"
|
|
3625
|
+
);
|
|
3626
|
+
}
|
|
3627
|
+
throw error;
|
|
3628
|
+
}
|
|
3629
|
+
}
|
|
3630
|
+
// ---------------------------------------------------------------------------
|
|
3631
|
+
// IPNS Resolution
|
|
3632
|
+
// ---------------------------------------------------------------------------
|
|
3633
|
+
/**
|
|
3634
|
+
* Resolve IPNS via Routing API (returns record with sequence number).
|
|
3635
|
+
* POST /api/v0/routing/get?arg=/ipns/{name}
|
|
3636
|
+
*/
|
|
3637
|
+
async resolveIpnsViaRoutingApi(gateway, ipnsName, timeoutMs = DEFAULT_ROUTING_API_TIMEOUT_MS) {
|
|
3638
|
+
try {
|
|
3639
|
+
const response = await this.fetchWithTimeout(
|
|
3640
|
+
`${gateway}/api/v0/routing/get?arg=/ipns/${ipnsName}`,
|
|
3641
|
+
timeoutMs,
|
|
3642
|
+
{ method: "POST" }
|
|
3643
|
+
);
|
|
3644
|
+
if (!response.ok) {
|
|
3645
|
+
const body = await response.text().catch(() => "");
|
|
3646
|
+
const category = classifyHttpStatus(response.status, body);
|
|
3647
|
+
if (category === "NOT_FOUND") return null;
|
|
3648
|
+
throw new IpfsError(`Routing API: HTTP ${response.status}`, category, gateway);
|
|
3649
|
+
}
|
|
3650
|
+
const text = await response.text();
|
|
3651
|
+
const parsed = await parseRoutingApiResponse(text);
|
|
3652
|
+
if (!parsed) return null;
|
|
3653
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
3654
|
+
return {
|
|
3655
|
+
cid: parsed.cid,
|
|
3656
|
+
sequence: parsed.sequence,
|
|
3657
|
+
gateway,
|
|
3658
|
+
recordData: parsed.recordData
|
|
3659
|
+
};
|
|
3660
|
+
} catch (error) {
|
|
3661
|
+
if (error instanceof IpfsError) throw error;
|
|
3662
|
+
const category = classifyFetchError(error);
|
|
3663
|
+
if (category !== "NOT_FOUND") {
|
|
3664
|
+
this.cache.recordGatewayFailure(gateway);
|
|
3665
|
+
}
|
|
3666
|
+
return null;
|
|
3667
|
+
}
|
|
3668
|
+
}
|
|
3669
|
+
/**
|
|
3670
|
+
* Resolve IPNS via gateway path (simpler, no sequence number).
|
|
3671
|
+
* GET /ipns/{name}?format=dag-json
|
|
3672
|
+
*/
|
|
3673
|
+
async resolveIpnsViaGatewayPath(gateway, ipnsName, timeoutMs = DEFAULT_GATEWAY_PATH_TIMEOUT_MS) {
|
|
3674
|
+
try {
|
|
3675
|
+
const response = await this.fetchWithTimeout(
|
|
3676
|
+
`${gateway}/ipns/${ipnsName}`,
|
|
3677
|
+
timeoutMs,
|
|
3678
|
+
{ headers: { Accept: "application/json" } }
|
|
3679
|
+
);
|
|
3680
|
+
if (!response.ok) return null;
|
|
3681
|
+
const content = await response.json();
|
|
3682
|
+
const cidHeader = response.headers.get("X-Ipfs-Path");
|
|
3683
|
+
if (cidHeader) {
|
|
3684
|
+
const match = cidHeader.match(/\/ipfs\/([a-zA-Z0-9]+)/);
|
|
3685
|
+
if (match) {
|
|
3686
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
3687
|
+
return { cid: match[1], content };
|
|
3688
|
+
}
|
|
3689
|
+
}
|
|
3690
|
+
return { cid: "", content };
|
|
3691
|
+
} catch {
|
|
3692
|
+
return null;
|
|
3693
|
+
}
|
|
3694
|
+
}
|
|
3695
|
+
/**
|
|
3696
|
+
* Progressive IPNS resolution across all gateways.
|
|
3697
|
+
* Queries all gateways in parallel, returns highest sequence number.
|
|
3698
|
+
*/
|
|
3699
|
+
async resolveIpns(ipnsName, gateways) {
|
|
3700
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
3701
|
+
if (targets.length === 0) {
|
|
3702
|
+
return { best: null, allResults: [], respondedCount: 0, totalGateways: 0 };
|
|
3703
|
+
}
|
|
3704
|
+
const results = [];
|
|
3705
|
+
let respondedCount = 0;
|
|
3706
|
+
const promises = targets.map(async (gateway) => {
|
|
3707
|
+
const result = await this.resolveIpnsViaRoutingApi(
|
|
3708
|
+
gateway,
|
|
3709
|
+
ipnsName,
|
|
3710
|
+
this.resolveTimeoutMs
|
|
3711
|
+
);
|
|
3712
|
+
if (result) results.push(result);
|
|
3713
|
+
respondedCount++;
|
|
3714
|
+
return result;
|
|
3715
|
+
});
|
|
3716
|
+
await Promise.race([
|
|
3717
|
+
Promise.allSettled(promises),
|
|
3718
|
+
new Promise((resolve) => setTimeout(resolve, this.resolveTimeoutMs + 1e3))
|
|
3719
|
+
]);
|
|
3720
|
+
let best = null;
|
|
3721
|
+
for (const result of results) {
|
|
3722
|
+
if (!best || result.sequence > best.sequence) {
|
|
3723
|
+
best = result;
|
|
3724
|
+
}
|
|
3725
|
+
}
|
|
3726
|
+
if (best) {
|
|
3727
|
+
this.cache.setIpnsRecord(ipnsName, best);
|
|
3728
|
+
}
|
|
3729
|
+
return {
|
|
3730
|
+
best,
|
|
3731
|
+
allResults: results,
|
|
3732
|
+
respondedCount,
|
|
3733
|
+
totalGateways: targets.length
|
|
3734
|
+
};
|
|
3735
|
+
}
|
|
3736
|
+
// ---------------------------------------------------------------------------
|
|
3737
|
+
// IPNS Publishing
|
|
3738
|
+
// ---------------------------------------------------------------------------
|
|
3739
|
+
/**
|
|
3740
|
+
* Publish IPNS record to a single gateway via routing API.
|
|
3741
|
+
*/
|
|
3742
|
+
async publishIpnsViaRoutingApi(gateway, ipnsName, marshalledRecord, timeoutMs = DEFAULT_PUBLISH_TIMEOUT_MS) {
|
|
3743
|
+
try {
|
|
3744
|
+
const formData = new FormData();
|
|
3745
|
+
formData.append(
|
|
3746
|
+
"file",
|
|
3747
|
+
new Blob([new Uint8Array(marshalledRecord)]),
|
|
3748
|
+
"record"
|
|
3749
|
+
);
|
|
3750
|
+
const response = await this.fetchWithTimeout(
|
|
3751
|
+
`${gateway}/api/v0/routing/put?arg=/ipns/${ipnsName}&allow-offline=true`,
|
|
3752
|
+
timeoutMs,
|
|
3753
|
+
{ method: "POST", body: formData }
|
|
3754
|
+
);
|
|
3755
|
+
if (!response.ok) {
|
|
3756
|
+
const errorText = await response.text().catch(() => "");
|
|
3757
|
+
throw new IpfsError(
|
|
3758
|
+
`IPNS publish: HTTP ${response.status}: ${errorText.slice(0, 100)}`,
|
|
3759
|
+
classifyHttpStatus(response.status, errorText),
|
|
3760
|
+
gateway
|
|
3761
|
+
);
|
|
3762
|
+
}
|
|
3763
|
+
this.cache.recordGatewaySuccess(gateway);
|
|
3764
|
+
this.log(`IPNS published to ${gateway}: ${ipnsName}`);
|
|
3765
|
+
return true;
|
|
3766
|
+
} catch (error) {
|
|
3767
|
+
if (error instanceof IpfsError && error.shouldTriggerCircuitBreaker) {
|
|
3768
|
+
this.cache.recordGatewayFailure(gateway);
|
|
3769
|
+
}
|
|
3770
|
+
this.log(`IPNS publish to ${gateway} failed: ${error}`);
|
|
3771
|
+
return false;
|
|
3772
|
+
}
|
|
3773
|
+
}
|
|
3774
|
+
/**
|
|
3775
|
+
* Publish IPNS record to all gateways in parallel.
|
|
3776
|
+
*/
|
|
3777
|
+
async publishIpns(ipnsName, marshalledRecord, gateways) {
|
|
3778
|
+
const targets = gateways ?? this.getAvailableGateways();
|
|
3779
|
+
if (targets.length === 0) {
|
|
3780
|
+
return { success: false, error: "No gateways available" };
|
|
3781
|
+
}
|
|
3782
|
+
const results = await Promise.allSettled(
|
|
3783
|
+
targets.map((gw) => this.publishIpnsViaRoutingApi(gw, ipnsName, marshalledRecord, this.publishTimeoutMs))
|
|
3784
|
+
);
|
|
3785
|
+
const successfulGateways = [];
|
|
3786
|
+
results.forEach((result, index) => {
|
|
3787
|
+
if (result.status === "fulfilled" && result.value) {
|
|
3788
|
+
successfulGateways.push(targets[index]);
|
|
3789
|
+
}
|
|
3790
|
+
});
|
|
3791
|
+
return {
|
|
3792
|
+
success: successfulGateways.length > 0,
|
|
3793
|
+
ipnsName,
|
|
3794
|
+
successfulGateways,
|
|
3795
|
+
error: successfulGateways.length === 0 ? "All gateways failed" : void 0
|
|
3796
|
+
};
|
|
3797
|
+
}
|
|
3798
|
+
// ---------------------------------------------------------------------------
|
|
3799
|
+
// IPNS Verification
|
|
3800
|
+
// ---------------------------------------------------------------------------
|
|
3801
|
+
/**
|
|
3802
|
+
* Verify IPNS record persistence after publishing.
|
|
3803
|
+
* Retries resolution to confirm the record was accepted.
|
|
3804
|
+
*/
|
|
3805
|
+
async verifyIpnsRecord(ipnsName, expectedSeq, expectedCid, retries = 3, delayMs = 1e3) {
|
|
3806
|
+
for (let i = 0; i < retries; i++) {
|
|
3807
|
+
if (i > 0) {
|
|
3808
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
3809
|
+
}
|
|
3810
|
+
const { best } = await this.resolveIpns(ipnsName);
|
|
3811
|
+
if (best && best.sequence >= expectedSeq && best.cid === expectedCid) {
|
|
3812
|
+
return true;
|
|
3813
|
+
}
|
|
3814
|
+
}
|
|
3815
|
+
return false;
|
|
3816
|
+
}
|
|
3817
|
+
// ---------------------------------------------------------------------------
|
|
3818
|
+
// Helpers
|
|
3819
|
+
// ---------------------------------------------------------------------------
|
|
3820
|
+
async fetchWithTimeout(url, timeoutMs, options) {
|
|
3821
|
+
const controller = new AbortController();
|
|
3822
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
3823
|
+
try {
|
|
3824
|
+
return await fetch(url, {
|
|
3825
|
+
...options,
|
|
3826
|
+
signal: controller.signal
|
|
3827
|
+
});
|
|
3828
|
+
} finally {
|
|
3829
|
+
clearTimeout(timer);
|
|
3830
|
+
}
|
|
3831
|
+
}
|
|
3832
|
+
log(message) {
|
|
3833
|
+
if (this.debug) {
|
|
3834
|
+
console.log(`[IPFS-HTTP] ${message}`);
|
|
3835
|
+
}
|
|
3836
|
+
}
|
|
3837
|
+
};
|
|
3838
|
+
|
|
3839
|
+
// impl/shared/ipfs/txf-merge.ts
|
|
3840
|
+
function mergeTxfData(local, remote) {
|
|
3841
|
+
let added = 0;
|
|
3842
|
+
let removed = 0;
|
|
3843
|
+
let conflicts = 0;
|
|
3844
|
+
const localVersion = local._meta?.version ?? 0;
|
|
3845
|
+
const remoteVersion = remote._meta?.version ?? 0;
|
|
3846
|
+
const baseMeta = localVersion >= remoteVersion ? local._meta : remote._meta;
|
|
3847
|
+
const mergedMeta = {
|
|
3848
|
+
...baseMeta,
|
|
3849
|
+
version: Math.max(localVersion, remoteVersion) + 1,
|
|
3850
|
+
updatedAt: Date.now()
|
|
3851
|
+
};
|
|
3852
|
+
const mergedTombstones = mergeTombstones(
|
|
3853
|
+
local._tombstones ?? [],
|
|
3854
|
+
remote._tombstones ?? []
|
|
3855
|
+
);
|
|
3856
|
+
const tombstoneKeys = new Set(
|
|
3857
|
+
mergedTombstones.map((t) => `${t.tokenId}:${t.stateHash}`)
|
|
3858
|
+
);
|
|
3859
|
+
const localTokenKeys = getTokenKeys(local);
|
|
3860
|
+
const remoteTokenKeys = getTokenKeys(remote);
|
|
3861
|
+
const allTokenKeys = /* @__PURE__ */ new Set([...localTokenKeys, ...remoteTokenKeys]);
|
|
3862
|
+
const mergedTokens = {};
|
|
3863
|
+
for (const key of allTokenKeys) {
|
|
3864
|
+
const tokenId = key.startsWith("_") ? key.slice(1) : key;
|
|
3865
|
+
const localToken = local[key];
|
|
3866
|
+
const remoteToken = remote[key];
|
|
3867
|
+
if (isTokenTombstoned(tokenId, localToken, remoteToken, tombstoneKeys)) {
|
|
3868
|
+
if (localTokenKeys.has(key)) removed++;
|
|
3869
|
+
continue;
|
|
3870
|
+
}
|
|
3871
|
+
if (localToken && !remoteToken) {
|
|
3872
|
+
mergedTokens[key] = localToken;
|
|
3873
|
+
} else if (!localToken && remoteToken) {
|
|
3874
|
+
mergedTokens[key] = remoteToken;
|
|
3875
|
+
added++;
|
|
3876
|
+
} else if (localToken && remoteToken) {
|
|
3877
|
+
mergedTokens[key] = localToken;
|
|
3878
|
+
conflicts++;
|
|
3879
|
+
}
|
|
3880
|
+
}
|
|
3881
|
+
const mergedOutbox = mergeArrayById(
|
|
3882
|
+
local._outbox ?? [],
|
|
3883
|
+
remote._outbox ?? [],
|
|
3884
|
+
"id"
|
|
3885
|
+
);
|
|
3886
|
+
const mergedSent = mergeArrayById(
|
|
3887
|
+
local._sent ?? [],
|
|
3888
|
+
remote._sent ?? [],
|
|
3889
|
+
"tokenId"
|
|
3890
|
+
);
|
|
3891
|
+
const mergedInvalid = mergeArrayById(
|
|
3892
|
+
local._invalid ?? [],
|
|
3893
|
+
remote._invalid ?? [],
|
|
3894
|
+
"tokenId"
|
|
3895
|
+
);
|
|
3896
|
+
const localNametags = local._nametags ?? [];
|
|
3897
|
+
const remoteNametags = remote._nametags ?? [];
|
|
3898
|
+
const mergedNametags = mergeNametagsByName(localNametags, remoteNametags);
|
|
3899
|
+
const merged = {
|
|
3900
|
+
_meta: mergedMeta,
|
|
3901
|
+
_tombstones: mergedTombstones.length > 0 ? mergedTombstones : void 0,
|
|
3902
|
+
_nametags: mergedNametags.length > 0 ? mergedNametags : void 0,
|
|
3903
|
+
_outbox: mergedOutbox.length > 0 ? mergedOutbox : void 0,
|
|
3904
|
+
_sent: mergedSent.length > 0 ? mergedSent : void 0,
|
|
3905
|
+
_invalid: mergedInvalid.length > 0 ? mergedInvalid : void 0,
|
|
3906
|
+
...mergedTokens
|
|
3907
|
+
};
|
|
3908
|
+
return { merged, added, removed, conflicts };
|
|
3909
|
+
}
|
|
3910
|
+
function mergeTombstones(local, remote) {
|
|
3911
|
+
const merged = /* @__PURE__ */ new Map();
|
|
3912
|
+
for (const tombstone of [...local, ...remote]) {
|
|
3913
|
+
const key = `${tombstone.tokenId}:${tombstone.stateHash}`;
|
|
3914
|
+
const existing = merged.get(key);
|
|
3915
|
+
if (!existing || tombstone.timestamp > existing.timestamp) {
|
|
3916
|
+
merged.set(key, tombstone);
|
|
3917
|
+
}
|
|
3918
|
+
}
|
|
3919
|
+
return Array.from(merged.values());
|
|
3920
|
+
}
|
|
3921
|
+
function getTokenKeys(data) {
|
|
3922
|
+
const reservedKeys = /* @__PURE__ */ new Set([
|
|
3923
|
+
"_meta",
|
|
3924
|
+
"_tombstones",
|
|
3925
|
+
"_outbox",
|
|
3926
|
+
"_sent",
|
|
3927
|
+
"_invalid",
|
|
3928
|
+
"_nametag",
|
|
3929
|
+
"_nametags",
|
|
3930
|
+
"_mintOutbox",
|
|
3931
|
+
"_invalidatedNametags",
|
|
3932
|
+
"_integrity"
|
|
3933
|
+
]);
|
|
3934
|
+
const keys = /* @__PURE__ */ new Set();
|
|
3935
|
+
for (const key of Object.keys(data)) {
|
|
3936
|
+
if (reservedKeys.has(key)) continue;
|
|
3937
|
+
if (key.startsWith("archived-") || key.startsWith("_forked_")) continue;
|
|
3938
|
+
keys.add(key);
|
|
3939
|
+
}
|
|
3940
|
+
return keys;
|
|
3941
|
+
}
|
|
3942
|
+
function isTokenTombstoned(tokenId, localToken, remoteToken, tombstoneKeys) {
|
|
3943
|
+
for (const key of tombstoneKeys) {
|
|
3944
|
+
if (key.startsWith(`${tokenId}:`)) {
|
|
3945
|
+
return true;
|
|
3946
|
+
}
|
|
3947
|
+
}
|
|
3948
|
+
void localToken;
|
|
3949
|
+
void remoteToken;
|
|
3950
|
+
return false;
|
|
3951
|
+
}
|
|
3952
|
+
function mergeNametagsByName(local, remote) {
|
|
3953
|
+
const seen = /* @__PURE__ */ new Map();
|
|
3954
|
+
for (const item of local) {
|
|
3955
|
+
if (item.name) seen.set(item.name, item);
|
|
3956
|
+
}
|
|
3957
|
+
for (const item of remote) {
|
|
3958
|
+
if (item.name && !seen.has(item.name)) {
|
|
3959
|
+
seen.set(item.name, item);
|
|
3960
|
+
}
|
|
3961
|
+
}
|
|
3962
|
+
return Array.from(seen.values());
|
|
3963
|
+
}
|
|
3964
|
+
function mergeArrayById(local, remote, idField) {
|
|
3965
|
+
const seen = /* @__PURE__ */ new Map();
|
|
3966
|
+
for (const item of local) {
|
|
3967
|
+
const id = item[idField];
|
|
3968
|
+
if (id !== void 0) {
|
|
3969
|
+
seen.set(id, item);
|
|
3970
|
+
}
|
|
3971
|
+
}
|
|
3972
|
+
for (const item of remote) {
|
|
3973
|
+
const id = item[idField];
|
|
3974
|
+
if (id !== void 0 && !seen.has(id)) {
|
|
3975
|
+
seen.set(id, item);
|
|
3976
|
+
}
|
|
3977
|
+
}
|
|
3978
|
+
return Array.from(seen.values());
|
|
3979
|
+
}
|
|
3980
|
+
|
|
3981
|
+
// impl/shared/ipfs/ipns-subscription-client.ts
|
|
3982
|
+
var IpnsSubscriptionClient = class {
|
|
3983
|
+
ws = null;
|
|
3984
|
+
subscriptions = /* @__PURE__ */ new Map();
|
|
3985
|
+
reconnectTimeout = null;
|
|
3986
|
+
pingInterval = null;
|
|
3987
|
+
fallbackPollInterval = null;
|
|
3988
|
+
wsUrl;
|
|
3989
|
+
createWebSocket;
|
|
3990
|
+
pingIntervalMs;
|
|
3991
|
+
initialReconnectDelayMs;
|
|
3992
|
+
maxReconnectDelayMs;
|
|
3993
|
+
debugEnabled;
|
|
3994
|
+
reconnectAttempts = 0;
|
|
3995
|
+
isConnecting = false;
|
|
3996
|
+
connectionOpenedAt = 0;
|
|
3997
|
+
destroyed = false;
|
|
3998
|
+
/** Minimum stable connection time before resetting backoff (30 seconds) */
|
|
3999
|
+
minStableConnectionMs = 3e4;
|
|
4000
|
+
fallbackPollFn = null;
|
|
4001
|
+
fallbackPollIntervalMs = 0;
|
|
4002
|
+
constructor(config) {
|
|
4003
|
+
this.wsUrl = config.wsUrl;
|
|
4004
|
+
this.createWebSocket = config.createWebSocket;
|
|
4005
|
+
this.pingIntervalMs = config.pingIntervalMs ?? 3e4;
|
|
4006
|
+
this.initialReconnectDelayMs = config.reconnectDelayMs ?? 5e3;
|
|
4007
|
+
this.maxReconnectDelayMs = config.maxReconnectDelayMs ?? 6e4;
|
|
4008
|
+
this.debugEnabled = config.debug ?? false;
|
|
4009
|
+
}
|
|
4010
|
+
// ---------------------------------------------------------------------------
|
|
4011
|
+
// Public API
|
|
4012
|
+
// ---------------------------------------------------------------------------
|
|
4013
|
+
/**
|
|
4014
|
+
* Subscribe to IPNS updates for a specific name.
|
|
4015
|
+
* Automatically connects the WebSocket if not already connected.
|
|
4016
|
+
* If WebSocket is connecting, the name will be subscribed once connected.
|
|
4017
|
+
*/
|
|
4018
|
+
subscribe(ipnsName, callback) {
|
|
4019
|
+
if (!ipnsName || typeof ipnsName !== "string") {
|
|
4020
|
+
this.log("Invalid IPNS name for subscription");
|
|
4021
|
+
return () => {
|
|
4022
|
+
};
|
|
4023
|
+
}
|
|
4024
|
+
const isNewSubscription = !this.subscriptions.has(ipnsName);
|
|
4025
|
+
if (isNewSubscription) {
|
|
4026
|
+
this.subscriptions.set(ipnsName, /* @__PURE__ */ new Set());
|
|
4027
|
+
}
|
|
4028
|
+
this.subscriptions.get(ipnsName).add(callback);
|
|
4029
|
+
if (isNewSubscription && this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
4030
|
+
this.sendSubscribe([ipnsName]);
|
|
4031
|
+
}
|
|
4032
|
+
if (!this.ws || this.ws.readyState !== WebSocketReadyState.OPEN) {
|
|
4033
|
+
this.connect();
|
|
4034
|
+
}
|
|
4035
|
+
return () => {
|
|
4036
|
+
const callbacks = this.subscriptions.get(ipnsName);
|
|
4037
|
+
if (callbacks) {
|
|
4038
|
+
callbacks.delete(callback);
|
|
4039
|
+
if (callbacks.size === 0) {
|
|
4040
|
+
this.subscriptions.delete(ipnsName);
|
|
4041
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
4042
|
+
this.sendUnsubscribe([ipnsName]);
|
|
4043
|
+
}
|
|
4044
|
+
if (this.subscriptions.size === 0) {
|
|
4045
|
+
this.disconnect();
|
|
4046
|
+
}
|
|
4047
|
+
}
|
|
4048
|
+
}
|
|
4049
|
+
};
|
|
4050
|
+
}
|
|
4051
|
+
/**
|
|
4052
|
+
* Register a convenience update callback for all subscriptions.
|
|
4053
|
+
* Returns an unsubscribe function.
|
|
4054
|
+
*/
|
|
4055
|
+
onUpdate(callback) {
|
|
4056
|
+
if (!this.subscriptions.has("*")) {
|
|
4057
|
+
this.subscriptions.set("*", /* @__PURE__ */ new Set());
|
|
4058
|
+
}
|
|
4059
|
+
this.subscriptions.get("*").add(callback);
|
|
4060
|
+
return () => {
|
|
4061
|
+
const callbacks = this.subscriptions.get("*");
|
|
4062
|
+
if (callbacks) {
|
|
4063
|
+
callbacks.delete(callback);
|
|
4064
|
+
if (callbacks.size === 0) {
|
|
4065
|
+
this.subscriptions.delete("*");
|
|
4066
|
+
}
|
|
4067
|
+
}
|
|
4068
|
+
};
|
|
4069
|
+
}
|
|
4070
|
+
/**
|
|
4071
|
+
* Set a fallback poll function to use when WebSocket is disconnected.
|
|
4072
|
+
* The poll function will be called at the specified interval while WS is down.
|
|
4073
|
+
*/
|
|
4074
|
+
setFallbackPoll(fn, intervalMs) {
|
|
4075
|
+
this.fallbackPollFn = fn;
|
|
4076
|
+
this.fallbackPollIntervalMs = intervalMs;
|
|
4077
|
+
if (!this.isConnected()) {
|
|
4078
|
+
this.startFallbackPolling();
|
|
4079
|
+
}
|
|
4080
|
+
}
|
|
4081
|
+
/**
|
|
4082
|
+
* Connect to the WebSocket server.
|
|
4083
|
+
*/
|
|
4084
|
+
connect() {
|
|
4085
|
+
if (this.destroyed) return;
|
|
4086
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN || this.isConnecting) {
|
|
4087
|
+
return;
|
|
4088
|
+
}
|
|
4089
|
+
this.isConnecting = true;
|
|
4090
|
+
try {
|
|
4091
|
+
this.log(`Connecting to ${this.wsUrl}...`);
|
|
4092
|
+
this.ws = this.createWebSocket(this.wsUrl);
|
|
4093
|
+
this.ws.onopen = () => {
|
|
4094
|
+
this.log("WebSocket connected");
|
|
4095
|
+
this.isConnecting = false;
|
|
4096
|
+
this.connectionOpenedAt = Date.now();
|
|
4097
|
+
const names = Array.from(this.subscriptions.keys()).filter((n) => n !== "*");
|
|
4098
|
+
if (names.length > 0) {
|
|
4099
|
+
this.sendSubscribe(names);
|
|
4100
|
+
}
|
|
4101
|
+
this.startPingInterval();
|
|
4102
|
+
this.stopFallbackPolling();
|
|
4103
|
+
};
|
|
4104
|
+
this.ws.onmessage = (event) => {
|
|
4105
|
+
this.handleMessage(event.data);
|
|
4106
|
+
};
|
|
4107
|
+
this.ws.onclose = () => {
|
|
4108
|
+
const connectionDuration = this.connectionOpenedAt > 0 ? Date.now() - this.connectionOpenedAt : 0;
|
|
4109
|
+
const wasStable = connectionDuration >= this.minStableConnectionMs;
|
|
4110
|
+
this.log(`WebSocket closed (duration: ${Math.round(connectionDuration / 1e3)}s)`);
|
|
4111
|
+
this.isConnecting = false;
|
|
4112
|
+
this.connectionOpenedAt = 0;
|
|
4113
|
+
this.stopPingInterval();
|
|
4114
|
+
if (wasStable) {
|
|
4115
|
+
this.reconnectAttempts = 0;
|
|
4116
|
+
}
|
|
4117
|
+
this.startFallbackPolling();
|
|
4118
|
+
this.scheduleReconnect();
|
|
4119
|
+
};
|
|
4120
|
+
this.ws.onerror = () => {
|
|
4121
|
+
this.log("WebSocket error");
|
|
4122
|
+
this.isConnecting = false;
|
|
4123
|
+
};
|
|
4124
|
+
} catch (e) {
|
|
4125
|
+
this.log(`Failed to connect: ${e}`);
|
|
4126
|
+
this.isConnecting = false;
|
|
4127
|
+
this.startFallbackPolling();
|
|
4128
|
+
this.scheduleReconnect();
|
|
4129
|
+
}
|
|
4130
|
+
}
|
|
4131
|
+
/**
|
|
4132
|
+
* Disconnect from the WebSocket server and clean up.
|
|
4133
|
+
*/
|
|
4134
|
+
disconnect() {
|
|
4135
|
+
this.destroyed = true;
|
|
4136
|
+
if (this.reconnectTimeout) {
|
|
4137
|
+
clearTimeout(this.reconnectTimeout);
|
|
4138
|
+
this.reconnectTimeout = null;
|
|
4139
|
+
}
|
|
4140
|
+
this.stopPingInterval();
|
|
4141
|
+
this.stopFallbackPolling();
|
|
4142
|
+
if (this.ws) {
|
|
4143
|
+
this.ws.onopen = null;
|
|
4144
|
+
this.ws.onclose = null;
|
|
4145
|
+
this.ws.onerror = null;
|
|
4146
|
+
this.ws.onmessage = null;
|
|
4147
|
+
this.ws.close();
|
|
4148
|
+
this.ws = null;
|
|
4149
|
+
}
|
|
4150
|
+
this.isConnecting = false;
|
|
4151
|
+
this.reconnectAttempts = 0;
|
|
4152
|
+
}
|
|
4153
|
+
/**
|
|
4154
|
+
* Check if connected to the WebSocket server.
|
|
4155
|
+
*/
|
|
4156
|
+
isConnected() {
|
|
4157
|
+
return this.ws?.readyState === WebSocketReadyState.OPEN;
|
|
4158
|
+
}
|
|
4159
|
+
// ---------------------------------------------------------------------------
|
|
4160
|
+
// Internal: Message Handling
|
|
4161
|
+
// ---------------------------------------------------------------------------
|
|
4162
|
+
handleMessage(data) {
|
|
4163
|
+
try {
|
|
4164
|
+
const message = JSON.parse(data);
|
|
4165
|
+
switch (message.type) {
|
|
4166
|
+
case "update":
|
|
4167
|
+
if (message.name && message.sequence !== void 0) {
|
|
4168
|
+
this.notifySubscribers({
|
|
4169
|
+
type: "update",
|
|
4170
|
+
name: message.name,
|
|
4171
|
+
sequence: message.sequence,
|
|
4172
|
+
cid: message.cid ?? "",
|
|
4173
|
+
timestamp: message.timestamp || (/* @__PURE__ */ new Date()).toISOString()
|
|
4174
|
+
});
|
|
4175
|
+
}
|
|
4176
|
+
break;
|
|
4177
|
+
case "subscribed":
|
|
4178
|
+
this.log(`Subscribed to ${message.names?.length || 0} names`);
|
|
4179
|
+
break;
|
|
4180
|
+
case "unsubscribed":
|
|
4181
|
+
this.log(`Unsubscribed from ${message.names?.length || 0} names`);
|
|
4182
|
+
break;
|
|
4183
|
+
case "pong":
|
|
4184
|
+
break;
|
|
4185
|
+
case "error":
|
|
4186
|
+
this.log(`Server error: ${message.message}`);
|
|
4187
|
+
break;
|
|
4188
|
+
default:
|
|
4189
|
+
break;
|
|
4190
|
+
}
|
|
4191
|
+
} catch {
|
|
4192
|
+
this.log("Failed to parse message");
|
|
4193
|
+
}
|
|
4194
|
+
}
|
|
4195
|
+
notifySubscribers(update) {
|
|
4196
|
+
const callbacks = this.subscriptions.get(update.name);
|
|
4197
|
+
if (callbacks) {
|
|
4198
|
+
this.log(`Update: ${update.name.slice(0, 16)}... seq=${update.sequence}`);
|
|
4199
|
+
for (const callback of callbacks) {
|
|
4200
|
+
try {
|
|
4201
|
+
callback(update);
|
|
4202
|
+
} catch {
|
|
4203
|
+
}
|
|
4204
|
+
}
|
|
4205
|
+
}
|
|
4206
|
+
const globalCallbacks = this.subscriptions.get("*");
|
|
4207
|
+
if (globalCallbacks) {
|
|
4208
|
+
for (const callback of globalCallbacks) {
|
|
4209
|
+
try {
|
|
4210
|
+
callback(update);
|
|
4211
|
+
} catch {
|
|
4212
|
+
}
|
|
4213
|
+
}
|
|
4214
|
+
}
|
|
4215
|
+
}
|
|
4216
|
+
// ---------------------------------------------------------------------------
|
|
4217
|
+
// Internal: WebSocket Send
|
|
4218
|
+
// ---------------------------------------------------------------------------
|
|
4219
|
+
sendSubscribe(names) {
|
|
4220
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
4221
|
+
this.ws.send(JSON.stringify({ action: "subscribe", names }));
|
|
4222
|
+
}
|
|
4223
|
+
}
|
|
4224
|
+
sendUnsubscribe(names) {
|
|
4225
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
4226
|
+
this.ws.send(JSON.stringify({ action: "unsubscribe", names }));
|
|
4227
|
+
}
|
|
4228
|
+
}
|
|
4229
|
+
// ---------------------------------------------------------------------------
|
|
4230
|
+
// Internal: Reconnection
|
|
4231
|
+
// ---------------------------------------------------------------------------
|
|
4232
|
+
/**
|
|
4233
|
+
* Schedule reconnection with exponential backoff.
|
|
4234
|
+
* Sequence: 5s, 10s, 20s, 40s, 60s (capped)
|
|
4235
|
+
*/
|
|
4236
|
+
scheduleReconnect() {
|
|
4237
|
+
if (this.destroyed || this.reconnectTimeout) return;
|
|
4238
|
+
const realSubscriptions = Array.from(this.subscriptions.keys()).filter((n) => n !== "*");
|
|
4239
|
+
if (realSubscriptions.length === 0) return;
|
|
4240
|
+
this.reconnectAttempts++;
|
|
4241
|
+
const delay = Math.min(
|
|
4242
|
+
this.initialReconnectDelayMs * Math.pow(2, this.reconnectAttempts - 1),
|
|
4243
|
+
this.maxReconnectDelayMs
|
|
4244
|
+
);
|
|
4245
|
+
this.log(`Reconnecting in ${(delay / 1e3).toFixed(1)}s (attempt ${this.reconnectAttempts})...`);
|
|
4246
|
+
this.reconnectTimeout = setTimeout(() => {
|
|
4247
|
+
this.reconnectTimeout = null;
|
|
4248
|
+
this.connect();
|
|
4249
|
+
}, delay);
|
|
4250
|
+
}
|
|
4251
|
+
// ---------------------------------------------------------------------------
|
|
4252
|
+
// Internal: Keepalive
|
|
4253
|
+
// ---------------------------------------------------------------------------
|
|
4254
|
+
startPingInterval() {
|
|
4255
|
+
this.stopPingInterval();
|
|
4256
|
+
this.pingInterval = setInterval(() => {
|
|
4257
|
+
if (this.ws?.readyState === WebSocketReadyState.OPEN) {
|
|
4258
|
+
this.ws.send(JSON.stringify({ action: "ping" }));
|
|
4259
|
+
}
|
|
4260
|
+
}, this.pingIntervalMs);
|
|
4261
|
+
}
|
|
4262
|
+
stopPingInterval() {
|
|
4263
|
+
if (this.pingInterval) {
|
|
4264
|
+
clearInterval(this.pingInterval);
|
|
4265
|
+
this.pingInterval = null;
|
|
4266
|
+
}
|
|
4267
|
+
}
|
|
4268
|
+
// ---------------------------------------------------------------------------
|
|
4269
|
+
// Internal: Fallback Polling
|
|
4270
|
+
// ---------------------------------------------------------------------------
|
|
4271
|
+
startFallbackPolling() {
|
|
4272
|
+
if (this.fallbackPollInterval || !this.fallbackPollFn || this.destroyed) return;
|
|
4273
|
+
this.log(`Starting fallback polling (${this.fallbackPollIntervalMs / 1e3}s interval)`);
|
|
4274
|
+
this.fallbackPollFn().catch(() => {
|
|
4275
|
+
});
|
|
4276
|
+
this.fallbackPollInterval = setInterval(() => {
|
|
4277
|
+
this.fallbackPollFn?.().catch(() => {
|
|
4278
|
+
});
|
|
4279
|
+
}, this.fallbackPollIntervalMs);
|
|
4280
|
+
}
|
|
4281
|
+
stopFallbackPolling() {
|
|
4282
|
+
if (this.fallbackPollInterval) {
|
|
4283
|
+
clearInterval(this.fallbackPollInterval);
|
|
4284
|
+
this.fallbackPollInterval = null;
|
|
4285
|
+
}
|
|
4286
|
+
}
|
|
4287
|
+
// ---------------------------------------------------------------------------
|
|
4288
|
+
// Internal: Logging
|
|
4289
|
+
// ---------------------------------------------------------------------------
|
|
4290
|
+
log(message) {
|
|
4291
|
+
if (this.debugEnabled) {
|
|
4292
|
+
console.log(`[IPNS-WS] ${message}`);
|
|
4293
|
+
}
|
|
4294
|
+
}
|
|
4295
|
+
};
|
|
4296
|
+
|
|
4297
|
+
// impl/shared/ipfs/write-behind-buffer.ts
|
|
4298
|
+
var AsyncSerialQueue = class {
|
|
4299
|
+
tail = Promise.resolve();
|
|
4300
|
+
/** Enqueue an async operation. Returns when it completes. */
|
|
4301
|
+
enqueue(fn) {
|
|
4302
|
+
let resolve;
|
|
4303
|
+
let reject;
|
|
4304
|
+
const promise = new Promise((res, rej) => {
|
|
4305
|
+
resolve = res;
|
|
4306
|
+
reject = rej;
|
|
4307
|
+
});
|
|
4308
|
+
this.tail = this.tail.then(
|
|
4309
|
+
() => fn().then(resolve, reject),
|
|
4310
|
+
() => fn().then(resolve, reject)
|
|
4311
|
+
);
|
|
4312
|
+
return promise;
|
|
4313
|
+
}
|
|
4314
|
+
};
|
|
4315
|
+
var WriteBuffer = class {
|
|
4316
|
+
/** Full TXF data from save() calls — latest wins */
|
|
4317
|
+
txfData = null;
|
|
4318
|
+
get isEmpty() {
|
|
4319
|
+
return this.txfData === null;
|
|
4320
|
+
}
|
|
4321
|
+
clear() {
|
|
4322
|
+
this.txfData = null;
|
|
4323
|
+
}
|
|
4324
|
+
/**
|
|
4325
|
+
* Merge another buffer's contents into this one (for rollback).
|
|
4326
|
+
* Existing (newer) mutations in `this` take precedence over `other`.
|
|
4327
|
+
*/
|
|
4328
|
+
mergeFrom(other) {
|
|
4329
|
+
if (other.txfData && !this.txfData) {
|
|
4330
|
+
this.txfData = other.txfData;
|
|
4331
|
+
}
|
|
4332
|
+
}
|
|
4333
|
+
};
|
|
4334
|
+
|
|
4335
|
+
// impl/shared/ipfs/ipfs-storage-provider.ts
|
|
4336
|
+
var IpfsStorageProvider = class {
|
|
4337
|
+
id = "ipfs";
|
|
4338
|
+
name = "IPFS Storage";
|
|
4339
|
+
type = "p2p";
|
|
4340
|
+
status = "disconnected";
|
|
4341
|
+
identity = null;
|
|
4342
|
+
ipnsKeyPair = null;
|
|
4343
|
+
ipnsName = null;
|
|
4344
|
+
ipnsSequenceNumber = 0n;
|
|
4345
|
+
lastCid = null;
|
|
4346
|
+
lastKnownRemoteSequence = 0n;
|
|
4347
|
+
dataVersion = 0;
|
|
4348
|
+
/**
|
|
4349
|
+
* The CID currently stored on the sidecar for this IPNS name.
|
|
4350
|
+
* Used as `_meta.lastCid` in the next save to satisfy chain validation.
|
|
4351
|
+
* - null for bootstrap (first-ever save)
|
|
4352
|
+
* - set after every successful save() or load()
|
|
4353
|
+
*/
|
|
4354
|
+
remoteCid = null;
|
|
4355
|
+
cache;
|
|
4356
|
+
httpClient;
|
|
4357
|
+
statePersistence;
|
|
4358
|
+
eventCallbacks = /* @__PURE__ */ new Set();
|
|
4359
|
+
debug;
|
|
4360
|
+
ipnsLifetimeMs;
|
|
4361
|
+
/** WebSocket factory for push subscriptions */
|
|
4362
|
+
createWebSocket;
|
|
4363
|
+
/** Override WS URL */
|
|
4364
|
+
wsUrl;
|
|
4365
|
+
/** Fallback poll interval (default: 90000) */
|
|
4366
|
+
fallbackPollIntervalMs;
|
|
4367
|
+
/** IPNS subscription client for push notifications */
|
|
4368
|
+
subscriptionClient = null;
|
|
4369
|
+
/** Unsubscribe function from subscription client */
|
|
4370
|
+
subscriptionUnsubscribe = null;
|
|
4371
|
+
/** Write-behind buffer: serializes flush / sync / shutdown */
|
|
4372
|
+
flushQueue = new AsyncSerialQueue();
|
|
4373
|
+
/** Pending mutations not yet flushed to IPFS */
|
|
4374
|
+
pendingBuffer = new WriteBuffer();
|
|
4375
|
+
/** Debounce timer for background flush */
|
|
4376
|
+
flushTimer = null;
|
|
4377
|
+
/** Debounce interval in ms */
|
|
4378
|
+
flushDebounceMs;
|
|
4379
|
+
/** Set to true during shutdown to prevent new flushes */
|
|
4380
|
+
isShuttingDown = false;
|
|
4381
|
+
constructor(config, statePersistence) {
|
|
4382
|
+
const gateways = config?.gateways ?? getIpfsGatewayUrls();
|
|
4383
|
+
this.debug = config?.debug ?? false;
|
|
4384
|
+
this.ipnsLifetimeMs = config?.ipnsLifetimeMs ?? 99 * 365 * 24 * 60 * 60 * 1e3;
|
|
4385
|
+
this.flushDebounceMs = config?.flushDebounceMs ?? 2e3;
|
|
4386
|
+
this.cache = new IpfsCache({
|
|
4387
|
+
ipnsTtlMs: config?.ipnsCacheTtlMs,
|
|
4388
|
+
failureCooldownMs: config?.circuitBreakerCooldownMs,
|
|
4389
|
+
failureThreshold: config?.circuitBreakerThreshold,
|
|
4390
|
+
knownFreshWindowMs: config?.knownFreshWindowMs
|
|
4391
|
+
});
|
|
4392
|
+
this.httpClient = new IpfsHttpClient({
|
|
4393
|
+
gateways,
|
|
4394
|
+
fetchTimeoutMs: config?.fetchTimeoutMs,
|
|
4395
|
+
resolveTimeoutMs: config?.resolveTimeoutMs,
|
|
4396
|
+
publishTimeoutMs: config?.publishTimeoutMs,
|
|
4397
|
+
connectivityTimeoutMs: config?.connectivityTimeoutMs,
|
|
4398
|
+
debug: this.debug
|
|
4399
|
+
}, this.cache);
|
|
4400
|
+
this.statePersistence = statePersistence ?? new InMemoryIpfsStatePersistence();
|
|
4401
|
+
this.createWebSocket = config?.createWebSocket;
|
|
4402
|
+
this.wsUrl = config?.wsUrl;
|
|
4403
|
+
this.fallbackPollIntervalMs = config?.fallbackPollIntervalMs ?? 9e4;
|
|
4404
|
+
}
|
|
4405
|
+
// ---------------------------------------------------------------------------
|
|
4406
|
+
// BaseProvider interface
|
|
4407
|
+
// ---------------------------------------------------------------------------
|
|
4408
|
+
async connect() {
|
|
4409
|
+
await this.initialize();
|
|
4410
|
+
}
|
|
4411
|
+
async disconnect() {
|
|
4412
|
+
await this.shutdown();
|
|
4413
|
+
}
|
|
4414
|
+
isConnected() {
|
|
4415
|
+
return this.status === "connected";
|
|
4416
|
+
}
|
|
4417
|
+
getStatus() {
|
|
4418
|
+
return this.status;
|
|
4419
|
+
}
|
|
4420
|
+
// ---------------------------------------------------------------------------
|
|
4421
|
+
// Identity & Initialization
|
|
4422
|
+
// ---------------------------------------------------------------------------
|
|
4423
|
+
setIdentity(identity) {
|
|
4424
|
+
this.identity = identity;
|
|
4425
|
+
}
|
|
4426
|
+
async initialize() {
|
|
4427
|
+
if (!this.identity) {
|
|
4428
|
+
this.log("Cannot initialize: no identity set");
|
|
4429
|
+
return false;
|
|
4430
|
+
}
|
|
4431
|
+
this.status = "connecting";
|
|
4432
|
+
this.emitEvent({ type: "storage:loading", timestamp: Date.now() });
|
|
4433
|
+
try {
|
|
4434
|
+
const { keyPair, ipnsName } = await deriveIpnsIdentity(this.identity.privateKey);
|
|
4435
|
+
this.ipnsKeyPair = keyPair;
|
|
4436
|
+
this.ipnsName = ipnsName;
|
|
4437
|
+
this.log(`IPNS name derived: ${ipnsName}`);
|
|
4438
|
+
const persisted = await this.statePersistence.load(ipnsName);
|
|
4439
|
+
if (persisted) {
|
|
4440
|
+
this.ipnsSequenceNumber = BigInt(persisted.sequenceNumber);
|
|
4441
|
+
this.lastCid = persisted.lastCid;
|
|
4442
|
+
this.remoteCid = persisted.lastCid;
|
|
4443
|
+
this.dataVersion = persisted.version;
|
|
4444
|
+
this.log(`Loaded persisted state: seq=${this.ipnsSequenceNumber}, cid=${this.lastCid}`);
|
|
4445
|
+
}
|
|
4446
|
+
if (this.createWebSocket) {
|
|
4447
|
+
try {
|
|
4448
|
+
const wsUrlFinal = this.wsUrl ?? this.deriveWsUrl();
|
|
4449
|
+
if (wsUrlFinal) {
|
|
4450
|
+
this.subscriptionClient = new IpnsSubscriptionClient({
|
|
4451
|
+
wsUrl: wsUrlFinal,
|
|
4452
|
+
createWebSocket: this.createWebSocket,
|
|
4453
|
+
debug: this.debug
|
|
4454
|
+
});
|
|
4455
|
+
this.subscriptionUnsubscribe = this.subscriptionClient.subscribe(
|
|
4456
|
+
ipnsName,
|
|
4457
|
+
(update) => {
|
|
4458
|
+
this.log(`Push update: seq=${update.sequence}, cid=${update.cid}`);
|
|
4459
|
+
this.emitEvent({
|
|
4460
|
+
type: "storage:remote-updated",
|
|
4461
|
+
timestamp: Date.now(),
|
|
4462
|
+
data: { name: update.name, sequence: update.sequence, cid: update.cid }
|
|
4463
|
+
});
|
|
4464
|
+
}
|
|
4465
|
+
);
|
|
4466
|
+
this.subscriptionClient.setFallbackPoll(
|
|
4467
|
+
() => this.pollForRemoteChanges(),
|
|
4468
|
+
this.fallbackPollIntervalMs
|
|
4469
|
+
);
|
|
4470
|
+
this.subscriptionClient.connect();
|
|
4471
|
+
}
|
|
4472
|
+
} catch (wsError) {
|
|
4473
|
+
this.log(`Failed to set up IPNS subscription: ${wsError}`);
|
|
4474
|
+
}
|
|
4475
|
+
}
|
|
4476
|
+
this.httpClient.findHealthyGateways().then((healthy) => {
|
|
4477
|
+
if (healthy.length > 0) {
|
|
4478
|
+
this.log(`${healthy.length} healthy gateway(s) found`);
|
|
4479
|
+
} else {
|
|
4480
|
+
this.log("Warning: no healthy gateways found");
|
|
4481
|
+
}
|
|
4482
|
+
}).catch(() => {
|
|
4483
|
+
});
|
|
4484
|
+
this.isShuttingDown = false;
|
|
4485
|
+
this.status = "connected";
|
|
4486
|
+
this.emitEvent({ type: "storage:loaded", timestamp: Date.now() });
|
|
4487
|
+
return true;
|
|
4488
|
+
} catch (error) {
|
|
4489
|
+
this.status = "error";
|
|
4490
|
+
this.emitEvent({
|
|
4491
|
+
type: "storage:error",
|
|
4492
|
+
timestamp: Date.now(),
|
|
4493
|
+
error: error instanceof Error ? error.message : String(error)
|
|
4494
|
+
});
|
|
4495
|
+
return false;
|
|
4496
|
+
}
|
|
4497
|
+
}
|
|
4498
|
+
async shutdown() {
|
|
4499
|
+
this.isShuttingDown = true;
|
|
4500
|
+
if (this.flushTimer) {
|
|
4501
|
+
clearTimeout(this.flushTimer);
|
|
4502
|
+
this.flushTimer = null;
|
|
4503
|
+
}
|
|
4504
|
+
await this.flushQueue.enqueue(async () => {
|
|
4505
|
+
if (!this.pendingBuffer.isEmpty) {
|
|
4506
|
+
try {
|
|
4507
|
+
await this.executeFlush();
|
|
4508
|
+
} catch {
|
|
4509
|
+
this.log("Final flush on shutdown failed (data may be lost)");
|
|
4510
|
+
}
|
|
4511
|
+
}
|
|
4512
|
+
});
|
|
4513
|
+
if (this.subscriptionUnsubscribe) {
|
|
4514
|
+
this.subscriptionUnsubscribe();
|
|
4515
|
+
this.subscriptionUnsubscribe = null;
|
|
4516
|
+
}
|
|
4517
|
+
if (this.subscriptionClient) {
|
|
4518
|
+
this.subscriptionClient.disconnect();
|
|
4519
|
+
this.subscriptionClient = null;
|
|
4520
|
+
}
|
|
4521
|
+
this.cache.clear();
|
|
4522
|
+
this.status = "disconnected";
|
|
4523
|
+
}
|
|
4524
|
+
// ---------------------------------------------------------------------------
|
|
4525
|
+
// Save (non-blocking — buffers data for async flush)
|
|
4526
|
+
// ---------------------------------------------------------------------------
|
|
4527
|
+
async save(data) {
|
|
4528
|
+
if (!this.ipnsKeyPair || !this.ipnsName) {
|
|
4529
|
+
return { success: false, error: "Not initialized", timestamp: Date.now() };
|
|
4530
|
+
}
|
|
4531
|
+
this.pendingBuffer.txfData = data;
|
|
4532
|
+
this.scheduleFlush();
|
|
4533
|
+
return { success: true, timestamp: Date.now() };
|
|
4534
|
+
}
|
|
4535
|
+
// ---------------------------------------------------------------------------
|
|
4536
|
+
// Internal: Blocking save (used by sync and executeFlush)
|
|
4537
|
+
// ---------------------------------------------------------------------------
|
|
4538
|
+
/**
|
|
4539
|
+
* Perform the actual upload + IPNS publish synchronously.
|
|
4540
|
+
* Called by executeFlush() and sync() — never by public save().
|
|
4541
|
+
*/
|
|
4542
|
+
async _doSave(data) {
|
|
4543
|
+
if (!this.ipnsKeyPair || !this.ipnsName) {
|
|
4544
|
+
return { success: false, error: "Not initialized", timestamp: Date.now() };
|
|
4545
|
+
}
|
|
4546
|
+
this.emitEvent({ type: "storage:saving", timestamp: Date.now() });
|
|
4547
|
+
try {
|
|
4548
|
+
this.dataVersion++;
|
|
4549
|
+
const metaUpdate = {
|
|
4550
|
+
...data._meta,
|
|
4551
|
+
version: this.dataVersion,
|
|
4552
|
+
ipnsName: this.ipnsName,
|
|
4553
|
+
updatedAt: Date.now()
|
|
4554
|
+
};
|
|
4555
|
+
if (this.remoteCid) {
|
|
4556
|
+
metaUpdate.lastCid = this.remoteCid;
|
|
4557
|
+
}
|
|
4558
|
+
const updatedData = { ...data, _meta: metaUpdate };
|
|
4559
|
+
const { cid } = await this.httpClient.upload(updatedData);
|
|
4560
|
+
this.log(`Content uploaded: CID=${cid}`);
|
|
4561
|
+
const baseSeq = this.ipnsSequenceNumber > this.lastKnownRemoteSequence ? this.ipnsSequenceNumber : this.lastKnownRemoteSequence;
|
|
4562
|
+
const newSeq = baseSeq + 1n;
|
|
4563
|
+
const marshalledRecord = await createSignedRecord(
|
|
4564
|
+
this.ipnsKeyPair,
|
|
4565
|
+
cid,
|
|
4566
|
+
newSeq,
|
|
4567
|
+
this.ipnsLifetimeMs
|
|
4568
|
+
);
|
|
4569
|
+
const publishResult = await this.httpClient.publishIpns(
|
|
4570
|
+
this.ipnsName,
|
|
4571
|
+
marshalledRecord
|
|
4572
|
+
);
|
|
4573
|
+
if (!publishResult.success) {
|
|
4574
|
+
this.dataVersion--;
|
|
4575
|
+
this.log(`IPNS publish failed: ${publishResult.error}`);
|
|
4576
|
+
return {
|
|
4577
|
+
success: false,
|
|
4578
|
+
error: publishResult.error ?? "IPNS publish failed",
|
|
4579
|
+
timestamp: Date.now()
|
|
4580
|
+
};
|
|
4581
|
+
}
|
|
4582
|
+
this.ipnsSequenceNumber = newSeq;
|
|
4583
|
+
this.lastCid = cid;
|
|
4584
|
+
this.remoteCid = cid;
|
|
4585
|
+
this.cache.setIpnsRecord(this.ipnsName, {
|
|
4586
|
+
cid,
|
|
4587
|
+
sequence: newSeq,
|
|
4588
|
+
gateway: "local"
|
|
4589
|
+
});
|
|
4590
|
+
this.cache.setContent(cid, updatedData);
|
|
4591
|
+
this.cache.markIpnsFresh(this.ipnsName);
|
|
4592
|
+
await this.statePersistence.save(this.ipnsName, {
|
|
4593
|
+
sequenceNumber: newSeq.toString(),
|
|
4594
|
+
lastCid: cid,
|
|
4595
|
+
version: this.dataVersion
|
|
4596
|
+
});
|
|
4597
|
+
this.emitEvent({
|
|
4598
|
+
type: "storage:saved",
|
|
4599
|
+
timestamp: Date.now(),
|
|
4600
|
+
data: { cid, sequence: newSeq.toString() }
|
|
4601
|
+
});
|
|
4602
|
+
this.log(`Saved: CID=${cid}, seq=${newSeq}`);
|
|
4603
|
+
return { success: true, cid, timestamp: Date.now() };
|
|
4604
|
+
} catch (error) {
|
|
4605
|
+
this.dataVersion--;
|
|
4606
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
4607
|
+
this.emitEvent({
|
|
4608
|
+
type: "storage:error",
|
|
4609
|
+
timestamp: Date.now(),
|
|
4610
|
+
error: errorMessage
|
|
4611
|
+
});
|
|
4612
|
+
return { success: false, error: errorMessage, timestamp: Date.now() };
|
|
4613
|
+
}
|
|
4614
|
+
}
|
|
4615
|
+
// ---------------------------------------------------------------------------
|
|
4616
|
+
// Write-behind buffer: scheduling and flushing
|
|
4617
|
+
// ---------------------------------------------------------------------------
|
|
4618
|
+
/**
|
|
4619
|
+
* Schedule a debounced background flush.
|
|
4620
|
+
* Resets the timer on each call so rapid mutations coalesce.
|
|
4621
|
+
*/
|
|
4622
|
+
scheduleFlush() {
|
|
4623
|
+
if (this.isShuttingDown) return;
|
|
4624
|
+
if (this.flushTimer) clearTimeout(this.flushTimer);
|
|
4625
|
+
this.flushTimer = setTimeout(() => {
|
|
4626
|
+
this.flushTimer = null;
|
|
4627
|
+
this.flushQueue.enqueue(() => this.executeFlush()).catch((err) => {
|
|
4628
|
+
this.log(`Background flush failed: ${err}`);
|
|
4629
|
+
});
|
|
4630
|
+
}, this.flushDebounceMs);
|
|
4631
|
+
}
|
|
4632
|
+
/**
|
|
4633
|
+
* Execute a flush of the pending buffer to IPFS.
|
|
4634
|
+
* Runs inside AsyncSerialQueue for concurrency safety.
|
|
4635
|
+
*/
|
|
4636
|
+
async executeFlush() {
|
|
4637
|
+
if (this.pendingBuffer.isEmpty) return;
|
|
4638
|
+
const active = this.pendingBuffer;
|
|
4639
|
+
this.pendingBuffer = new WriteBuffer();
|
|
4640
|
+
try {
|
|
4641
|
+
const baseData = active.txfData ?? {
|
|
4642
|
+
_meta: { version: 0, address: this.identity?.directAddress ?? "", formatVersion: "2.0", updatedAt: 0 }
|
|
4643
|
+
};
|
|
4644
|
+
const result = await this._doSave(baseData);
|
|
4645
|
+
if (!result.success) {
|
|
4646
|
+
throw new Error(result.error ?? "Save failed");
|
|
4647
|
+
}
|
|
4648
|
+
this.log(`Flushed successfully: CID=${result.cid}`);
|
|
4649
|
+
} catch (error) {
|
|
4650
|
+
this.pendingBuffer.mergeFrom(active);
|
|
4651
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
4652
|
+
this.log(`Flush failed (will retry): ${msg}`);
|
|
4653
|
+
this.scheduleFlush();
|
|
4654
|
+
throw error;
|
|
4655
|
+
}
|
|
4656
|
+
}
|
|
4657
|
+
// ---------------------------------------------------------------------------
|
|
4658
|
+
// Load
|
|
4659
|
+
// ---------------------------------------------------------------------------
|
|
4660
|
+
async load(identifier) {
|
|
4661
|
+
if (!this.ipnsName && !identifier) {
|
|
4662
|
+
return { success: false, error: "Not initialized", source: "local", timestamp: Date.now() };
|
|
4663
|
+
}
|
|
4664
|
+
this.emitEvent({ type: "storage:loading", timestamp: Date.now() });
|
|
4665
|
+
try {
|
|
4666
|
+
if (identifier) {
|
|
4667
|
+
const data2 = await this.httpClient.fetchContent(identifier);
|
|
4668
|
+
return { success: true, data: data2, source: "remote", timestamp: Date.now() };
|
|
4669
|
+
}
|
|
4670
|
+
const ipnsName = this.ipnsName;
|
|
4671
|
+
if (this.cache.isIpnsKnownFresh(ipnsName)) {
|
|
4672
|
+
const cached = this.cache.getIpnsRecordIgnoreTtl(ipnsName);
|
|
4673
|
+
if (cached) {
|
|
4674
|
+
const content = this.cache.getContent(cached.cid);
|
|
4675
|
+
if (content) {
|
|
4676
|
+
this.log("Using known-fresh cached data");
|
|
4677
|
+
return { success: true, data: content, source: "cache", timestamp: Date.now() };
|
|
4678
|
+
}
|
|
4679
|
+
}
|
|
4680
|
+
}
|
|
4681
|
+
const cachedRecord = this.cache.getIpnsRecord(ipnsName);
|
|
4682
|
+
if (cachedRecord) {
|
|
4683
|
+
const content = this.cache.getContent(cachedRecord.cid);
|
|
4684
|
+
if (content) {
|
|
4685
|
+
this.log("IPNS cache hit");
|
|
4686
|
+
return { success: true, data: content, source: "cache", timestamp: Date.now() };
|
|
4687
|
+
}
|
|
4688
|
+
try {
|
|
4689
|
+
const data2 = await this.httpClient.fetchContent(cachedRecord.cid);
|
|
4690
|
+
return { success: true, data: data2, source: "remote", timestamp: Date.now() };
|
|
4691
|
+
} catch {
|
|
4692
|
+
}
|
|
4693
|
+
}
|
|
4694
|
+
const { best } = await this.httpClient.resolveIpns(ipnsName);
|
|
4695
|
+
if (!best) {
|
|
4696
|
+
this.log("IPNS record not found (new wallet?)");
|
|
4697
|
+
return { success: false, error: "IPNS record not found", source: "remote", timestamp: Date.now() };
|
|
4698
|
+
}
|
|
4699
|
+
if (best.sequence > this.lastKnownRemoteSequence) {
|
|
4700
|
+
this.lastKnownRemoteSequence = best.sequence;
|
|
4701
|
+
}
|
|
4702
|
+
this.remoteCid = best.cid;
|
|
4703
|
+
const data = await this.httpClient.fetchContent(best.cid);
|
|
4704
|
+
const remoteVersion = data?._meta?.version;
|
|
4705
|
+
if (typeof remoteVersion === "number" && remoteVersion > this.dataVersion) {
|
|
4706
|
+
this.dataVersion = remoteVersion;
|
|
4707
|
+
}
|
|
4708
|
+
this.emitEvent({
|
|
4709
|
+
type: "storage:loaded",
|
|
4710
|
+
timestamp: Date.now(),
|
|
4711
|
+
data: { cid: best.cid, sequence: best.sequence.toString() }
|
|
4712
|
+
});
|
|
4713
|
+
return { success: true, data, source: "remote", timestamp: Date.now() };
|
|
4714
|
+
} catch (error) {
|
|
4715
|
+
if (this.ipnsName) {
|
|
4716
|
+
const cached = this.cache.getIpnsRecordIgnoreTtl(this.ipnsName);
|
|
4717
|
+
if (cached) {
|
|
4718
|
+
const content = this.cache.getContent(cached.cid);
|
|
4719
|
+
if (content) {
|
|
4720
|
+
this.log("Network error, returning stale cache");
|
|
4721
|
+
return { success: true, data: content, source: "cache", timestamp: Date.now() };
|
|
4722
|
+
}
|
|
4723
|
+
}
|
|
4724
|
+
}
|
|
4725
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
4726
|
+
this.emitEvent({
|
|
4727
|
+
type: "storage:error",
|
|
4728
|
+
timestamp: Date.now(),
|
|
4729
|
+
error: errorMessage
|
|
4730
|
+
});
|
|
4731
|
+
return { success: false, error: errorMessage, source: "remote", timestamp: Date.now() };
|
|
4732
|
+
}
|
|
4733
|
+
}
|
|
4734
|
+
// ---------------------------------------------------------------------------
|
|
4735
|
+
// Sync (enters serial queue to avoid concurrent IPNS conflicts)
|
|
4736
|
+
// ---------------------------------------------------------------------------
|
|
4737
|
+
async sync(localData) {
|
|
4738
|
+
return this.flushQueue.enqueue(async () => {
|
|
4739
|
+
if (this.flushTimer) {
|
|
4740
|
+
clearTimeout(this.flushTimer);
|
|
4741
|
+
this.flushTimer = null;
|
|
4742
|
+
}
|
|
4743
|
+
this.emitEvent({ type: "sync:started", timestamp: Date.now() });
|
|
4744
|
+
try {
|
|
4745
|
+
this.pendingBuffer.clear();
|
|
4746
|
+
const remoteResult = await this.load();
|
|
4747
|
+
if (!remoteResult.success || !remoteResult.data) {
|
|
4748
|
+
this.log("No remote data found, uploading local data");
|
|
4749
|
+
const saveResult2 = await this._doSave(localData);
|
|
4750
|
+
this.emitEvent({ type: "sync:completed", timestamp: Date.now() });
|
|
4751
|
+
return {
|
|
4752
|
+
success: saveResult2.success,
|
|
4753
|
+
merged: localData,
|
|
4754
|
+
added: 0,
|
|
4755
|
+
removed: 0,
|
|
4756
|
+
conflicts: 0,
|
|
4757
|
+
error: saveResult2.error
|
|
4758
|
+
};
|
|
4759
|
+
}
|
|
4760
|
+
const remoteData = remoteResult.data;
|
|
4761
|
+
const localVersion = localData._meta?.version ?? 0;
|
|
4762
|
+
const remoteVersion = remoteData._meta?.version ?? 0;
|
|
4763
|
+
if (localVersion === remoteVersion && this.lastCid) {
|
|
4764
|
+
this.log("Data is in sync (same version)");
|
|
4765
|
+
this.emitEvent({ type: "sync:completed", timestamp: Date.now() });
|
|
4766
|
+
return {
|
|
4767
|
+
success: true,
|
|
4768
|
+
merged: localData,
|
|
4769
|
+
added: 0,
|
|
4770
|
+
removed: 0,
|
|
4771
|
+
conflicts: 0
|
|
4772
|
+
};
|
|
4773
|
+
}
|
|
4774
|
+
this.log(`Merging: local v${localVersion} <-> remote v${remoteVersion}`);
|
|
4775
|
+
const { merged, added, removed, conflicts } = mergeTxfData(localData, remoteData);
|
|
4776
|
+
if (conflicts > 0) {
|
|
4777
|
+
this.emitEvent({
|
|
4778
|
+
type: "sync:conflict",
|
|
4779
|
+
timestamp: Date.now(),
|
|
4780
|
+
data: { conflicts }
|
|
4781
|
+
});
|
|
4782
|
+
}
|
|
4783
|
+
const saveResult = await this._doSave(merged);
|
|
4784
|
+
this.emitEvent({
|
|
4785
|
+
type: "sync:completed",
|
|
4786
|
+
timestamp: Date.now(),
|
|
4787
|
+
data: { added, removed, conflicts }
|
|
4788
|
+
});
|
|
4789
|
+
return {
|
|
4790
|
+
success: saveResult.success,
|
|
4791
|
+
merged,
|
|
4792
|
+
added,
|
|
4793
|
+
removed,
|
|
4794
|
+
conflicts,
|
|
4795
|
+
error: saveResult.error
|
|
4796
|
+
};
|
|
4797
|
+
} catch (error) {
|
|
4798
|
+
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
4799
|
+
this.emitEvent({
|
|
4800
|
+
type: "sync:error",
|
|
4801
|
+
timestamp: Date.now(),
|
|
4802
|
+
error: errorMessage
|
|
4803
|
+
});
|
|
4804
|
+
return {
|
|
4805
|
+
success: false,
|
|
4806
|
+
added: 0,
|
|
4807
|
+
removed: 0,
|
|
4808
|
+
conflicts: 0,
|
|
4809
|
+
error: errorMessage
|
|
4810
|
+
};
|
|
4811
|
+
}
|
|
4812
|
+
});
|
|
4813
|
+
}
|
|
4814
|
+
// ---------------------------------------------------------------------------
|
|
4815
|
+
// Private Helpers
|
|
4816
|
+
// ---------------------------------------------------------------------------
|
|
4817
|
+
// ---------------------------------------------------------------------------
|
|
4818
|
+
// Optional Methods
|
|
4819
|
+
// ---------------------------------------------------------------------------
|
|
4820
|
+
async exists() {
|
|
4821
|
+
if (!this.ipnsName) return false;
|
|
4822
|
+
const cached = this.cache.getIpnsRecord(this.ipnsName);
|
|
4823
|
+
if (cached) return true;
|
|
4824
|
+
const { best } = await this.httpClient.resolveIpns(this.ipnsName);
|
|
4825
|
+
return best !== null;
|
|
4826
|
+
}
|
|
4827
|
+
async clear() {
|
|
4828
|
+
if (!this.ipnsKeyPair || !this.ipnsName) return false;
|
|
4829
|
+
this.pendingBuffer.clear();
|
|
4830
|
+
if (this.flushTimer) {
|
|
4831
|
+
clearTimeout(this.flushTimer);
|
|
4832
|
+
this.flushTimer = null;
|
|
4833
|
+
}
|
|
4834
|
+
const emptyData = {
|
|
4835
|
+
_meta: {
|
|
4836
|
+
version: 0,
|
|
4837
|
+
address: this.identity?.directAddress ?? "",
|
|
4838
|
+
ipnsName: this.ipnsName,
|
|
4839
|
+
formatVersion: "2.0",
|
|
4840
|
+
updatedAt: Date.now()
|
|
4841
|
+
}
|
|
4842
|
+
};
|
|
4843
|
+
const result = await this._doSave(emptyData);
|
|
4844
|
+
if (result.success) {
|
|
4845
|
+
this.cache.clear();
|
|
4846
|
+
await this.statePersistence.clear(this.ipnsName);
|
|
4847
|
+
}
|
|
4848
|
+
return result.success;
|
|
4849
|
+
}
|
|
4850
|
+
onEvent(callback) {
|
|
4851
|
+
this.eventCallbacks.add(callback);
|
|
4852
|
+
return () => {
|
|
4853
|
+
this.eventCallbacks.delete(callback);
|
|
4854
|
+
};
|
|
4855
|
+
}
|
|
4856
|
+
// ---------------------------------------------------------------------------
|
|
4857
|
+
// Public Accessors
|
|
4858
|
+
// ---------------------------------------------------------------------------
|
|
4859
|
+
getIpnsName() {
|
|
4860
|
+
return this.ipnsName;
|
|
4861
|
+
}
|
|
4862
|
+
getLastCid() {
|
|
4863
|
+
return this.lastCid;
|
|
4864
|
+
}
|
|
4865
|
+
getSequenceNumber() {
|
|
4866
|
+
return this.ipnsSequenceNumber;
|
|
4867
|
+
}
|
|
4868
|
+
getDataVersion() {
|
|
4869
|
+
return this.dataVersion;
|
|
4870
|
+
}
|
|
4871
|
+
getRemoteCid() {
|
|
4872
|
+
return this.remoteCid;
|
|
4873
|
+
}
|
|
4874
|
+
// ---------------------------------------------------------------------------
|
|
4875
|
+
// Testing helper: wait for pending flush to complete
|
|
4876
|
+
// ---------------------------------------------------------------------------
|
|
4877
|
+
/**
|
|
4878
|
+
* Wait for the pending flush timer to fire and the flush operation to
|
|
4879
|
+
* complete. Useful in tests to await background writes.
|
|
4880
|
+
* Returns immediately if no flush is pending.
|
|
4881
|
+
*/
|
|
4882
|
+
async waitForFlush() {
|
|
4883
|
+
if (this.flushTimer) {
|
|
4884
|
+
clearTimeout(this.flushTimer);
|
|
4885
|
+
this.flushTimer = null;
|
|
4886
|
+
await this.flushQueue.enqueue(() => this.executeFlush()).catch(() => {
|
|
4887
|
+
});
|
|
4888
|
+
} else if (!this.pendingBuffer.isEmpty) {
|
|
4889
|
+
await this.flushQueue.enqueue(() => this.executeFlush()).catch(() => {
|
|
4890
|
+
});
|
|
4891
|
+
} else {
|
|
4892
|
+
await this.flushQueue.enqueue(async () => {
|
|
4893
|
+
});
|
|
4894
|
+
}
|
|
4895
|
+
}
|
|
4896
|
+
// ---------------------------------------------------------------------------
|
|
4897
|
+
// Internal: Push Subscription Helpers
|
|
4898
|
+
// ---------------------------------------------------------------------------
|
|
4899
|
+
/**
|
|
4900
|
+
* Derive WebSocket URL from the first configured gateway.
|
|
4901
|
+
* Converts https://host → wss://host/ws/ipns
|
|
4902
|
+
*/
|
|
4903
|
+
deriveWsUrl() {
|
|
4904
|
+
const gateways = this.httpClient.getGateways();
|
|
4905
|
+
if (gateways.length === 0) return null;
|
|
4906
|
+
const gateway = gateways[0];
|
|
4907
|
+
const wsProtocol = gateway.startsWith("https://") ? "wss://" : "ws://";
|
|
4908
|
+
const host = gateway.replace(/^https?:\/\//, "");
|
|
4909
|
+
return `${wsProtocol}${host}/ws/ipns`;
|
|
4910
|
+
}
|
|
4911
|
+
/**
|
|
4912
|
+
* Poll for remote IPNS changes (fallback when WS is unavailable).
|
|
4913
|
+
* Compares remote sequence number with last known and emits event if changed.
|
|
4914
|
+
*/
|
|
4915
|
+
async pollForRemoteChanges() {
|
|
4916
|
+
if (!this.ipnsName) return;
|
|
4917
|
+
try {
|
|
4918
|
+
const { best } = await this.httpClient.resolveIpns(this.ipnsName);
|
|
4919
|
+
if (best && best.sequence > this.lastKnownRemoteSequence) {
|
|
4920
|
+
this.log(`Poll detected remote change: seq=${best.sequence} (was ${this.lastKnownRemoteSequence})`);
|
|
4921
|
+
this.lastKnownRemoteSequence = best.sequence;
|
|
4922
|
+
this.emitEvent({
|
|
4923
|
+
type: "storage:remote-updated",
|
|
4924
|
+
timestamp: Date.now(),
|
|
4925
|
+
data: { name: this.ipnsName, sequence: Number(best.sequence), cid: best.cid }
|
|
4926
|
+
});
|
|
4927
|
+
}
|
|
4928
|
+
} catch {
|
|
4929
|
+
}
|
|
4930
|
+
}
|
|
4931
|
+
// ---------------------------------------------------------------------------
|
|
4932
|
+
// Internal
|
|
4933
|
+
// ---------------------------------------------------------------------------
|
|
4934
|
+
emitEvent(event) {
|
|
4935
|
+
for (const callback of this.eventCallbacks) {
|
|
4936
|
+
try {
|
|
4937
|
+
callback(event);
|
|
4938
|
+
} catch {
|
|
4939
|
+
}
|
|
4940
|
+
}
|
|
4941
|
+
}
|
|
4942
|
+
log(message) {
|
|
4943
|
+
if (this.debug) {
|
|
4944
|
+
console.log(`[IPFS-Storage] ${message}`);
|
|
4945
|
+
}
|
|
4946
|
+
}
|
|
4947
|
+
};
|
|
4948
|
+
|
|
4949
|
+
// impl/browser/ipfs/browser-ipfs-state-persistence.ts
|
|
4950
|
+
var KEY_PREFIX = "sphere_ipfs_";
|
|
4951
|
+
function seqKey(ipnsName) {
|
|
4952
|
+
return `${KEY_PREFIX}seq_${ipnsName}`;
|
|
4953
|
+
}
|
|
4954
|
+
function cidKey(ipnsName) {
|
|
4955
|
+
return `${KEY_PREFIX}cid_${ipnsName}`;
|
|
4956
|
+
}
|
|
4957
|
+
function verKey(ipnsName) {
|
|
4958
|
+
return `${KEY_PREFIX}ver_${ipnsName}`;
|
|
4959
|
+
}
|
|
4960
|
+
var BrowserIpfsStatePersistence = class {
|
|
4961
|
+
async load(ipnsName) {
|
|
4962
|
+
try {
|
|
4963
|
+
const seq = localStorage.getItem(seqKey(ipnsName));
|
|
4964
|
+
if (!seq) return null;
|
|
4965
|
+
return {
|
|
4966
|
+
sequenceNumber: seq,
|
|
4967
|
+
lastCid: localStorage.getItem(cidKey(ipnsName)),
|
|
4968
|
+
version: parseInt(localStorage.getItem(verKey(ipnsName)) ?? "0", 10)
|
|
4969
|
+
};
|
|
4970
|
+
} catch {
|
|
4971
|
+
return null;
|
|
4972
|
+
}
|
|
4973
|
+
}
|
|
4974
|
+
async save(ipnsName, state) {
|
|
4975
|
+
try {
|
|
4976
|
+
localStorage.setItem(seqKey(ipnsName), state.sequenceNumber);
|
|
4977
|
+
if (state.lastCid) {
|
|
4978
|
+
localStorage.setItem(cidKey(ipnsName), state.lastCid);
|
|
4979
|
+
} else {
|
|
4980
|
+
localStorage.removeItem(cidKey(ipnsName));
|
|
4981
|
+
}
|
|
4982
|
+
localStorage.setItem(verKey(ipnsName), String(state.version));
|
|
4983
|
+
} catch {
|
|
4984
|
+
}
|
|
4985
|
+
}
|
|
4986
|
+
async clear(ipnsName) {
|
|
4987
|
+
try {
|
|
4988
|
+
localStorage.removeItem(seqKey(ipnsName));
|
|
4989
|
+
localStorage.removeItem(cidKey(ipnsName));
|
|
4990
|
+
localStorage.removeItem(verKey(ipnsName));
|
|
4991
|
+
} catch {
|
|
4992
|
+
}
|
|
4993
|
+
}
|
|
4994
|
+
};
|
|
4995
|
+
|
|
4996
|
+
// impl/browser/ipfs/index.ts
|
|
4997
|
+
function createBrowserWebSocket2(url) {
|
|
4998
|
+
return new WebSocket(url);
|
|
4999
|
+
}
|
|
5000
|
+
function createBrowserIpfsStorageProvider(config) {
|
|
5001
|
+
return new IpfsStorageProvider(
|
|
5002
|
+
{ ...config, createWebSocket: config?.createWebSocket ?? createBrowserWebSocket2 },
|
|
5003
|
+
new BrowserIpfsStatePersistence()
|
|
5004
|
+
);
|
|
5005
|
+
}
|
|
5006
|
+
|
|
5007
|
+
// price/CoinGeckoPriceProvider.ts
|
|
5008
|
+
var CoinGeckoPriceProvider = class {
|
|
5009
|
+
platform = "coingecko";
|
|
5010
|
+
cache = /* @__PURE__ */ new Map();
|
|
5011
|
+
apiKey;
|
|
5012
|
+
cacheTtlMs;
|
|
5013
|
+
timeout;
|
|
5014
|
+
debug;
|
|
5015
|
+
baseUrl;
|
|
5016
|
+
constructor(config) {
|
|
5017
|
+
this.apiKey = config?.apiKey;
|
|
5018
|
+
this.cacheTtlMs = config?.cacheTtlMs ?? 6e4;
|
|
5019
|
+
this.timeout = config?.timeout ?? 1e4;
|
|
5020
|
+
this.debug = config?.debug ?? false;
|
|
5021
|
+
this.baseUrl = config?.baseUrl ?? (this.apiKey ? "https://pro-api.coingecko.com/api/v3" : "https://api.coingecko.com/api/v3");
|
|
5022
|
+
}
|
|
5023
|
+
async getPrices(tokenNames) {
|
|
5024
|
+
if (tokenNames.length === 0) {
|
|
5025
|
+
return /* @__PURE__ */ new Map();
|
|
5026
|
+
}
|
|
5027
|
+
const now = Date.now();
|
|
5028
|
+
const result = /* @__PURE__ */ new Map();
|
|
5029
|
+
const uncachedNames = [];
|
|
5030
|
+
for (const name of tokenNames) {
|
|
5031
|
+
const cached = this.cache.get(name);
|
|
5032
|
+
if (cached && cached.expiresAt > now) {
|
|
5033
|
+
if (cached.price !== null) {
|
|
5034
|
+
result.set(name, cached.price);
|
|
5035
|
+
}
|
|
5036
|
+
} else {
|
|
5037
|
+
uncachedNames.push(name);
|
|
5038
|
+
}
|
|
5039
|
+
}
|
|
5040
|
+
if (uncachedNames.length === 0) {
|
|
5041
|
+
return result;
|
|
5042
|
+
}
|
|
5043
|
+
try {
|
|
5044
|
+
const ids = uncachedNames.join(",");
|
|
5045
|
+
const url = `${this.baseUrl}/simple/price?ids=${encodeURIComponent(ids)}&vs_currencies=usd,eur&include_24hr_change=true`;
|
|
5046
|
+
const headers = { Accept: "application/json" };
|
|
5047
|
+
if (this.apiKey) {
|
|
5048
|
+
headers["x-cg-pro-api-key"] = this.apiKey;
|
|
5049
|
+
}
|
|
5050
|
+
if (this.debug) {
|
|
5051
|
+
console.log(`[CoinGecko] Fetching prices for: ${uncachedNames.join(", ")}`);
|
|
5052
|
+
}
|
|
5053
|
+
const response = await fetch(url, {
|
|
5054
|
+
headers,
|
|
5055
|
+
signal: AbortSignal.timeout(this.timeout)
|
|
5056
|
+
});
|
|
5057
|
+
if (!response.ok) {
|
|
5058
|
+
throw new Error(`CoinGecko API error: ${response.status} ${response.statusText}`);
|
|
5059
|
+
}
|
|
5060
|
+
const data = await response.json();
|
|
5061
|
+
for (const [name, values] of Object.entries(data)) {
|
|
5062
|
+
if (values && typeof values === "object") {
|
|
5063
|
+
const price = {
|
|
5064
|
+
tokenName: name,
|
|
5065
|
+
priceUsd: values.usd ?? 0,
|
|
5066
|
+
priceEur: values.eur,
|
|
5067
|
+
change24h: values.usd_24h_change,
|
|
5068
|
+
timestamp: now
|
|
5069
|
+
};
|
|
5070
|
+
this.cache.set(name, { price, expiresAt: now + this.cacheTtlMs });
|
|
5071
|
+
result.set(name, price);
|
|
5072
|
+
}
|
|
5073
|
+
}
|
|
5074
|
+
for (const name of uncachedNames) {
|
|
5075
|
+
if (!result.has(name)) {
|
|
5076
|
+
this.cache.set(name, { price: null, expiresAt: now + this.cacheTtlMs });
|
|
5077
|
+
}
|
|
5078
|
+
}
|
|
5079
|
+
if (this.debug) {
|
|
5080
|
+
console.log(`[CoinGecko] Fetched ${result.size} prices`);
|
|
5081
|
+
}
|
|
5082
|
+
} catch (error) {
|
|
5083
|
+
if (this.debug) {
|
|
5084
|
+
console.warn("[CoinGecko] Fetch failed, using stale cache:", error);
|
|
5085
|
+
}
|
|
5086
|
+
for (const name of uncachedNames) {
|
|
5087
|
+
const stale = this.cache.get(name);
|
|
5088
|
+
if (stale?.price) {
|
|
5089
|
+
result.set(name, stale.price);
|
|
5090
|
+
}
|
|
5091
|
+
}
|
|
5092
|
+
}
|
|
5093
|
+
return result;
|
|
5094
|
+
}
|
|
5095
|
+
async getPrice(tokenName) {
|
|
5096
|
+
const prices = await this.getPrices([tokenName]);
|
|
5097
|
+
return prices.get(tokenName) ?? null;
|
|
5098
|
+
}
|
|
5099
|
+
clearCache() {
|
|
5100
|
+
this.cache.clear();
|
|
5101
|
+
}
|
|
5102
|
+
};
|
|
5103
|
+
|
|
5104
|
+
// price/index.ts
|
|
5105
|
+
function createPriceProvider(config) {
|
|
5106
|
+
switch (config.platform) {
|
|
5107
|
+
case "coingecko":
|
|
5108
|
+
return new CoinGeckoPriceProvider(config);
|
|
5109
|
+
default:
|
|
5110
|
+
throw new Error(`Unsupported price platform: ${String(config.platform)}`);
|
|
5111
|
+
}
|
|
5112
|
+
}
|
|
5113
|
+
|
|
5114
|
+
// impl/shared/resolvers.ts
|
|
5115
|
+
function getNetworkConfig(network = "mainnet") {
|
|
5116
|
+
return NETWORKS[network];
|
|
5117
|
+
}
|
|
5118
|
+
function resolveTransportConfig(network, config) {
|
|
5119
|
+
const networkConfig = getNetworkConfig(network);
|
|
5120
|
+
let relays;
|
|
5121
|
+
if (config?.relays) {
|
|
5122
|
+
relays = config.relays;
|
|
5123
|
+
} else {
|
|
5124
|
+
relays = [...networkConfig.nostrRelays];
|
|
5125
|
+
if (config?.additionalRelays) {
|
|
5126
|
+
relays = [...relays, ...config.additionalRelays];
|
|
5127
|
+
}
|
|
5128
|
+
}
|
|
5129
|
+
return {
|
|
5130
|
+
relays,
|
|
5131
|
+
timeout: config?.timeout,
|
|
5132
|
+
autoReconnect: config?.autoReconnect,
|
|
5133
|
+
debug: config?.debug,
|
|
5134
|
+
// Browser-specific
|
|
5135
|
+
reconnectDelay: config?.reconnectDelay,
|
|
5136
|
+
maxReconnectAttempts: config?.maxReconnectAttempts
|
|
5137
|
+
};
|
|
5138
|
+
}
|
|
5139
|
+
function resolveOracleConfig(network, config) {
|
|
5140
|
+
const networkConfig = getNetworkConfig(network);
|
|
5141
|
+
return {
|
|
5142
|
+
url: config?.url ?? networkConfig.aggregatorUrl,
|
|
5143
|
+
apiKey: config?.apiKey ?? DEFAULT_AGGREGATOR_API_KEY,
|
|
5144
|
+
timeout: config?.timeout,
|
|
5145
|
+
skipVerification: config?.skipVerification,
|
|
5146
|
+
debug: config?.debug,
|
|
5147
|
+
// Node.js-specific
|
|
5148
|
+
trustBasePath: config?.trustBasePath
|
|
5149
|
+
};
|
|
5150
|
+
}
|
|
5151
|
+
function resolveL1Config(network, config) {
|
|
5152
|
+
if (config === void 0) {
|
|
5153
|
+
return void 0;
|
|
5154
|
+
}
|
|
5155
|
+
const networkConfig = getNetworkConfig(network);
|
|
5156
|
+
return {
|
|
5157
|
+
electrumUrl: config.electrumUrl ?? networkConfig.electrumUrl,
|
|
5158
|
+
defaultFeeRate: config.defaultFeeRate,
|
|
5159
|
+
enableVesting: config.enableVesting
|
|
5160
|
+
};
|
|
5161
|
+
}
|
|
5162
|
+
function resolvePriceConfig(config) {
|
|
5163
|
+
if (config === void 0) {
|
|
5164
|
+
return void 0;
|
|
5165
|
+
}
|
|
5166
|
+
return {
|
|
5167
|
+
platform: config.platform ?? "coingecko",
|
|
5168
|
+
apiKey: config.apiKey,
|
|
5169
|
+
baseUrl: config.baseUrl,
|
|
5170
|
+
cacheTtlMs: config.cacheTtlMs,
|
|
5171
|
+
timeout: config.timeout,
|
|
5172
|
+
debug: config.debug
|
|
5173
|
+
};
|
|
5174
|
+
}
|
|
5175
|
+
function resolveArrayConfig(defaults, replace, additional) {
|
|
5176
|
+
if (replace) {
|
|
5177
|
+
return replace;
|
|
5178
|
+
}
|
|
5179
|
+
const result = [...defaults];
|
|
5180
|
+
if (additional) {
|
|
5181
|
+
return [...result, ...additional];
|
|
5182
|
+
}
|
|
5183
|
+
return result;
|
|
5184
|
+
}
|
|
5185
|
+
function resolveGroupChatConfig(network, config) {
|
|
5186
|
+
if (!config) return void 0;
|
|
5187
|
+
if (config === true) {
|
|
5188
|
+
const netConfig2 = getNetworkConfig(network);
|
|
5189
|
+
return { relays: [...netConfig2.groupRelays] };
|
|
5190
|
+
}
|
|
5191
|
+
if (typeof config === "object" && config.enabled === false) {
|
|
5192
|
+
return void 0;
|
|
5193
|
+
}
|
|
5194
|
+
const netConfig = getNetworkConfig(network);
|
|
5195
|
+
return {
|
|
5196
|
+
relays: config.relays ?? [...netConfig.groupRelays]
|
|
5197
|
+
};
|
|
3274
5198
|
}
|
|
3275
5199
|
|
|
3276
5200
|
// impl/browser/index.ts
|
|
@@ -3331,8 +5255,16 @@ function createBrowserProviders(config) {
|
|
|
3331
5255
|
const tokenSyncConfig = resolveTokenSyncConfig(network, config?.tokenSync);
|
|
3332
5256
|
const priceConfig = resolvePriceConfig(config?.price);
|
|
3333
5257
|
const storage = createLocalStorageProvider(config?.storage);
|
|
5258
|
+
const ipfsConfig = tokenSyncConfig?.ipfs;
|
|
5259
|
+
const ipfsTokenStorage = ipfsConfig?.enabled ? createBrowserIpfsStorageProvider({
|
|
5260
|
+
gateways: ipfsConfig.gateways,
|
|
5261
|
+
debug: config?.tokenSync?.ipfs?.useDht
|
|
5262
|
+
// reuse debug-like flag
|
|
5263
|
+
}) : void 0;
|
|
5264
|
+
const groupChat = resolveGroupChatConfig(network, config?.groupChat);
|
|
3334
5265
|
return {
|
|
3335
5266
|
storage,
|
|
5267
|
+
groupChat,
|
|
3336
5268
|
transport: createNostrTransportProvider({
|
|
3337
5269
|
relays: transportConfig.relays,
|
|
3338
5270
|
timeout: transportConfig.timeout,
|
|
@@ -3353,6 +5285,7 @@ function createBrowserProviders(config) {
|
|
|
3353
5285
|
tokenStorage: createIndexedDBTokenStorageProvider(),
|
|
3354
5286
|
l1: l1Config,
|
|
3355
5287
|
price: priceConfig ? createPriceProvider(priceConfig) : void 0,
|
|
5288
|
+
ipfsTokenStorage,
|
|
3356
5289
|
tokenSyncConfig
|
|
3357
5290
|
};
|
|
3358
5291
|
}
|