Skip to content

Commit

Permalink
improve counter store by removing json methods
Browse files Browse the repository at this point in the history
  • Loading branch information
KKA11010 committed Feb 7, 2024
1 parent 750a8f6 commit 48168e9
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 50 deletions.
6 changes: 3 additions & 3 deletions src/components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -132,16 +132,16 @@ function _App() {

// init auth data
const initAuth = async () => {
const [pinHash, onboard, sawSeed, counter] = await Promise.all([
const [pinHash, onboard, sawSeed, seed] = await Promise.all([
secureStore.get(SECURESTORE_KEY),
store.get(STORE_KEYS.explainer),
store.get(STORE_KEYS.sawSeedUpdate),
store.get(STORE_KEYS.restoreCounter),
store.get(STORE_KEYS.hasSeed),
])
setAuth({ pinHash: isNull(pinHash) ? '' : pinHash })
setShouldOnboard(onboard && onboard === '1' ? false : true)
setSawSeedUpdate(sawSeed && sawSeed === '1' ? true : false)
setHasSeed(!!counter)
setHasSeed(!!seed)
// check for pin attempts and app locked state
await handlePinForeground()
}
Expand Down
4 changes: 0 additions & 4 deletions src/model/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,10 +165,6 @@ export interface IOpenPromptAutoCloseProps {
ms?: number
}

export interface ICounters {
[key: string]: number
}

export type TPayLnInvoiceReturnType = Promise<{ result?: PayLnInvoiceResponse, fee?: number, realFee?: number, error?: unknown }>

export type TRequestTokenReturnType = Promise<{ success: boolean; invoice: IInvoice | null | undefined }>
Expand Down
2 changes: 1 addition & 1 deletion src/screens/Restore/ConfirmMnemonic.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ export default function ConfirmMnemonicScreen({ navigation, route }: IConfirmMne
await saveSeed(seed)
stopLoading()
openPromptAutoClose({ msg: t('seedEnabled'), success: true })
await store.set(STORE_KEYS.restoreCounter, '')
await store.set(STORE_KEYS.hasSeed, '1')
if (route.params.comingFromOnboarding) {
return navigation.navigate('auth', { pinHash: '' })
}
Expand Down
6 changes: 3 additions & 3 deletions src/screens/Settings/Security.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { NS } from '@src/i18n'
import { secureStore, store } from '@store'
import { SECURESTORE_KEY, STORE_KEYS } from '@store/consts'
import { globals } from '@styles'
import { isNull, isStr } from '@util'
import { isNull } from '@util'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ScrollView, View } from 'react-native'
Expand All @@ -24,9 +24,9 @@ export default function SecuritySettings({ navigation, route }: TSecuritySetting
const [hasSeed, setHasSeed] = useState(false)
const init = async () => {
const pinHash = await secureStore.get(SECURESTORE_KEY)
const restoreCounter = await store.get(STORE_KEYS.restoreCounter)
const seed = await store.get(STORE_KEYS.hasSeed)
setPin(isNull(pinHash) ? '' : pinHash)
setHasSeed(isStr(restoreCounter))
setHasSeed(!!seed)
}
useEffect(() => {
void init()
Expand Down
2 changes: 1 addition & 1 deletion src/storage/store/consts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export const STORE_KEYS = {
lud16: 'nostr_lud16',
nostrReseted: 'nostr_reseted',
sawSeedUpdate: 'saw_seed_update',
restoreCounter: 'restore_counter',
hasSeed: 'has_seed',
// secure store keys
mnemonic: 'mnemonic',
seed: 'seed',
Expand Down
39 changes: 18 additions & 21 deletions src/wallet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,10 @@ import {
getMintsBalances, getMintsUrls
} from '@db'
import { l } from '@log'
import type { ICounters, IInvoice, ISecret, ITokenInfo, TPayLnInvoiceReturnType, TRequestTokenReturnType } from '@model'
import type { IInvoice, ISecret, ITokenInfo, TPayLnInvoiceReturnType, TRequestTokenReturnType } from '@model'
import { store } from '@store'
import { STORE_KEYS } from '@store/consts'
import { getCustomMintNames } from '@store/mintStore'
import { getSeed } from '@store/restore'
import { cTo, toJson } from '@store/utils'
import { decodeLnInvoice, isCashuToken, isNum } from '@util'

import { sumProofsValue, sumTokenProofs } from './proofs'
Expand Down Expand Up @@ -300,19 +298,19 @@ export async function getCounterByMintUrl(mintUrl: string) {
try {
const seed = await getSeed()
if (!seed) { return }
const counters = await store.get(STORE_KEYS.restoreCounter)
// TODO do not call getMintCurrentKeySetId() every time. find a faster way to get keysetId
const keysetId = await getMintCurrentKeySetId(mintUrl)
if (!counters) {
const storeKey = `${mintUrl}:${keysetId}`
const counter = await store.get(storeKey)
if (!counter) {
// store counters for current keyset of mint url passed as param
await store.set(STORE_KEYS.restoreCounter, toJson({ [keysetId]: 0 }))
await store.set(storeKey, '0')
return 0
}
const parsedCounters = cTo<ICounters>(counters)
l('[getCounterByMintUrl] ', { storedCounters: parsedCounters })
if (!parsedCounters[keysetId]) { parsedCounters[keysetId] = 0 }
await store.set(STORE_KEYS.restoreCounter, toJson(parsedCounters))
l('[getCounterByMintUrl] ', { keysetId, counter: parsedCounters[keysetId] })
return parsedCounters[keysetId]
l('[getCounterByMintUrl] ', { mintUrl, keysetId, storedCounter: counter })
// await store.set(storeKey, counter)
l('[getCounterByMintUrl] ', { keysetId, counter: counter })
return +counter
} catch (e) {
l('[getCounterByMintUrl] Error while getCounter: ', e)
throw Error('[getCounterByMintUrl] Error while getCounter')
Expand All @@ -323,16 +321,15 @@ export async function incrementCounterByMintUrl(mintUrl: string, count: number)
try {
const seed = await getSeed()
if (!seed) { return }
const counters = await store.get(STORE_KEYS.restoreCounter)
// TODO do not call getMintCurrentKeySetId() every time. find a faster way to get keysetId
const keysetId = await getMintCurrentKeySetId(mintUrl)
if (!counters) {
return store.set(STORE_KEYS.restoreCounter, toJson({ [keysetId]: count }))
}
const parsedCounters = cTo<ICounters>(counters)
l('[before increment] ', { keysetId, counter: parsedCounters[keysetId] })
parsedCounters[keysetId] = (parsedCounters[keysetId] || 0) + count
l('[after increment] ', { keysetId, counter: parsedCounters[keysetId] })
await store.set(STORE_KEYS.restoreCounter, toJson(parsedCounters))
const storeKey = `${mintUrl}:${keysetId}`
const counter = await store.get(storeKey)
if (!counter) { return store.set(storeKey, `${count}`) }
l('[before increment] ', { keysetId, counter })
const newCounter = +counter + count
l('[after increment] ', { keysetId, newCounter })
await store.set(storeKey, `${newCounter}`)
} catch (e) {
l('[incrementCounterByKeysetId] Error during counter increment: ', e)
throw Error('[incrementCounterByKeysetId] Error during counter increment')
Expand Down
30 changes: 13 additions & 17 deletions test/restore.test.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
import type { MintKeys, Proof } from '@cashu/cashu-ts'
import { RESTORE_INTERVAL, RESTORE_OVERSHOOT } from '@consts/mints'
import { ICounters } from '@src/model'
import { store } from '@store'
import { STORE_KEYS } from '@store/consts'
import { cTo, toJson } from '@store/utils'

type TRestoreInterval = { proofs: Proof[]; newKeys?: MintKeys; lastCount: number } | undefined


describe('test restore', () => {
// eslint-disable-next-line @typescript-eslint/await-thenable
afterAll(async () => { await store.delete(STORE_KEYS.restoreCounter) })
afterAll(async () => { await store.clear() })

const mints = [
{ mintUrl: 'mint1-2Ids', id: 'mint1-id1' },
Expand Down Expand Up @@ -173,24 +169,24 @@ describe('test restore', () => {
}
}

const storeKey = `${mints[0].mintUrl}:${mints[0].id}`

test('creates and returns new counter', async () => {
let counters = await store.get(STORE_KEYS.restoreCounter)
if (!counters) {
await store.set(STORE_KEYS.restoreCounter, toJson({ [mints[0].id]: 0 }))
counters = await store.get(STORE_KEYS.restoreCounter)
let counter = await store.get(storeKey)
if (!counter) {
await store.set(storeKey, '0')
counter = await store.get(storeKey)
}
const parsedCounters = cTo<ICounters>(counters || '')
expect(parsedCounters[mints[0].id]).toBe(0)
expect(counter).toBe('0')
})

test('increments counter', async () => {
const count = 5
const counters = await store.get(STORE_KEYS.restoreCounter)
const parsedCounters = cTo<ICounters>(counters || '')
const keysetId = mints[0].id
parsedCounters[keysetId] = (parsedCounters[keysetId] || 0) + count
await store.set(STORE_KEYS.restoreCounter, toJson(parsedCounters))
expect(parsedCounters[keysetId]).toBe(5)
const counters = await store.get(storeKey)
if (!counters) { return }
const newCounter = +counters + count
await store.set(storeKey, `${newCounter}`)
expect(newCounter).toBe(5)
})

test('restore', () => {
Expand Down

0 comments on commit 48168e9

Please sign in to comment.