@arkade-os/sdk 0.4.68 → 0.4.69

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.
Files changed (74) hide show
  1. package/README.md +33 -0
  2. package/dist/adapters/expo.cjs +5 -5
  3. package/dist/adapters/expo.d.cts +2 -2
  4. package/dist/adapters/expo.d.ts +2 -2
  5. package/dist/adapters/expo.js +3 -3
  6. package/dist/adapters/indexedDB.cjs +5 -5
  7. package/dist/adapters/indexedDB.js +4 -4
  8. package/dist/{asyncStorageTaskQueue-DaZlVTbM.d.ts → asyncStorageTaskQueue-BgUJN-3X.d.ts} +1 -1
  9. package/dist/{asyncStorageTaskQueue-B2CcXIHU.d.cts → asyncStorageTaskQueue-Cstx6hS7.d.cts} +1 -1
  10. package/dist/{chunk-45FKMOJH.js → chunk-2PPL3O7Z.js} +3 -3
  11. package/dist/{chunk-45FKMOJH.js.map → chunk-2PPL3O7Z.js.map} +1 -1
  12. package/dist/{chunk-EJOFL5WH.cjs → chunk-5MLC2HU3.cjs} +3 -3
  13. package/dist/{chunk-EJOFL5WH.cjs.map → chunk-5MLC2HU3.cjs.map} +1 -1
  14. package/dist/{chunk-WCJVKFAP.cjs → chunk-EBYCTLET.cjs} +787 -479
  15. package/dist/chunk-EBYCTLET.cjs.map +1 -0
  16. package/dist/{chunk-PJR63FTK.cjs → chunk-GVHUHTRH.cjs} +17 -17
  17. package/dist/{chunk-PJR63FTK.cjs.map → chunk-GVHUHTRH.cjs.map} +1 -1
  18. package/dist/{chunk-4KCVS4ZN.cjs → chunk-HQ4DMGA4.cjs} +10 -10
  19. package/dist/{chunk-4KCVS4ZN.cjs.map → chunk-HQ4DMGA4.cjs.map} +1 -1
  20. package/dist/{chunk-4CMXV5SF.js → chunk-L5SCQYHF.js} +3 -3
  21. package/dist/{chunk-4CMXV5SF.js.map → chunk-L5SCQYHF.js.map} +1 -1
  22. package/dist/{chunk-G4I6PU5H.js → chunk-MNMPGEK2.js} +4 -4
  23. package/dist/{chunk-G4I6PU5H.js.map → chunk-MNMPGEK2.js.map} +1 -1
  24. package/dist/{chunk-VBHXBI7F.js → chunk-TA7XLEP2.js} +357 -50
  25. package/dist/chunk-TA7XLEP2.js.map +1 -0
  26. package/dist/{chunk-6YUACVX4.cjs → chunk-WIFL5QYZ.cjs} +49 -49
  27. package/dist/{chunk-6YUACVX4.cjs.map → chunk-WIFL5QYZ.cjs.map} +1 -1
  28. package/dist/{chunk-GQ4NMQGR.js → chunk-XLWDX7QZ.js} +4 -4
  29. package/dist/{chunk-GQ4NMQGR.js.map → chunk-XLWDX7QZ.js.map} +1 -1
  30. package/dist/{chunk-JGMSZIE4.cjs → chunk-XQPN5YP2.cjs} +17 -17
  31. package/dist/{chunk-JGMSZIE4.cjs.map → chunk-XQPN5YP2.cjs.map} +1 -1
  32. package/dist/{chunk-33Q2RFET.js → chunk-YG7T6LI3.js} +3 -3
  33. package/dist/{chunk-33Q2RFET.js.map → chunk-YG7T6LI3.js.map} +1 -1
  34. package/dist/contracts/handlers/index.cjs +9 -9
  35. package/dist/contracts/handlers/index.d.cts +3 -3
  36. package/dist/contracts/handlers/index.d.ts +3 -3
  37. package/dist/contracts/handlers/index.js +2 -2
  38. package/dist/{delegate-AomVWxO_.d.ts → delegate-BPdzTbwN.d.ts} +1 -1
  39. package/dist/{delegate-Bffc5f54.d.cts → delegate-DrwIar11.d.cts} +1 -1
  40. package/dist/{hdWalletCapable-DZdIVa23.d.ts → hdWalletCapable-D4WH35z0.d.cts} +49 -5
  41. package/dist/{hdWalletCapable-B5nRs3RH.d.cts → hdWalletCapable-DyxCiNVE.d.ts} +49 -5
  42. package/dist/{index-nfyQM33h.d.cts → index-BqhpAqqj.d.cts} +2 -2
  43. package/dist/{index-jouvy8FD.d.ts → index-TZJvbIaA.d.ts} +2 -2
  44. package/dist/{index-C7RZCfoY.d.cts → index-dWRqYSdS.d.cts} +53 -1
  45. package/dist/{index-C7RZCfoY.d.ts → index-dWRqYSdS.d.ts} +53 -1
  46. package/dist/index.cjs +294 -290
  47. package/dist/index.d.cts +25 -8
  48. package/dist/index.d.ts +25 -8
  49. package/dist/index.js +4 -4
  50. package/dist/repositories/realm/index.cjs +19 -19
  51. package/dist/repositories/realm/index.d.cts +2 -2
  52. package/dist/repositories/realm/index.d.ts +2 -2
  53. package/dist/repositories/realm/index.js +5 -5
  54. package/dist/repositories/sqlite/index.cjs +18 -18
  55. package/dist/repositories/sqlite/index.d.cts +2 -2
  56. package/dist/repositories/sqlite/index.d.ts +2 -2
  57. package/dist/repositories/sqlite/index.js +5 -5
  58. package/dist/{taskRunner-D2vnpPBT.d.cts → taskRunner-CzYKyJ9c.d.cts} +1 -1
  59. package/dist/{taskRunner-DuwK9t8O.d.ts → taskRunner-D2fnbqYw.d.ts} +1 -1
  60. package/dist/wallet/expo/background.cjs +14 -14
  61. package/dist/wallet/expo/background.d.cts +3 -3
  62. package/dist/wallet/expo/background.d.ts +3 -3
  63. package/dist/wallet/expo/background.js +6 -6
  64. package/dist/wallet/expo/index.cjs +14 -14
  65. package/dist/wallet/expo/index.d.cts +4 -4
  66. package/dist/wallet/expo/index.d.ts +4 -4
  67. package/dist/wallet/expo/index.js +5 -5
  68. package/dist/worker/expo/index.cjs +9 -9
  69. package/dist/worker/expo/index.d.cts +4 -4
  70. package/dist/worker/expo/index.d.ts +4 -4
  71. package/dist/worker/expo/index.js +5 -5
  72. package/package.json +1 -1
  73. package/dist/chunk-VBHXBI7F.js.map +0 -1
  74. package/dist/chunk-WCJVKFAP.cjs.map +0 -1
@@ -1,5 +1,5 @@
1
- import { RestIndexerProvider } from './chunk-33Q2RFET.js';
2
- import { RestArkProvider, DEFAULT_ARKADE_SERVER_URL, isFetchTimeoutError, convertVtxo, buildVersion, sdkVersion, fetch } from './chunk-4CMXV5SF.js';
1
+ import { RestIndexerProvider } from './chunk-YG7T6LI3.js';
2
+ import { RestArkProvider, DEFAULT_ARKADE_SERVER_URL, isFetchTimeoutError, convertVtxo, buildVersion, sdkVersion, fetch } from './chunk-L5SCQYHF.js';
3
3
 
4
4
  // src/providers/expoUtils.ts
