//! SPDX-FileCopyrightText: 2025 Chris Duncan <chris@codecow.com>
//! SPDX-License-Identifier: GPL-3.0-or-later
-import { WorkGenerateResponse } from "nano-pow"
+import { WorkGenerateResponse } from 'nano-pow'
-export class Cache {
+const STORAGE_KEY = 'NanoPowCache'
- static clear (): void {
- this.#removeItem('NanoPowCache')
- }
+let storage: { [key: string]: string } = {}
+
+function getItem (key: string): string | null {
+ if (globalThis?.localStorage) return globalThis.localStorage.getItem(key)
+ return storage[key]
+}
+
+function removeItem (key: string): void {
+ if (globalThis?.localStorage) return globalThis.localStorage.removeItem(key)
+ storage = {}
+}
+
+function setItem (key: string, item: string): void {
+ if (globalThis?.localStorage) return globalThis.localStorage.setItem(key, item)
+ storage[key] = item
+}
+
+export function clear (): void {
+ removeItem(STORAGE_KEY)
+}
- static search (hash: bigint, difficulty: bigint): WorkGenerateResponse | null {
- const item = this.#getItem('NanoPowCache')
- if (item) {
- const cache = JSON.parse(item) as WorkGenerateResponse[]
- for (const c of cache) {
- if (BigInt(`0x${c.hash}`) === hash && BigInt(`0x${c.difficulty}`) >= difficulty) {
- return c
- }
+export function search (hash: bigint, difficulty: bigint): WorkGenerateResponse | null {
+ const item = getItem(STORAGE_KEY)
+ if (item) {
+ const cache = JSON.parse(item) as WorkGenerateResponse[]
+ for (const c of cache) {
+ if (BigInt(`0x${c.hash}`) === hash && BigInt(`0x${c.difficulty}`) >= difficulty) {
+ return c
}
}
- return null
- }
-
- static store (result: WorkGenerateResponse): WorkGenerateResponse {
- const item = this.#getItem('NanoPowCache')
- const cache = JSON.parse(item ?? '[]') as WorkGenerateResponse[]
- if (cache.push(result) > 1000) cache.shift()
- this.#setItem('NanoPowCache', JSON.stringify(cache))
- return result
}
+ return null
+}
- static #storage: { [key: string]: string } = {}
- static #getItem (key: string): string | null {
- if (globalThis?.localStorage) return globalThis.localStorage.getItem(key)
- return this.#storage[key]
- }
- static #removeItem (key: string): void {
- if (globalThis?.localStorage) return globalThis.localStorage.removeItem(key)
- this.#storage = {}
- }
- static #setItem (key: string, item: string): void {
- if (globalThis?.localStorage) return globalThis.localStorage.setItem(key, item)
- this.#storage[key] = item
- }
+export function store (result: WorkGenerateResponse): WorkGenerateResponse {
+ const item = getItem(STORAGE_KEY)
+ const cache = JSON.parse(item ?? '[]') as WorkGenerateResponse[]
+ if (cache.push(result) > 1000) cache.shift()
+ setItem(STORAGE_KEY, JSON.stringify(cache))
+ return result
}
+
+export const Cache = { clear, search, store }