Skip to content

Commit

Permalink
Improve typings on MessagesRef entry store
Browse files Browse the repository at this point in the history
  • Loading branch information
KaffinPX committed Aug 9, 2024
1 parent 260ae8c commit 09c3e3a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
18 changes: 12 additions & 6 deletions src/contexts/Kaspa.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ export interface IKaspa {
provider: string
}

interface MessageEntry<M extends keyof RequestMappings> {
resolve: (value: ResponseMappings[M]) => void;
reject: (reason?: any) => void;
message: Request<M>;
}

export const defaultState: IKaspa = {
status: Status.Uninitialized,
connected: false,
Expand All @@ -34,7 +40,7 @@ export function KaspaProvider ({ children }: {
const [ kaspa, setState ] = useState(defaultState)

const connectionRef = useRef<Runtime.Port | null>(null)
const messagesRef = useRef(new Map<number, any>()) // TODO: Improve typing
const messagesRef = useRef(new Map<number, MessageEntry<any>>())
const nonceRef = useRef(0)

const getConnection = useCallback(() => {
Expand All @@ -44,7 +50,7 @@ export function KaspaProvider ({ children }: {

connection.onMessage.addListener(async (message: Response | Event) => {
if (!isEvent(message)) {
const [ resolve, reject ] = messagesRef.current.get(message.id)
const { resolve, reject } = messagesRef.current.get(message.id)!

if (!message.error) {
resolve(message.result)
Expand Down Expand Up @@ -87,9 +93,9 @@ export function KaspaProvider ({ children }: {

connectionRef.current = null

messagesRef.current.forEach(message => {
getConnection().postMessage(message[2])
})
for (const entry of messagesRef.current.values()) {
getConnection().postMessage(entry.message)
}
})

connectionRef.current = connection
Expand All @@ -105,7 +111,7 @@ export function KaspaProvider ({ children }: {
}

return new Promise<ResponseMappings[M]>((resolve, reject) => {
messagesRef.current.set(message.id, [ resolve, reject, message ])
messagesRef.current.set(message.id, { resolve, reject, message })

getConnection().postMessage(message)
})
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Wallet/Settings.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { i18n, runtime } from "webextension-polyfill"
import { runtime, i18n } from "webextension-polyfill"
import { SettingsIcon } from "lucide-react"
import GeneralTab from "@/pages/Wallet/Settings/General"
import WalletTab from "@/pages/Wallet/Settings/Wallet"
Expand Down

0 comments on commit 09c3e3a

Please sign in to comment.