5
5
  async function getExpoFetch(options) {
@@ -185,5 +185,5 @@ var ExpoIndexerProvider = class extends RestIndexerProvider {
185
185
  };
186
186
 
187
187
  export { ExpoArkProvider, ExpoIndexerProvider };
188
- //# sourceMappingURL=chunk-G4I6PU5H.js.map
189
- //# sourceMappingURL=chunk-G4I6PU5H.js.map
188
+ //# sourceMappingURL=chunk-MNMPGEK2.js.map
189
+ //# sourceMappingURL=chunk-MNMPGEK2.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/providers/expoUtils.ts","../src/providers/expoArk.ts","../src/providers/expoIndexer.ts"],"names":[],"mappings":";;;;AAMA,eAAsB,aAAa,OAAA,EAA4D;AAG3F,EAAA,IAAI;AACA,IAAA,MAAM,eAAA,GAAkB,MAAM,OAAO,YAAY,CAAA;AACjD,IAAA,OAAA,CAAQ,MAAM,gCAAgC,CAAA;AAC9C,IAAA,MAAM,mBAAA,GAAsB,CAAC,KAAA,EAAoB,IAAA,KAAuB;AACpE,MAAA,MAAM,OAAA,GAAU,IAAI,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AACzC,MAAA,OAAA,CAAQ,GAAA,CAAI,mBAAmB,YAAY,CAAA;AAC3C,MAAA,OAAA,CAAQ,GAAA,CAAI,iBAAiB,UAAU,CAAA;AACvC,MAAA,OAAO,gBAAgB,KAAA,CAAM,KAAA,EAAO,EAAE,GAAG,IAAA,EAAM,SAAS,CAAA;AAAA,IAC5D,CAAA;AACA,IAAA,OAAO,mBAAA;AAAA,EACX,SAAS,KAAA,EAAO;AAQZ,IAAA,OAAA,CAAQ,IAAA;AAAA,MACJ,wGAAA;AAAA,MAEA;AAAA,KACJ;AACA,IAAA,OAAO,KAAA;AAAA,EACX;AACJ;AAYA,gBAAuB,iBAAA,CACnB,GAAA,EACA,WAAA,EACA,OAAA,EACA,SACA,SAAA,EACgC;AAChC,EAAA,MAAM,eAAA,GAA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AAA,IAAI,IAAA,CAAK,cAAc,KAAA,CAAA,EAAW;AAE9B,cAAA,OAAO,IAAA;AAAA,YACX;AAEA,YAAA,IAAI,KAAK,KAAA,EAAO;AACZ,cAAA,OAAO;AAAA,gBACH,IAAA,EAAM,KAAK,KAAA,CAAM,IAAA;AAAA,gBACjB,OAAA,EAAS,IAAA,CAAK,KAAA,CAAM,OAAA,IAAW,EAAC;AAAA,gBAChC,WAAW,IAAA,CAAK,KAAA,CAAM,YAAY,EAAC,EAAG,IAAI,WAAW,CAAA;AAAA,gBACrD,aAAa,IAAA,CAAK,KAAA,CAAM,cAAc,EAAC,EAAG,IAAI,WAAW,CAAA;AAAA,gBACzD,aAAa,IAAA,CAAK,KAAA,CAAM,cAAc,EAAC,EAAG,IAAI,WAAW,CAAA;AAAA,gBACzD,EAAA,EAAI,KAAK,KAAA,CAAM,EAAA;AAAA,gBACf,aAAA,EAAe,KAAK,KAAA,CAAM;AAAA,eAC9B;AAAA,YACJ;AACA,YAAA,OAAO,IAAA;AAAA,UACX;AAAA,SACJ;AAAA,MACJ,SAAS,KAAA,EAAO;AACZ,QAAA,IAAI,KAAA,YAAiB,KAAA,IAAS,KAAA,CAAM,IAAA,KAAS,YAAA,EAAc;AACvD,UAAA;AAAA,QACJ;AAIA,QAAA,IAAI,mBAAA,CAAoB,KAAK,CAAA,EAAG;AAC5B,UAAA,OAAA,CAAQ,MAAM,uBAAuB,CAAA;AACrC,UAAA;AAAA,QACJ;AAEA,QAAA,OAAA,CAAQ,KAAA,CAAM,uBAAuB,KAAK,CAAA;AAC1C,QAAA,MAAM,KAAA;AAAA,MACV;AAAA,IACJ;AAAA,EACJ;AACJ","file":"chunk-G4I6PU5H.js","sourcesContent":["import { fetch, buildVersion, sdkVersion } from \"../utils/fetch\";\n\n/**\n * Dynamically imports expo/fetch with fallback to standard fetch.\n * @returns A fetch function suitable for SSE streaming\n */\nexport async function getExpoFetch(options?: { requireExpo?: boolean }): Promise<typeof fetch> {\n const requireExpo = options?.requireExpo ?? false;\n\n try {\n const expoFetchModule = await import(\"expo/fetch\");\n console.debug(\"Using expo/fetch for streaming\");\n const expoFetchWithHeader = (input: RequestInfo, init?: RequestInit) => {\n const headers = new Headers(init?.headers);\n headers.set(\"X-Build-Version\", buildVersion);\n headers.set(\"X-SDK-VERSION\", sdkVersion);\n return expoFetchModule.fetch(input, { ...init, headers });\n };\n return expoFetchWithHeader as unknown as typeof fetch;\n } catch (error) {\n if (requireExpo) {\n throw new Error(\n \"expo/fetch is unavailable in this environment. \" +\n \"Please ensure expo/fetch is installed and properly configured.\",\n );\n }\n\n console.warn(\n \"Using standard fetch instead of expo/fetch. \" +\n \"Streaming may not be fully supported in some environments.\",\n error,\n );\n return fetch;\n }\n}\n\n/**\n * Generic SSE stream processor using fetch API with ReadableStream.\n * Handles SSE format parsing, buffer management, and abort signals.\n *\n * @param url - The SSE endpoint URL\n * @param abortSignal - Signal to abort the stream\n * @param fetchFn - Fetch function to use (defaults to standard fetch)\n * @param headers - Additional headers to send\n * @param parseData - Function to parse and yield data from SSE events\n */\nexport async function* sseStreamIterator<T>(\n url: string,\n abortSignal: AbortSignal,\n fetchFn: typeof fetch,\n headers: Record<string, string>,\n parseData: (data: any) => T | null,\n): AsyncGenerator<T, void, unknown> {\n const fetchController = new AbortController();\n const cleanup = () => fetchController.abort();\n abortSignal?.addEventListener(\"abort\", cleanup, { once: true });\n\n try {\n const response = await fetchFn(url, {\n headers: {\n Accept: \"text/event-stream\",\n ...headers,\n },\n signal: fetchController.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Unexpected status ${response.status} when fetching SSE stream`);\n }\n\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (!abortSignal?.aborted) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n for (let i = 0; i < lines.length - 1; i++) {\n const line = lines[i].trim();\n if (!line) continue;\n\n if (line.startsWith(\"data:\")) {\n const jsonStr = line.substring(5).trim();\n if (!jsonStr) continue;\n\n try {\n const data = JSON.parse(jsonStr);\n const parsed = parseData(data);\n if (parsed !== null) {\n yield parsed;\n }\n } catch (parseError) {\n console.error(\"Failed to parse SSE data:\", parseError);\n throw parseError;\n }\n }\n }\n\n buffer = lines[lines.length - 1];\n }\n } finally {\n abortSignal?.removeEventListener(\"abort\", cleanup);\n }\n}\n","import { DEFAULT_ARKADE_SERVER_URL } from \"../networks\";\nimport { RestArkProvider, SettlementEvent, TxNotificationEvent, isFetchTimeoutError } from \"./ark\";\nimport { getExpoFetch, sseStreamIterator } from \"./expoUtils\";\n\n/**\n * Expo-compatible Arkade provider implementation using expo/fetch for SSE support.\n * This provider works specifically in React Native/Expo environments where\n * standard EventSource is not available but expo/fetch provides SSE capabilities.\n *\n * @example\n * ```typescript\n * import { ExpoArkProvider } from '@arkade-os/sdk/providers/expo';\n *\n * const provider = new ExpoArkProvider('https://arkade.computer');\n * const info = await provider.getInfo();\n * ```\n */\nexport class ExpoArkProvider extends RestArkProvider {\n constructor(serverUrl: string = DEFAULT_ARKADE_SERVER_URL) {\n super(serverUrl);\n }\n\n override async *getEventStream(\n signal: AbortSignal,\n topics: string[],\n ): AsyncIterableIterator<SettlementEvent> {\n const expoFetch = await getExpoFetch();\n const url = `${this.serverUrl}/v1/batch/events`;\n const queryParams =\n topics.length > 0\n ? `?${topics.map((topic) => `topics=${encodeURIComponent(topic)}`).join(\"&\")}`\n : \"\";\n\n while (!signal?.aborted) {\n try {\n yield* sseStreamIterator(url + queryParams, signal, expoFetch, {}, (data) => {\n // Handle different response structures\n // v8 mesh API might wrap in {result: ...} or send directly\n const eventData = data.result || data;\n\n // Skip heartbeat messages\n if (eventData.heartbeat !== undefined) {\n return null;\n }\n\n return this.parseSettlementEvent(eventData);\n });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n break;\n }\n\n // ignore timeout errors, they're expected when the server is not sending anything for 5 min\n // these timeouts are set by expo/fetch function\n if (isFetchTimeoutError(error)) {\n console.debug(\"Timeout error ignored\");\n continue;\n }\n\n console.error(\"Event stream error:\", error);\n throw error;\n }\n }\n }\n\n override async *getTransactionsStream(\n signal: AbortSignal,\n ): AsyncIterableIterator<TxNotificationEvent> {\n const expoFetch = await getExpoFetch();\n const url = `${this.serverUrl}/v1/txs`;\n\n while (!signal?.aborted) {\n try {\n yield* sseStreamIterator(url, signal, expoFetch, {}, (data) => {\n return this.parseTransactionNotification(data.result);\n });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n break;\n }\n\n // ignore timeout errors, they're expected when the server is not sending anything for 5 min\n // these timeouts are set by expo/fetch function\n if (isFetchTimeoutError(error)) {\n console.debug(\"Timeout error ignored\");\n continue;\n }\n\n console.error(\"Transaction stream error:\", error);\n throw error;\n }\n }\n }\n}\n","import { RestIndexerProvider, SubscriptionResponse } from \"./indexer\";\nimport { isFetchTimeoutError } from \"./ark\";\nimport { convertVtxo } from \"../wallet/vtxo\";\nimport { getExpoFetch, sseStreamIterator } from \"./expoUtils\";\nimport { DEFAULT_ARKADE_SERVER_URL } from \"../networks\";\n\n/**\n * Expo-compatible Indexer provider implementation using expo/fetch for streaming support.\n * This provider works specifically in React Native/Expo environments where\n * standard fetch streaming may not work properly but expo/fetch provides streaming capabilities.\n *\n * @example\n * ```typescript\n * import { ExpoIndexerProvider } from '@arkade-os/sdk/adapters/expo';\n *\n * const provider = new ExpoIndexerProvider('https://indexer.example.com');\n * const vtxos = await provider.getVtxos({ scripts: ['script1'] });\n * ```\n */\nexport class ExpoIndexerProvider extends RestIndexerProvider {\n constructor(serverUrl: string = DEFAULT_ARKADE_SERVER_URL) {\n super(serverUrl);\n }\n\n override async *getSubscription(\n subscriptionId: string,\n abortSignal: AbortSignal,\n ): AsyncIterableIterator<SubscriptionResponse> {\n // Detect if we're running in React Native/Expo environment\n const isReactNative =\n typeof navigator !== \"undefined\" && navigator.product === \"ReactNative\";\n\n const expoFetch = await getExpoFetch().catch((error) => {\n // In React Native/Expo, expo/fetch is required for proper streaming support\n if (isReactNative) {\n throw new Error(\n \"expo/fetch is unavailable in React Native environment. \" +\n \"Please ensure expo/fetch is installed and properly configured. \" +\n \"Streaming support may not work with standard fetch in React Native.\",\n );\n }\n throw error;\n });\n\n const url = `${this.serverUrl}/v1/indexer/script/subscription/${subscriptionId}`;\n\n while (!abortSignal.aborted) {\n try {\n yield* sseStreamIterator(\n url,\n abortSignal,\n expoFetch,\n { \"Content-Type\": \"application/json\" },\n (data): SubscriptionResponse | null => {\n // Handle new v8 proto format with heartbeat or event\n if (data.heartbeat !== undefined) {\n // Skip heartbeat messages\n return null;\n }\n // Process event messages\n if (data.event) {\n return {\n txid: data.event.txid,\n scripts: data.event.scripts || [],\n newVtxos: (data.event.newVtxos || []).map(convertVtxo),\n spentVtxos: (data.event.spentVtxos || []).map(convertVtxo),\n sweptVtxos: (data.event.sweptVtxos || []).map(convertVtxo),\n tx: data.event.tx,\n checkpointTxs: data.event.checkpointTxs,\n };\n }\n return null;\n },\n );\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n break;\n }\n\n // ignore timeout errors, they're expected when the server is not sending anything for 5 min\n // these timeouts are set by expo/fetch function\n if (isFetchTimeoutError(error)) {\n console.debug(\"Timeout error ignored\");\n continue;\n }\n\n console.error(\"Subscription error:\", error);\n throw error;\n }\n }\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/providers/expoUtils.ts","../src/providers/expoArk.ts","../src/providers/expoIndexer.ts"],"names":[],"mappings":";;;;AAMA,eAAsB,aAAa,OAAA,EAA4D;AAG3F,EAAA,IAAI;AACA,IAAA,MAAM,eAAA,GAAkB,MAAM,OAAO,YAAY,CAAA;AACjD,IAAA,OAAA,CAAQ,MAAM,gCAAgC,CAAA;AAC9C,IAAA,MAAM,mBAAA,GAAsB,CAAC,KAAA,EAAoB,IAAA,KAAuB;AACpE,MAAA,MAAM,O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;AACZ,QAAA,IAAI,KAAA,YAAiB,KAAA,IAAS,KAAA,CAAM,IAAA,KAAS,YAAA,EAAc;AACvD,UAAA;AAAA,QACJ;AAIA,QAAA,IAAI,mBAAA,CAAoB,KAAK,CAAA,EAAG;AAC5B,UAAA,OAAA,CAAQ,MAAM,uBAAuB,CAAA;AACrC,UAAA;AAAA,QACJ;AAEA,QAAA,OAAA,CAAQ,KAAA,CAAM,uBAAuB,KAAK,CAAA;AAC1C,QAAA,MAAM,KAAA;AAAA,MACV;AAAA,IACJ;AAAA,EACJ;AACJ","file":"chunk-MNMPGEK2.js","sourcesContent":["import { fetch, buildVersion, sdkVersion } from \"../utils/fetch\";\n\n/**\n * Dynamically imports expo/fetch with fallback to standard fetch.\n * @returns A fetch function suitable for SSE streaming\n */\nexport async function getExpoFetch(options?: { requireExpo?: boolean }): Promise<typeof fetch> {\n const requireExpo = options?.requireExpo ?? false;\n\n try {\n const expoFetchModule = await import(\"expo/fetch\");\n console.debug(\"Using expo/fetch for streaming\");\n const expoFetchWithHeader = (input: RequestInfo, init?: RequestInit) => {\n const headers = new Headers(init?.headers);\n headers.set(\"X-Build-Version\", buildVersion);\n headers.set(\"X-SDK-VERSION\", sdkVersion);\n return expoFetchModule.fetch(input, { ...init, headers });\n };\n return expoFetchWithHeader as unknown as typeof fetch;\n } catch (error) {\n if (requireExpo) {\n throw new Error(\n \"expo/fetch is unavailable in this environment. \" +\n \"Please ensure expo/fetch is installed and properly configured.\",\n );\n }\n\n console.warn(\n \"Using standard fetch instead of expo/fetch. \" +\n \"Streaming may not be fully supported in some environments.\",\n error,\n );\n return fetch;\n }\n}\n\n/**\n * Generic SSE stream processor using fetch API with ReadableStream.\n * Handles SSE format parsing, buffer management, and abort signals.\n *\n * @param url - The SSE endpoint URL\n * @param abortSignal - Signal to abort the stream\n * @param fetchFn - Fetch function to use (defaults to standard fetch)\n * @param headers - Additional headers to send\n * @param parseData - Function to parse and yield data from SSE events\n */\nexport async function* sseStreamIterator<T>(\n url: string,\n abortSignal: AbortSignal,\n fetchFn: typeof fetch,\n headers: Record<string, string>,\n parseData: (data: any) => T | null,\n): AsyncGenerator<T, void, unknown> {\n const fetchController = new AbortController();\n const cleanup = () => fetchController.abort();\n abortSignal?.addEventListener(\"abort\", cleanup, { once: true });\n\n try {\n const response = await fetchFn(url, {\n headers: {\n Accept: \"text/event-stream\",\n ...headers,\n },\n signal: fetchController.signal,\n });\n\n if (!response.ok) {\n throw new Error(`Unexpected status ${response.status} when fetching SSE stream`);\n }\n\n if (!response.body) {\n throw new Error(\"Response body is null\");\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n while (!abortSignal?.aborted) {\n const { done, value } = await reader.read();\n if (done) {\n break;\n }\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n for (let i = 0; i < lines.length - 1; i++) {\n const line = lines[i].trim();\n if (!line) continue;\n\n if (line.startsWith(\"data:\")) {\n const jsonStr = line.substring(5).trim();\n if (!jsonStr) continue;\n\n try {\n const data = JSON.parse(jsonStr);\n const parsed = parseData(data);\n if (parsed !== null) {\n yield parsed;\n }\n } catch (parseError) {\n console.error(\"Failed to parse SSE data:\", parseError);\n throw parseError;\n }\n }\n }\n\n buffer = lines[lines.length - 1];\n }\n } finally {\n abortSignal?.removeEventListener(\"abort\", cleanup);\n }\n}\n","import { DEFAULT_ARKADE_SERVER_URL } from \"../networks\";\nimport { RestArkProvider, SettlementEvent, TxNotificationEvent, isFetchTimeoutError } from \"./ark\";\nimport { getExpoFetch, sseStreamIterator } from \"./expoUtils\";\n\n/**\n * Expo-compatible Arkade provider implementation using expo/fetch for SSE support.\n * This provider works specifically in React Native/Expo environments where\n * standard EventSource is not available but expo/fetch provides SSE capabilities.\n *\n * @example\n * ```typescript\n * import { ExpoArkProvider } from '@arkade-os/sdk/providers/expo';\n *\n * const provider = new ExpoArkProvider('https://arkade.computer');\n * const info = await provider.getInfo();\n * ```\n */\nexport class ExpoArkProvider extends RestArkProvider {\n constructor(serverUrl: string = DEFAULT_ARKADE_SERVER_URL) {\n super(serverUrl);\n }\n\n override async *getEventStream(\n signal: AbortSignal,\n topics: string[],\n ): AsyncIterableIterator<SettlementEvent> {\n const expoFetch = await getExpoFetch();\n const url = `${this.serverUrl}/v1/batch/events`;\n const queryParams =\n topics.length > 0\n ? `?${topics.map((topic) => `topics=${encodeURIComponent(topic)}`).join(\"&\")}`\n : \"\";\n\n while (!signal?.aborted) {\n try {\n yield* sseStreamIterator(url + queryParams, signal, expoFetch, {}, (data) => {\n // Handle different response structures\n // v8 mesh API might wrap in {result: ...} or send directly\n const eventData = data.result || data;\n\n // Skip heartbeat messages\n if (eventData.heartbeat !== undefined) {\n return null;\n }\n\n return this.parseSettlementEvent(eventData);\n });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n break;\n }\n\n // ignore timeout errors, they're expected when the server is not sending anything for 5 min\n // these timeouts are set by expo/fetch function\n if (isFetchTimeoutError(error)) {\n console.debug(\"Timeout error ignored\");\n continue;\n }\n\n console.error(\"Event stream error:\", error);\n throw error;\n }\n }\n }\n\n override async *getTransactionsStream(\n signal: AbortSignal,\n ): AsyncIterableIterator<TxNotificationEvent> {\n const expoFetch = await getExpoFetch();\n const url = `${this.serverUrl}/v1/txs`;\n\n while (!signal?.aborted) {\n try {\n yield* sseStreamIterator(url, signal, expoFetch, {}, (data) => {\n return this.parseTransactionNotification(data.result);\n });\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n break;\n }\n\n // ignore timeout errors, they're expected when the server is not sending anything for 5 min\n // these timeouts are set by expo/fetch function\n if (isFetchTimeoutError(error)) {\n console.debug(\"Timeout error ignored\");\n continue;\n }\n\n console.error(\"Transaction stream error:\", error);\n throw error;\n }\n }\n }\n}\n","import { RestIndexerProvider, SubscriptionResponse } from \"./indexer\";\nimport { isFetchTimeoutError } from \"./ark\";\nimport { convertVtxo } from \"../wallet/vtxo\";\nimport { getExpoFetch, sseStreamIterator } from \"./expoUtils\";\nimport { DEFAULT_ARKADE_SERVER_URL } from \"../networks\";\n\n/**\n * Expo-compatible Indexer provider implementation using expo/fetch for streaming support.\n * This provider works specifically in React Native/Expo environments where\n * standard fetch streaming may not work properly but expo/fetch provides streaming capabilities.\n *\n * @example\n * ```typescript\n * import { ExpoIndexerProvider } from '@arkade-os/sdk/adapters/expo';\n *\n * const provider = new ExpoIndexerProvider('https://indexer.example.com');\n * const vtxos = await provider.getVtxos({ scripts: ['script1'] });\n * ```\n */\nexport class ExpoIndexerProvider extends RestIndexerProvider {\n constructor(serverUrl: string = DEFAULT_ARKADE_SERVER_URL) {\n super(serverUrl);\n }\n\n override async *getSubscription(\n subscriptionId: string,\n abortSignal: AbortSignal,\n ): AsyncIterableIterator<SubscriptionResponse> {\n // Detect if we're running in React Native/Expo environment\n const isReactNative =\n typeof navigator !== \"undefined\" && navigator.product === \"ReactNative\";\n\n const expoFetch = await getExpoFetch().catch((error) => {\n // In React Native/Expo, expo/fetch is required for proper streaming support\n if (isReactNative) {\n throw new Error(\n \"expo/fetch is unavailable in React Native environment. \" +\n \"Please ensure expo/fetch is installed and properly configured. \" +\n \"Streaming support may not work with standard fetch in React Native.\",\n );\n }\n throw error;\n });\n\n const url = `${this.serverUrl}/v1/indexer/script/subscription/${subscriptionId}`;\n\n while (!abortSignal.aborted) {\n try {\n yield* sseStreamIterator(\n url,\n abortSignal,\n expoFetch,\n { \"Content-Type\": \"application/json\" },\n (data): SubscriptionResponse | null => {\n // Handle new v8 proto format with heartbeat or event\n if (data.heartbeat !== undefined) {\n // Skip heartbeat messages\n return null;\n }\n // Process event messages\n if (data.event) {\n return {\n txid: data.event.txid,\n scripts: data.event.scripts || [],\n newVtxos: (data.event.newVtxos || []).map(convertVtxo),\n spentVtxos: (data.event.spentVtxos || []).map(convertVtxo),\n sweptVtxos: (data.event.sweptVtxos || []).map(convertVtxo),\n tx: data.event.tx,\n checkpointTxs: data.event.checkpointTxs,\n };\n }\n return null;\n },\n );\n } catch (error) {\n if (error instanceof Error && error.name === \"AbortError\") {\n break;\n }\n\n // ignore timeout errors, they're expected when the server is not sending anything for 5 min\n // these timeouts are set by expo/fetch function\n if (isFetchTimeoutError(error)) {\n console.debug(\"Timeout error ignored\");\n continue;\n }\n\n console.error(\"Subscription error:\", error);\n throw error;\n }\n }\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { AssetId, AssetGroup, AssetInput, AssetOutput, Metadata, Packet, BufferReader, BufferWriter, AssetRef, RestIndexerProvider } from './chunk-33Q2RFET.js';
2
- import { witnessRefToBytes, validateProgram, toASM, stringifyArtifact, serializeArkadeContractParams, resolveAsm, parseArtifact, getOpcodeValue, getOpcodeName, fromASM, deserializeArkadeContractParams, computeArkadeScriptPublicKey, bytesToASM, asmToBytes, arkadeWitnessHash, arkadeScriptHash, SUPPORTED_PROGRAM_VERSION, OPCODE_VALUES, OPCODE_NAMES, bignum_exports, ArkadeScript, ArkadeProgramScript, ARKADE_OPS, ARKADE_OPCODE_VALUES, ARKADE_OPCODE_NAMES, ARKADE_OPCODES, ARKADE_OP, toXOnly, inputName, contractHandlers, isMainnetDescriptor, descriptorIsOurs, deriveDescriptorLeafPubKey, deriveDescriptorLeafCompressedPubKey, parseHDDescriptor, identityDescriptor, DefaultVtxo, speculativeReceiveMetadata, DelegateVtxo, WALLET_RECEIVE_SOURCE, BoardingContractHandler } from './chunk-45FKMOJH.js';
3
- import { VtxoScript, Transaction, isRecoverable, CSVMultisigTapscript, DEFAULT_NETWORK, resolveEmulatorPubkey, hasTerminalSpend, getNormalizedVtxos, setArkPsbtField, PrevArkTxField, ConditionWitness, craftToSpendTx, ArkAddress, isVirtualCoin, getArkPsbtFields, CosignerPublicKey, ServerResponseMismatchError, OP_RETURN_EMPTY_PKSCRIPT, canSweepOnchain, sequenceToTimelock, decodeTapscript, scriptFromTapLeafScript, CLTVMultisigTapscript, VtxoTaprootTree, timelockToSequence, assertAllowedSighashTypes, baseFetch, Intent, rateGate, DEFAULT_NETWORK_NAME, formatSighash, normalizeVtxo, getSequence, toBatchExpiry, maybeArkError, isArkError, ArkErrorName, toOffchainInputFeeParams, canRecoverOnchain, getNetwork, MultisigTapscript, isEventSourceError, isEventSourceUnavailableError, isRetryableProviderError, getAllNormalizedVtxos, DEFAULT_PAGE_SIZE, RestArkProvider, toVirtualStatus, ArkError, TapTreeCoder, resolveTimeHeight, canSpendOffchain, parseLegacyExpiry, isExpired, PrevoutTxField, DEFAULT_ARKADE_SERVER_URL, ProviderUnavailableError, networks as networks$1, isPastExpiry, fetchVtxoCreatedAtByTxid } from './chunk-4CMXV5SF.js';
1
+ import { AssetId, AssetGroup, AssetInput, AssetOutput, Metadata, Packet, BufferReader, BufferWriter, AssetRef, RestIndexerProvider } from './chunk-YG7T6LI3.js';
2
+ import { witnessRefToBytes, validateProgram, toASM, stringifyArtifact, serializeArkadeContractParams, resolveAsm, parseArtifact, getOpcodeValue, getOpcodeName, fromASM, deserializeArkadeContractParams, computeArkadeScriptPublicKey, bytesToASM, asmToBytes, arkadeWitnessHash, arkadeScriptHash, SUPPORTED_PROGRAM_VERSION, OPCODE_VALUES, OPCODE_NAMES, bignum_exports, ArkadeScript, ArkadeProgramScript, ARKADE_OPS, ARKADE_OPCODE_VALUES, ARKADE_OPCODE_NAMES, ARKADE_OPCODES, ARKADE_OP, toXOnly, inputName, contractHandlers, isMainnetDescriptor, descriptorIsOurs, deriveDescriptorLeafPubKey, deriveDescriptorLeafCompressedPubKey, parseHDDescriptor, identityDescriptor, DefaultVtxo, speculativeReceiveMetadata, DelegateVtxo, WALLET_RECEIVE_SOURCE, BoardingContractHandler } from './chunk-2PPL3O7Z.js';
3
+ import { VtxoScript, Transaction, isRecoverable, CSVMultisigTapscript, DEFAULT_NETWORK, resolveEmulatorPubkey, hasTerminalSpend, getNormalizedVtxos, setArkPsbtField, PrevArkTxField, ConditionWitness, craftToSpendTx, ArkAddress, isVirtualCoin, getArkPsbtFields, CosignerPublicKey, ServerResponseMismatchError, OP_RETURN_EMPTY_PKSCRIPT, canSweepOnchain, sequenceToTimelock, decodeTapscript, scriptFromTapLeafScript, CLTVMultisigTapscript, VtxoTaprootTree, timelockToSequence, assertAllowedSighashTypes, baseFetch, Intent, rateGate, DEFAULT_NETWORK_NAME, formatSighash, normalizeVtxo, getSequence, toBatchExpiry, maybeArkError, isArkError, ArkErrorName, toOffchainInputFeeParams, canRecoverOnchain, getNetwork, MultisigTapscript, isEventSourceError, isEventSourceUnavailableError, isRetryableProviderError, getAllNormalizedVtxos, DEFAULT_PAGE_SIZE, RestArkProvider, toVirtualStatus, ArkError, TapTreeCoder, resolveTimeHeight, canSpendOffchain, parseLegacyExpiry, isExpired, PrevoutTxField, DEFAULT_ARKADE_SERVER_URL, ProviderUnavailableError, networks as networks$1, isPastExpiry, fetchVtxoCreatedAtByTxid } from './chunk-L5SCQYHF.js';
4
4
  import { __export } from './chunk-NSBPE2FW.js';
5
5
  import { sha256 as sha256$1, equalBytes, hash160, sha256x2, concatBytes, randomPrivateKeyBytes, pubECDSA, pubSchnorr } from '@scure/btc-signer/utils.js';
6
6
  import { SigHash, Script, OP, OutScript, Address, RawWitness, p2tr, p2wpkh, TaprootControlBlock, DEFAULT_SEQUENCE, Transaction as Transaction$2 } from '@scure/btc-signer';
@@ -1649,6 +1649,16 @@ var EsploraProvider = class {
1649
1649
  baseUrl;
1650
1650
  pollingInterval;
1651
1651
  forcePolling;
1652
+ /**
1653
+ * Live {@link watchAddresses} subscriptions, keyed by their address set.
1654
+ *
1655
+ * Concurrent watchers over the same addresses share one transport, so a
1656
+ * caller that opens watchers in a loop — or leaks them by abandoning
1657
+ * {@link waitForIncomingFunds} — costs one entry in a `Set` rather than
1658
+ * another WebSocket plus another full-history polling loop. Entries are
1659
+ * dropped once their last subscriber stops.
1660
+ */
1661
+ addressWatches = /* @__PURE__ */ new Map();
1652
1662
  async getCoins(address) {
1653
1663
  const response = await baseFetch(`${this.baseUrl}/address/${address}/utxo`);
1654
1664
  if (!response.ok) {
@@ -1693,6 +1703,18 @@ var EsploraProvider = class {
1693
1703
  }
1694
1704
  return response.json();
1695
1705
  }
1706
+ /**
1707
+ * Activity counts for an address, without its transactions — orders of
1708
+ * magnitude smaller than `/address/{addr}/txs`, which is what makes it
1709
+ * usable as a change probe for the polling fallback.
1710
+ */
1711
+ async getAddressStats(address) {
1712
+ const response = await baseFetch(`${this.baseUrl}/address/${address}`);
1713
+ if (!response.ok) {
1714
+ throw new Error(`Failed to get address stats: ${response.statusText}`);
1715
+ }
1716
+ return response.json();
1717
+ }
1696
1718
  async getRawTransaction(txid) {
1697
1719
  const response = await baseFetch(`${this.baseUrl}/tx/${txid}/hex`);
1698
1720
  if (!response.ok) {
@@ -1724,50 +1746,227 @@ var EsploraProvider = class {
1724
1746
  blockHeight: data.block_height
1725
1747
  };
1726
1748
  }
1749
+ /**
1750
+ * Watch a set of addresses over the explorer's WebSocket, degrading to HTTP
1751
+ * polling whenever the socket is unavailable and returning to the socket as
1752
+ * soon as it can be re-established.
1753
+ *
1754
+ * Concurrent calls covering the same address set share one transport. The
1755
+ * returned function releases **this** subscription only; the transport is
1756
+ * torn down when the last subscriber releases it. Calling it more than once
1757
+ * is a no-op.
1758
+ *
1759
+ * @param addresses - Addresses to monitor; order is not significant
1760
+ * @param callback - Invoked with transactions seen after the watch started
1761
+ * @returns A function releasing this subscription
1762
+ * @remarks
1763
+ * The HTTP fallback fetches full address history per address per cycle,
1764
+ * which is dramatically more expensive than the socket — so callers should
1765
+ * release watches they no longer need rather than relying on sharing.
1766
+ * @see {@link waitForIncomingFunds} for the cancellation-aware wallet-level helper
1767
+ */
1727
1768
  async watchAddresses(addresses, callback) {
1728
- let intervalId = null;
1769
+ const key = [...addresses].sort().join("\0");
1770
+ let watch = this.addressWatches.get(key);
1771
+ if (!watch) {
1772
+ watch = this.createAddressWatch(addresses, () => this.addressWatches.delete(key));
1773
+ this.addressWatches.set(key, watch);
1774
+ }
1775
+ const subscriber = { callback };
1776
+ watch.subscribers.add(subscriber);
1777
+ const shared = watch;
1778
+ await shared.started;
1779
+ let released = false;
1780
+ return () => {
1781
+ if (released) return;
1782
+ released = true;
1783
+ shared.subscribers.delete(subscriber);
1784
+ if (shared.subscribers.size === 0) shared.teardown();
1785
+ };
1786
+ }
1787
+ /**
1788
+ * Bring up one shared address watch: a WebSocket subscription where the
1789
+ * explorer supports it, degrading to HTTP polling when it doesn't.
1790
+ *
1791
+ * @param addresses - Addresses this watch covers
1792
+ * @param onTeardown - Invoked when the watch retires, to drop the registry entry
1793
+ */
1794
+ createAddressWatch(addresses, onTeardown) {
1795
+ const subscribers = /* @__PURE__ */ new Set();
1729
1796
  const wsUrl = this.baseUrl.replace(/^http(s)?:/, "ws$1:") + "/v1/ws";
1730
- const poll = async () => {
1731
- const getAllTxs = async () => {
1732
- const txArrays = await Promise.all(
1733
- addresses.map((address) => this.getTransactions(address))
1734
- );
1735
- return txArrays.flat();
1797
+ let stopped = false;
1798
+ let timer = null;
1799
+ let pollStarted = false;
1800
+ let ws = null;
1801
+ let reconnectTimer = null;
1802
+ let reconnectFailures = 0;
1803
+ let pollSession = 0;
1804
+ const emit = (txs) => {
1805
+ if (stopped || txs.length === 0) return;
1806
+ for (const subscriber of [...subscribers]) {
1807
+ try {
1808
+ subscriber.callback(txs);
1809
+ } catch (error) {
1810
+ console.error("Address watch subscriber threw:", error);
1811
+ }
1812
+ }
1813
+ };
1814
+ const txKey2 = (tx) => `${tx.txid}_${tx.status.block_time}`;
1815
+ const getAllTxs = async () => {
1816
+ const txArrays = await Promise.all(
1817
+ addresses.map((address) => this.getTransactions(address))
1818
+ );
1819
+ return txArrays.flat();
1820
+ };
1821
+ const seen = /* @__PURE__ */ new Set();
1822
+ let baselined = false;
1823
+ let anchorHeight;
1824
+ const baseline = (async () => {
1825
+ const [history, tip] = await Promise.allSettled([getAllTxs(), this.getChainTip()]);
1826
+ if (history.status === "fulfilled") {
1827
+ for (const tx of history.value) seen.add(txKey2(tx));
1828
+ baselined = true;
1829
+ return;
1830
+ }
1831
+ console.warn(
1832
+ "Could not baseline watched addresses; the first poll pass will establish it instead:",
1833
+ history.reason
1834
+ );
1835
+ if (tip.status === "fulfilled") anchorHeight = tip.value.height;
1836
+ })();
1837
+ const report = (txs) => {
1838
+ const fresh = [];
1839
+ for (const tx of txs) {
1840
+ const key = txKey2(tx);
1841
+ if (seen.has(key)) continue;
1842
+ seen.add(key);
1843
+ fresh.push(tx);
1844
+ }
1845
+ if (fresh.length === 0) return;
1846
+ emit(fresh);
1847
+ };
1848
+ const startPolling = async () => {
1849
+ if (stopped || pollStarted) return;
1850
+ pollStarted = true;
1851
+ console.warn(
1852
+ `Esplora websocket unavailable (${wsUrl}); falling back to HTTP polling every ${this.pollingInterval}ms for ${addresses.length} address(es) while retrying the socket`
1853
+ );
1854
+ let failures = 0;
1855
+ const activityFingerprint = async () => {
1856
+ try {
1857
+ const stats = await Promise.all(
1858
+ addresses.map((address) => this.getAddressStats(address))
1859
+ );
1860
+ const counted = (activity) => typeof activity?.tx_count === "number" && typeof activity.funded_txo_count === "number" && typeof activity.spent_txo_count === "number";
1861
+ const usable = stats.every(
1862
+ (s) => counted(s?.chain_stats) && counted(s?.mempool_stats)
1863
+ );
1864
+ if (!usable) return void 0;
1865
+ if (stats.some((s) => s.mempool_stats.tx_count > 0)) return void 0;
1866
+ return stats.map(
1867
+ ({ chain_stats: chain }) => `${chain.tx_count}:${chain.funded_txo_count}:${chain.spent_txo_count}`
1868
+ ).join(",");
1869
+ } catch {
1870
+ return void 0;
1871
+ }
1872
+ };
1873
+ let lastFingerprint;
1874
+ const session = pollSession;
1875
+ const isCurrentLoop = () => !stopped && session === pollSession;
1876
+ const schedule = () => {
1877
+ if (!isCurrentLoop()) return;
1878
+ timer = setTimeout(tick, this.pollingInterval * 2 ** failures);
1736
1879
  };
1737
- const initialTxs = await getAllTxs();
1738
- const txKey2 = (tx) => `${tx.txid}_${tx.status.block_time}`;
1739
- const existingTxs = new Set(initialTxs.map(txKey2));
1740
- intervalId = setInterval(async () => {
1880
+ const tick = async () => {
1741
1881
  try {
1882
+ const fingerprint = await activityFingerprint();
1883
+ if (!isCurrentLoop()) return;
1884
+ if (fingerprint !== void 0 && fingerprint === lastFingerprint) {
1885
+ failures = 0;
1886
+ schedule();
1887
+ return;
1888
+ }
1742
1889
  const currentTxs = await getAllTxs();
1743
- const newTxs = currentTxs.filter((tx) => !existingTxs.has(txKey2(tx)));
1744
- if (newTxs.length > 0) {
1745
- newTxs.forEach((tx) => existingTxs.add(txKey2(tx)));
1746
- callback(newTxs);
1890
+ if (!isCurrentLoop()) return;
1891
+ lastFingerprint = fingerprint;
1892
+ if (baselined) {
1893
+ report(currentTxs);
1894
+ } else if (anchorHeight !== void 0) {
1895
+ const arrivedAfterStart = (tx) => !tx.status.confirmed || tx.status.block_height === void 0 || tx.status.block_height > anchorHeight;
1896
+ for (const tx of currentTxs) {
1897
+ if (!arrivedAfterStart(tx)) seen.add(txKey2(tx));
1898
+ }
1899
+ baselined = true;
1900
+ report(currentTxs);
1901
+ } else {
1902
+ console.warn(
1903
+ `Esplora address watch established its baseline late for ${addresses.length} address(es); deposits arriving before now may not have been reported`
1904
+ );
1905
+ for (const tx of currentTxs) seen.add(txKey2(tx));
1906
+ baselined = true;
1747
1907
  }
1908
+ failures = 0;
1748
1909
  } catch (error) {
1749
- console.error("Error in polling mechanism:", error);
1910
+ failures = Math.min(failures + 1, MAX_POLL_BACKOFF_EXPONENT);
1911
+ console.error("Error polling watched addresses:", error);
1750
1912
  }
1751
- }, this.pollingInterval);
1913
+ schedule();
1914
+ };
1915
+ await baseline;
1916
+ if (!isCurrentLoop()) return;
1917
+ await tick();
1752
1918
  };
1753
- let ws = null;
1754
- const stopFunc = () => {
1755
- if (ws) ws.close();
1756
- if (intervalId) clearInterval(intervalId);
1919
+ const stopPolling = () => {
1920
+ pollSession++;
1921
+ if (timer) {
1922
+ clearTimeout(timer);
1923
+ timer = null;
1924
+ }
1925
+ pollStarted = false;
1757
1926
  };
1758
- if (this.forcePolling) {
1759
- await poll();
1760
- return stopFunc;
1761
- }
1762
- try {
1763
- ws = new WebSocket(wsUrl);
1764
- ws.addEventListener("open", () => {
1927
+ const handleSocketFailure = () => {
1928
+ if (stopped) return Promise.resolve();
1929
+ scheduleReconnect();
1930
+ return startPolling();
1931
+ };
1932
+ const scheduleReconnect = () => {
1933
+ if (stopped || reconnectTimer !== null) return;
1934
+ const delay = RECONNECT_BASE_DELAY_MS * 2 ** Math.min(reconnectFailures, MAX_RECONNECT_BACKOFF_EXPONENT);
1935
+ reconnectFailures++;
1936
+ reconnectTimer = setTimeout(() => {
1937
+ reconnectTimer = null;
1938
+ connect();
1939
+ }, delay);
1940
+ };
1941
+ const connect = () => {
1942
+ if (stopped) return Promise.resolve();
1943
+ const previous = ws;
1944
+ ws = null;
1945
+ if (previous) {
1946
+ try {
1947
+ previous.close();
1948
+ } catch {
1949
+ }
1950
+ }
1951
+ let socket;
1952
+ try {
1953
+ socket = new WebSocket(wsUrl);
1954
+ } catch {
1955
+ return handleSocketFailure();
1956
+ }
1957
+ ws = socket;
1958
+ const isCurrent = () => !stopped && ws === socket;
1959
+ socket.addEventListener("open", () => {
1960
+ if (!isCurrent()) return;
1961
+ reconnectFailures = 0;
1765
1962
  const subscribeMsg = {
1766
1963
  "track-addresses": addresses
1767
1964
  };
1768
- ws.send(JSON.stringify(subscribeMsg));
1965
+ socket.send(JSON.stringify(subscribeMsg));
1966
+ stopPolling();
1769
1967
  });
1770
- ws.addEventListener("message", (event) => {
1968
+ socket.addEventListener("message", (event) => {
1969
+ if (!isCurrent()) return;
1771
1970
  try {
1772
1971
  const newTxs = [];
1773
1972
  const message = JSON.parse(event.data.toString());
@@ -1779,19 +1978,42 @@ var EsploraProvider = class {
1779
1978
  newTxs.push(...aux[address][type].filter(isExplorerTransaction));
1780
1979
  }
1781
1980
  }
1782
- if (newTxs.length > 0) callback(newTxs);
1981
+ report(newTxs);
1783
1982
  } catch (error) {
1784
1983
  console.error("Failed to process WebSocket message:", error);
1785
1984
  }
1786
1985
  });
1787
- ws.addEventListener("error", async () => {
1788
- await poll();
1986
+ socket.addEventListener("error", () => {
1987
+ if (isCurrent()) void handleSocketFailure();
1789
1988
  });
1790
- } catch {
1791
- if (intervalId) clearInterval(intervalId);
1792
- await poll();
1793
- }
1794
- return stopFunc;
1989
+ socket.addEventListener("close", () => {
1990
+ if (isCurrent()) void handleSocketFailure();
1991
+ });
1992
+ return Promise.resolve();
1993
+ };
1994
+ const teardown = () => {
1995
+ if (stopped) return;
1996
+ stopped = true;
1997
+ onTeardown();
1998
+ if (timer) {
1999
+ clearTimeout(timer);
2000
+ timer = null;
2001
+ }
2002
+ if (reconnectTimer !== null) {
2003
+ clearTimeout(reconnectTimer);
2004
+ reconnectTimer = null;
2005
+ }
2006
+ if (ws) {
2007
+ try {
2008
+ ws.close();
2009
+ } catch {
2010
+ }
2011
+ ws = null;
2012
+ }
2013
+ subscribers.clear();
2014
+ };
2015
+ const started = this.forcePolling ? startPolling() : connect().then(() => baseline);
2016
+ return { subscribers, teardown, started };
1795
2017
  }
1796
2018
  async getChainTip() {
1797
2019
  const tipBlocks = await baseFetch(`${this.baseUrl}/blocks`);
@@ -1808,6 +2030,8 @@ var EsploraProvider = class {
1808
2030
  const hash = tip[0].id;
1809
2031
  return {
1810
2032
  height: tip[0].height,
2033
+ // `mediantime`, never `timestamp`: the latter is the header's own
2034
+ // `nTime`, and this field is specified as MTP.
1811
2035
  time: tip[0].mediantime,
1812
2036
  hash
1813
2037
  };
@@ -1873,6 +2097,9 @@ var isExplorerTransaction = (tx) => {
1873
2097
  (vout) => typeof vout.scriptpubkey_address === "string" && typeof vout.value === "number"
1874
2098
  ) && typeof tx.status === "object" && typeof tx.status.confirmed === "boolean";
1875
2099
  };
2100
+ var MAX_POLL_BACKOFF_EXPONENT = 4;
2101
+ var RECONNECT_BASE_DELAY_MS = 1e3;
2102
+ var MAX_RECONNECT_BACKOFF_EXPONENT = 5;
1876
2103
  var getVarIntSize = (n) => {
1877
2104
  if (n < 253) return 1;
1878
2105
  if (n <= 65535) return 3;
@@ -16278,19 +16505,53 @@ function selectVirtualCoins(coins, targetAmount) {
16278
16505
  changeAmount
16279
16506
  };
16280
16507
  }
16281
- async function waitForIncomingFunds(wallet) {
16508
+ var AbortError = class extends Error {
16509
+ constructor(message = "Operation aborted") {
16510
+ super(message);
16511
+ this.name = "AbortError";
16512
+ }
16513
+ };
16514
+ function abortReason(signal) {
16515
+ const { reason } = signal;
16516
+ if (reason instanceof Error) return reason;
16517
+ return new AbortError(typeof reason === "string" ? reason : void 0);
16518
+ }
16519
+ async function waitForIncomingFunds(wallet, options) {
16520
+ const { signal, timeoutMs } = options ?? {};
16521
+ if (signal?.aborted) throw abortReason(signal);
16282
16522
  let stopFunc;
16283
16523
  let settled = false;
16284
- return new Promise((resolve) => {
16524
+ let timeoutId;
16525
+ let onAbort;
16526
+ return new Promise((resolve, reject) => {
16527
+ const settle = (deliver) => {
16528
+ if (settled) return;
16529
+ settled = true;
16530
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
16531
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
16532
+ stopFunc?.();
16533
+ deliver();
16534
+ };
16535
+ const cancel = (reason) => settle(() => reject(reason));
16536
+ if (signal) {
16537
+ onAbort = () => cancel(abortReason(signal));
16538
+ signal.addEventListener("abort", onAbort);
16539
+ }
16540
+ if (timeoutMs !== void 0) {
16541
+ timeoutId = setTimeout(
16542
+ () => cancel(new AbortError(`waitForIncomingFunds timed out after ${timeoutMs}ms`)),
16543
+ timeoutMs
16544
+ );
16545
+ }
16285
16546
  wallet.notifyIncomingFunds((funds) => {
16286
16547
  const hasFunds = funds.type === "utxo" ? funds.coins.length > 0 : funds.newVtxos.length > 0;
16287
16548
  if (settled || !hasFunds) return;
16288
- settled = true;
16289
- resolve(funds);
16290
- stopFunc?.();
16549
+ settle(() => resolve(funds));
16291
16550
  }).then((stop) => {
16292
16551
  stopFunc = stop;
16293
16552
  if (settled) stop();
16553
+ }).catch((error) => {
16554
+ cancel(error);
16294
16555
  });
16295
16556
  });
16296
16557
  }
@@ -20120,6 +20381,7 @@ var ListUnspentMethod = "blockchain.scripthash.listunspent";
20120
20381
  var MISSING_TRANSACTION = "missingtransaction";
20121
20382
  var MAX_FETCH_TRANSACTIONS_ATTEMPTS = 5;
20122
20383
  var BLOCK_HEADER_SIZE = 80;
20384
+ var MTP_WINDOW = 11;
20123
20385
  function parseBlockHeader(headerHex) {
20124
20386
  const headerBytes = hex.decode(headerHex);
20125
20387
  if (headerBytes.length !== BLOCK_HEADER_SIZE) {
@@ -20426,6 +20688,8 @@ var ElectrumOnchainProvider = class {
20426
20688
  ws;
20427
20689
  network;
20428
20690
  chain;
20691
+ mtpCache;
20692
+ mtpInflight;
20429
20693
  async getCoins(address) {
20430
20694
  const script = this.encodeAddress(address);
20431
20695
  const scriptHash = toScriptHash(script);
@@ -20681,15 +20945,58 @@ var ElectrumOnchainProvider = class {
20681
20945
  blockTime
20682
20946
  };
20683
20947
  }
20948
+ /** `time` is median-time-past, per {@link OnchainProvider.getChainTip};
20949
+ * Electrum serves raw headers and no MTP, so it is computed here. */
20684
20950
  async getChainTip() {
20685
20951
  const tip = await this.chain.subscribeHeaders();
20686
20952
  const { hash, timestamp } = parseBlockHeader(tip.hex);
20687
20953
  return {
20688
20954
  height: tip.height,
20689
- time: timestamp,
20955
+ time: await this.medianTimePast(tip.height, timestamp, hash),
20690
20956
  hash
20691
20957
  };
20692
20958
  }
20959
+ /**
20960
+ * Consensus's `GetMedianTimePast`, ending at and including `height`.
20961
+ *
20962
+ * Cached per tip HASH, not height: this runs on every balance read, and
20963
+ * hashing means a reorg at the same height recomputes rather than serving
20964
+ * the orphaned chain's median.
20965
+ */
20966
+ async medianTimePast(height, tipTime, hash) {
20967
+ if (this.mtpCache?.hash === hash) return this.mtpCache.mtp;
20968
+ if (this.mtpInflight?.hash === hash) return this.mtpInflight.mtp;
20969
+ const mtp = this.readMedianTimePast(height, tipTime, hash).finally(() => {
20970
+ this.mtpInflight = void 0;
20971
+ });
20972
+ this.mtpInflight = { hash, mtp };
20973
+ return mtp;
20974
+ }
20975
+ /** Degrades to the tip's `nTime` rather than throwing — a caller that
20976
+ * cannot read the tip at all is worse off. */
20977
+ async readMedianTimePast(height, tipTime, hash) {
20978
+ const heights = [];
20979
+ for (let h = height - 1; h >= 0 && heights.length < MTP_WINDOW - 1; h--) heights.push(h);
20980
+ if (heights.length === 0) return tipTime;
20981
+ let timestamps;
20982
+ try {
20983
+ const headers = await this.chain.fetchBlockHeaders(heights);
20984
+ timestamps = [
20985
+ tipTime,
20986
+ ...headers.map((header) => parseBlockHeader(header.hex).timestamp)
20987
+ ];
20988
+ } catch (e) {
20989
+ console.warn(
20990
+ "Failed to fetch the median-time-past window; using the tip's own time",
20991
+ e
20992
+ );
20993
+ return tipTime;
20994
+ }
20995
+ timestamps.sort((a, b) => a - b);
20996
+ const mtp = timestamps[Math.floor(timestamps.length / 2)];
20997
+ this.mtpCache = { hash, mtp };
20998
+ return mtp;
20999
+ }
20693
21000
  async watchAddresses(addresses, eventCallback) {
20694
21001
  const scripts = addresses.map((addr) => this.encodeAddress(addr));
20695
21002
  const scriptHashes = scripts.map(toScriptHash);
@@ -23508,6 +23815,6 @@ function createDefaultPaymentRouter(wallet) {
23508
23815
  (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
23509
23816
  */
23510
23817
 
23511
- export { ARKADE_MAGIC, ARKADE_SALTED_PREIMAGE_TAG, ARKADE_SWAP_PREIMAGE_TAG, ActivityRegistry, AmbiguousRouteError, ArkNote, ArkadeCash, ArkadeCashCreateError, AssetManager, BIP21, BIP21Error, BIP322, BLOCKED_UPGRADE_TIMEOUT_MS, Batch, CachingArkProvider, ChainedTxType, ConnectionDisposedError, ContractManager, ContractRepositoryImpl, ContractWatcher, DB_VERSION, DEFAULT_MESSAGE_TIMEOUTS, DEFAULT_MIN_BATCH_EXPIRY_SECONDS, DEFAULT_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, DatabaseUpgradeBlockedError, DelegateManagerImpl, DelegateNotConfiguredError, DelegatorManagerImpl, DelegatorNotConfiguredError, DescriptorIdentity, DescriptorSigningProviderMissingError, DustChangeError, ELECTRUM_TCP_HOST, ELECTRUM_WS_URL, ESPLORA_URL, ElectrumOnchainProvider, EmulatorPacket, EsploraProvider, Estimator, Extension, ExtensionNotFoundError, ForeignDescriptorError, HDDescriptorProvider, INTENT_TERMINAL_STATES, InMemoryContractRepository, InMemoryIntentRepository, InMemoryVirtualTxRepository, InMemoryWalletRepository, IndexedDBContractRepository, IndexedDBIntentRepository, IndexedDBVirtualTxRepository, IndexedDBWalletRepository, MAX_USED_SIGNING_DESCRIPTORS_LOOK_AHEAD, MESSAGE_BUS_INITIALIZING, MESSAGE_BUS_NOT_INITIALIZED, MIGRATION_KEY, MUTINYNET_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, MessageBus, MessageBusInitializingError, MessageBusNotInitializedError, MissingSigningDescriptorError, MnemonicIdentity, OnchainWallet, P2A, PaymentRouter, PrevTxUnavailableError, REGTEST_MIN_BATCH_EXPIRY_SECONDS, REGTEST_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, Ramps, ReadonlyAssetManager, ReadonlyDescriptorIdentity, ReadonlySingleKey, ReadonlyWallet, ReadonlyWalletError, RestDelegateProvider, RestDelegatorProvider, RestEmulatorProvider, SIGNET_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, SeedIdentity, ServiceWorkerReadonlyWallet, ServiceWorkerTimeoutError, ServiceWorkerWallet, SingleKey, TxTree, TxType, TxWeightEstimator, UnannotatableInputError, UnilateralExit, UnknownPacket, Unroll, VtxoManager, Wallet2 as Wallet, WalletCannotAllocateAddressError, WalletCannotSignError, WalletMessageHandler, WalletNotInitializedError, WalletRepositoryImpl, WsElectrumChainSource, adoptContractDescriptor, arkRail, arkTarget, arkade_exports, assertFinalCommitmentMatchesValidated, assertIntentIdUnique, assertSendableAmount, assertSubmittedArkTxid, assertValidBatchExpiry, assertValidServerUnrollScript, assetMintResolver, attachPrevArkTxs, attachPrevoutTxs, awaitTransaction, boardingResolver, btcTarget, buildForfeitTx, buildOffchainTx, buildPreimageMessage, buildSaltedPreimageMessage, claimWithPreimageIdentity, classifyAgainstSignerSet, classifyContractSigner, closeDatabase, collabExitResolver, combineTapscriptSigs, contractFromArkContract, contractFromArkContractWithAddress, contractPreimage, contractSigner, createAssetPacket, createDefaultActivityRegistry, createDefaultPaymentRouter, createExitChainResolver, createManagedConnection, decodeArkContract, defaultBatchExpiryPolicy, defaultCheckpointExitDelayPolicy, deleteByIndex, deserializeAssets, deserializeExitPackage, deserializeUtxo, deserializeVtxo, encodeArkContract, exitObserverFor, extendVirtualCoinForContract, extractArkProviderUrl, gateExclusion, gatedContracts, getAllByIndexValues, getMigrationStatus, getRandomId, hasBoardingTxExpired, hasCandidates, intentMatchesFilter, intentPageBounds, invoiceTarget, isAddressAllocationCapable, isArkContract, isBatchSignable, isBtcAddress, isContractGenericallySpendable, isCooperativelyMigratable, isDeterministicSigner, isDiscoverable, isHDAllocationCapable, isHDDeterministicSignCapable, isHDWalletCapable, isLightningInvoice, isLnurl, isMessageBusInitializingError, isMessageBusNotInitializedError, isPerArtifactDescriptor, isSigningIdentity, isSubdust, isTerminalIntentState, isValidArkAddress, isVtxoExpiringSoon, isVtxoForScript, isWatchedContract, logExcludedVtxos, makeHandle, matchServerCheckpoints, mergeChainedTxType, migrateWalletRepository, notifyExitObserved, onchainRail, openDatabase, outpointExclusion, outpointReasons, promisifyRequest, provisionClaimSecret, provisionRefundKey, requiresMigration, resolveBatchExpiryPolicy, resolveCheckpointExitDelayPolicy, resolveDescriptorSigner, resolvePrevTxs, resolveSendAmount, rollbackMigration, saveVtxosForContract, scriptFromArkAddress, selectCoinsWithAsset, selectVirtualCoins, serializeAssets, serializeExitPackage, serializeUtxo, serializeVtxo, setupServiceWorker, signAndSubmitOffchainTx, signerSetFromInfo, signingDescriptorIndex, strictSigningDescriptorIndex, toXOnlySignerHex, tryResolveSendAmount, validateBatchRecipients, validateConnectorsTxGraph, validateVtxoTxGraph, verifyTapscriptSignatures, waitForIncomingFunds, warnAndFilterVtxosForScript, withPrevTxs };
23512
- //# sourceMappingURL=chunk-VBHXBI7F.js.map
23513
- //# sourceMappingURL=chunk-VBHXBI7F.js.map
23818
+ export { ARKADE_MAGIC, ARKADE_SALTED_PREIMAGE_TAG, ARKADE_SWAP_PREIMAGE_TAG, AbortError, ActivityRegistry, AmbiguousRouteError, ArkNote, ArkadeCash, ArkadeCashCreateError, AssetManager, BIP21, BIP21Error, BIP322, BLOCKED_UPGRADE_TIMEOUT_MS, Batch, CachingArkProvider, ChainedTxType, ConnectionDisposedError, ContractManager, ContractRepositoryImpl, ContractWatcher, DB_VERSION, DEFAULT_MESSAGE_TIMEOUTS, DEFAULT_MIN_BATCH_EXPIRY_SECONDS, DEFAULT_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, DatabaseUpgradeBlockedError, DelegateManagerImpl, DelegateNotConfiguredError, DelegatorManagerImpl, DelegatorNotConfiguredError, DescriptorIdentity, DescriptorSigningProviderMissingError, DustChangeError, ELECTRUM_TCP_HOST, ELECTRUM_WS_URL, ESPLORA_URL, ElectrumOnchainProvider, EmulatorPacket, EsploraProvider, Estimator, Extension, ExtensionNotFoundError, ForeignDescriptorError, HDDescriptorProvider, INTENT_TERMINAL_STATES, InMemoryContractRepository, InMemoryIntentRepository, InMemoryVirtualTxRepository, InMemoryWalletRepository, IndexedDBContractRepository, IndexedDBIntentRepository, IndexedDBVirtualTxRepository, IndexedDBWalletRepository, MAX_USED_SIGNING_DESCRIPTORS_LOOK_AHEAD, MESSAGE_BUS_INITIALIZING, MESSAGE_BUS_NOT_INITIALIZED, MIGRATION_KEY, MUTINYNET_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, MessageBus, MessageBusInitializingError, MessageBusNotInitializedError, MissingSigningDescriptorError, MnemonicIdentity, OnchainWallet, P2A, PaymentRouter, PrevTxUnavailableError, REGTEST_MIN_BATCH_EXPIRY_SECONDS, REGTEST_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, Ramps, ReadonlyAssetManager, ReadonlyDescriptorIdentity, ReadonlySingleKey, ReadonlyWallet, ReadonlyWalletError, RestDelegateProvider, RestDelegatorProvider, RestEmulatorProvider, SIGNET_MIN_CHECKPOINT_EXIT_DELAY_SECONDS, SeedIdentity, ServiceWorkerReadonlyWallet, ServiceWorkerTimeoutError, ServiceWorkerWallet, SingleKey, TxTree, TxType, TxWeightEstimator, UnannotatableInputError, UnilateralExit, UnknownPacket, Unroll, VtxoManager, Wallet2 as Wallet, WalletCannotAllocateAddressError, WalletCannotSignError, WalletMessageHandler, WalletNotInitializedError, WalletRepositoryImpl, WsElectrumChainSource, adoptContractDescriptor, arkRail, arkTarget, arkade_exports, assertFinalCommitmentMatchesValidated, assertIntentIdUnique, assertSendableAmount, assertSubmittedArkTxid, assertValidBatchExpiry, assertValidServerUnrollScript, assetMintResolver, attachPrevArkTxs, attachPrevoutTxs, awaitTransaction, boardingResolver, btcTarget, buildForfeitTx, buildOffchainTx, buildPreimageMessage, buildSaltedPreimageMessage, claimWithPreimageIdentity, classifyAgainstSignerSet, classifyContractSigner, closeDatabase, collabExitResolver, combineTapscriptSigs, contractFromArkContract, contractFromArkContractWithAddress, contractPreimage, contractSigner, createAssetPacket, createDefaultActivityRegistry, createDefaultPaymentRouter, createExitChainResolver, createManagedConnection, decodeArkContract, defaultBatchExpiryPolicy, defaultCheckpointExitDelayPolicy, deleteByIndex, deserializeAssets, deserializeExitPackage, deserializeUtxo, deserializeVtxo, encodeArkContract, exitObserverFor, extendVirtualCoinForContract, extractArkProviderUrl, gateExclusion, gatedContracts, getAllByIndexValues, getMigrationStatus, getRandomId, hasBoardingTxExpired, hasCandidates, intentMatchesFilter, intentPageBounds, invoiceTarget, isAddressAllocationCapable, isArkContract, isBatchSignable, isBtcAddress, isContractGenericallySpendable, isCooperativelyMigratable, isDeterministicSigner, isDiscoverable, isHDAllocationCapable, isHDDeterministicSignCapable, isHDWalletCapable, isLightningInvoice, isLnurl, isMessageBusInitializingError, isMessageBusNotInitializedError, isPerArtifactDescriptor, isSigningIdentity, isSubdust, isTerminalIntentState, isValidArkAddress, isVtxoExpiringSoon, isVtxoForScript, isWatchedContract, logExcludedVtxos, makeHandle, matchServerCheckpoints, mergeChainedTxType, migrateWalletRepository, notifyExitObserved, onchainRail, openDatabase, outpointExclusion, outpointReasons, promisifyRequest, provisionClaimSecret, provisionRefundKey, requiresMigration, resolveBatchExpiryPolicy, resolveCheckpointExitDelayPolicy, resolveDescriptorSigner, resolvePrevTxs, resolveSendAmount, rollbackMigration, saveVtxosForContract, scriptFromArkAddress, selectCoinsWithAsset, selectVirtualCoins, serializeAssets, serializeExitPackage, serializeUtxo, serializeVtxo, setupServiceWorker, signAndSubmitOffchainTx, signerSetFromInfo, signingDescriptorIndex, strictSigningDescriptorIndex, toXOnlySignerHex, tryResolveSendAmount, validateBatchRecipients, validateConnectorsTxGraph, validateVtxoTxGraph, verifyTapscriptSignatures, waitForIncomingFunds, warnAndFilterVtxosForScript, withPrevTxs };
23819
+ //# sourceMappingURL=chunk-TA7XLEP2.js.map
23820
+ //# sourceMappingURL=chunk-TA7XLEP2.js.map