Skip to content

fix failing api calls due to inactive service worker #731

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/tender-flies-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"wallet": patch
---

fix failing api calls due to inactive service worker
6 changes: 2 additions & 4 deletions apps/wallet/src/data/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import { createTRPCProxyClient } from '@trpc/client'
import { initTRPC } from '@trpc/server'
import superjson from 'superjson'
import { createChromeHandler } from 'trpc-chrome/adapter'
import { chromeLink } from 'trpc-chrome/link'
import { z } from 'zod'

import * as bitcoin from './bitcoin/bitcoin'
import { chromeLinkWithRetries } from './chromeLink'
import * as ethereum from './ethereum/ethereum'
import { getKeystore } from './keystore'
import * as solana from './solana/solana'
Expand Down Expand Up @@ -601,10 +601,8 @@ export async function createAPI() {
}

export function createAPIClient() {
const port = chrome.runtime.connect()

return createTRPCProxyClient<APIRouter>({
links: [chromeLink({ port })],
links: [chromeLinkWithRetries()],
transformer: superjson,
})
}
117 changes: 117 additions & 0 deletions apps/wallet/src/data/chromeLink.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { chromeLink } from 'trpc-chrome/link'

import type { TRPCLink } from '@trpc/client'
import type { AnyRouter } from '@trpc/server'
import type { ChromeLinkOptions } from 'trpc-chrome/link'

const MAX_RETRIES = 3
const RETRY_DELAY = 100

export function chromeLinkWithRetries<TRouter extends AnyRouter>(
options: Omit<ChromeLinkOptions, 'port'> = {},
): TRPCLink<TRouter> {
const chromeLinkOptions = options

let port: chrome.runtime.Port | null = null
let currentLink: TRPCLink<TRouter> | null = null

const createPort = () => {
if (port) {
try {
port.disconnect()
// eslint-disable-next-line no-empty
} catch {}
}

port = chrome.runtime.connect()
port.onDisconnect.addListener(() => {
port = null
currentLink = null
})

currentLink = chromeLink({ ...chromeLinkOptions, port })

return port
}

const checkConnection = () => {
if (!port || !currentLink) {
createPort()
} else {
try {
port.postMessage({ type: 'ping' })
if (chrome.runtime.lastError) {
createPort()
}
} catch {
createPort()
}
}
}

// @ts-expect-error - Custom observable missing pipe method but functionally compatible
return runtime => {
return ctx => {
let retryCount = 0

const isConnectionError = (error: unknown): boolean => {
return (
error instanceof Error &&
(error.message.includes('Attempting to use a disconnected port') ||
error.message.includes('Failed to establish connection') ||
error.message.includes('Extension context invalidated') ||
chrome.runtime.lastError !== undefined)
)
}

const handleConnectionError = (error: unknown) => {
if (isConnectionError(error) && retryCount < MAX_RETRIES) {
retryCount++
port = null
currentLink = null
setTimeout(() => retryOperation(), RETRY_DELAY * retryCount)
} else {
observer.error?.(error)
}
}

return {
subscribe(observer) {
let subscription: { unsubscribe: () => void } | null = null

const retryOperation = () => {
try {
checkConnection()

if (!currentLink) {
throw new Error('Failed to establish connection')
}

subscription = currentLink!(runtime)(ctx).subscribe({
next(value) {
observer.next?.(
value as Parameters<NonNullable<typeof observer.next>>[0],
)
observer.complete?.()
},
error(err) {
handleConnectionError(err)
},
})
} catch (error) {
handleConnectionError(error)
}
}

retryOperation()

return {
unsubscribe: () => {
subscription?.unsubscribe()
},
}
},
}
}
}
}
Loading