Skip to content

Commit

Permalink
refactor: remove async storage (#2060)
Browse files Browse the repository at this point in the history
  • Loading branch information
pwltr authored Jul 15, 2024
1 parent 94bdef3 commit d9e9e3d
Show file tree
Hide file tree
Showing 12 changed files with 168 additions and 189 deletions.
3 changes: 3 additions & 0 deletions ReactotronConfig.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import Reactotron from 'reactotron-react-native';
import { reactotronRedux } from 'reactotron-redux';
import mmkvPlugin from 'reactotron-react-native-mmkv';
import { storage } from './src/store/mmkv-storage';

const reactotron = Reactotron.configure()
.use(reactotronRedux())
.use(mmkvPlugin({ storage }))
.useReactNative()
.connect();

Expand Down
1 change: 0 additions & 1 deletion __mocks__/@react-native-async-storage/async-storage.js

This file was deleted.

6 changes: 0 additions & 6 deletions ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -1361,8 +1361,6 @@ PODS:
- React-utils (= 0.74.3)
- ReactNativeCameraKit (14.0.0-beta15):
- React-Core
- RNCAsyncStorage (1.22.3):
- React-Core
- RNCClipboard (1.14.1):
- React-Core
- RNDeviceInfo (11.1.0):
Expand Down Expand Up @@ -1560,7 +1558,6 @@ DEPENDENCIES:
- React-utils (from `../node_modules/react-native/ReactCommon/react/utils`)
- ReactCommon/turbomodule/core (from `../node_modules/react-native/ReactCommon`)
- ReactNativeCameraKit (from `../node_modules/react-native-camera-kit`)
- "RNCAsyncStorage (from `../node_modules/@react-native-async-storage/async-storage`)"
- "RNCClipboard (from `../node_modules/@react-native-clipboard/clipboard`)"
- RNDeviceInfo (from `../node_modules/react-native-device-info`)
- RNExitApp (from `../node_modules/react-native-exit-app`)
Expand Down Expand Up @@ -1731,8 +1728,6 @@ EXTERNAL SOURCES:
:path: "../node_modules/react-native/ReactCommon"
ReactNativeCameraKit:
:path: "../node_modules/react-native-camera-kit"
RNCAsyncStorage:
:path: "../node_modules/@react-native-async-storage/async-storage"
RNCClipboard:
:path: "../node_modules/@react-native-clipboard/clipboard"
RNDeviceInfo:
Expand Down Expand Up @@ -1845,7 +1840,6 @@ SPEC CHECKSUMS:
React-utils: a06061b3887c702235d2dac92dacbd93e1ea079e
ReactCommon: f00e436b3925a7ae44dfa294b43ef360fbd8ccc4
ReactNativeCameraKit: 71343efc1256720184ce980f164c7eedb78d5c16
RNCAsyncStorage: 10591b9e0a91eaffee14e69b3721009759235125
RNCClipboard: 0a720adef5ec193aa0e3de24c3977222c7e52a37
RNDeviceInfo: b899ce37a403a4dea52b7cb85e16e49c04a5b88e
RNExitApp: 00036cabe7bacbb413d276d5520bf74ba39afa6a
Expand Down
132 changes: 66 additions & 66 deletions ios/bitkit.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

3 changes: 0 additions & 3 deletions jest.setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,6 @@ jest.mock('react-native-permissions', () =>
jest.mock('@react-native-community/netinfo', () => mockRNCNetInfo);
jest.mock('react-native-localize', () => mockRNLocalize);
jest.mock('@synonymdev/react-native-ldk', () => mockLDK);
jest.mock('@react-native-async-storage/async-storage', () =>
require('@react-native-async-storage/async-storage/jest/async-storage-mock'),
);

global.net = require('net'); // needed by Electrum client. For RN it is proviced in shim.js
global.tls = require('tls'); // needed by Electrum client. For RN it is proviced in shim.js
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
"@formatjs/intl-pluralrules": "5.2.12",
"@formatjs/intl-relativetimeformat": "11.2.12",
"@gorhom/bottom-sheet": "4.6.3",
"@react-native-async-storage/async-storage": "1.22.3",
"@react-native-clipboard/clipboard": "1.14.1",
"@react-native-community/blur": "4.4.0",
"@react-native-community/netinfo": "11.3.1",
Expand Down Expand Up @@ -174,6 +173,7 @@
"react-native-skia-stub": "0.0.1",
"react-native-svg-transformer": "^1.3.0",
"reactotron-react-native": "^5.1.6",
"reactotron-react-native-mmkv": "^0.2.6",
"reactotron-redux": "^3.1.9",
"typescript": "5.4.5"
},
Expand Down
84 changes: 6 additions & 78 deletions src/components/SlashtagsProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,91 +3,19 @@ import { createContext } from 'react';
import b4a from 'b4a';
import KeyChain from '@synonymdev/slashtags-keychain';
import type { Client as IWebRelayClient } from '@synonymdev/web-relay';
import Client from '@synonymdev/web-relay/lib/client';
import { Client, Store } from '@synonymdev/web-relay/lib/client';
import SlashtagsProfile from '@synonymdev/slashtags-profile';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { format, parse } from '@synonymdev/slashtags-url';

import i18n from '../utils/i18n';
import { showToast } from '../utils/notifications';
import { getSlashtagsPrimaryKey } from '../utils/wallet';
import { WebRelayCache } from '../store/mmkv-storage';
import { seedHashSelector } from '../store/reselect/wallet';
import { showToast } from '../utils/notifications';
import { useAppSelector } from '../hooks/redux';
import { webRelaySelector } from '../store/reselect/settings';
import i18n from '../utils/i18n';

class Store {
location: string;

constructor(location: string) {
this.location = 'WEB-RELAY-CLIENT!' + location + '!';
}

async *iterator(
opts: Parameters<Client.Store['iterator']>[0],
): AsyncIterable<[string, Uint8Array | undefined]> {
const allKeys = await AsyncStorage.getAllKeys();
for (let key of allKeys) {
if (!key.startsWith(this.location)) {
continue;
}

const suffix = key.replace(this.location, '');

// @ts-ignore
if (opts.gt && suffix <= opts.gt) {
continue;
}
// @ts-ignore
if (opts.gte && suffix < opts.gte) {
continue;
}
// @ts-ignore
if (opts.lt && suffix >= opts.lt) {
continue;
}
// @ts-ignore
if (opts.lte && suffix > opts.lte) {
continue;
}

const value = await AsyncStorage.getItem(key);
const buffer = value ? b4a.from(value, 'hex') : undefined;

yield [key, buffer];
}
}

_storeKey(key: string): string {
return this.location + key;
}

async put(key: string, buffer: Uint8Array): Promise<void> {
const value = b4a.toString(buffer, 'hex');
return AsyncStorage.setItem(this._storeKey(key), value);
}

async del(key: string): Promise<void> {
return AsyncStorage.removeItem(this._storeKey(key));
}

async get(key: string): Promise<Uint8Array | undefined> {
const value = await AsyncStorage.getItem(this._storeKey(key));
const buffer = value ? b4a.from(value, 'hex') : undefined;
return buffer;
}

batch(): Store {
return this;
}

write(): Store {
return this;
}

async close(): Promise<void> {}
}
import { useAppSelector } from '../hooks/redux';

const store = new Store('slashtags.db') as unknown as Client.Store;
const store: Store = new WebRelayCache('slashtags.db');

export let webRelayClient: IWebRelayClient;
let profile: SlashtagsProfile;
Expand Down
15 changes: 12 additions & 3 deletions src/screens/Settings/DevSettings/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, { memo, ReactElement, useState } from 'react';
import RNFS, { unlink, writeFile } from 'react-native-fs';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Share from 'react-native-share';
import { useTranslation } from 'react-i18next';

Expand Down Expand Up @@ -40,6 +39,7 @@ import { showToast } from '../../../utils/notifications';
import { getFakeTransaction } from '../../../utils/wallet/testing';
import Dialog from '../../../components/Dialog';
import { resetBackupState } from '../../../store/slices/backup';
import { storage } from '../../../store/mmkv-storage';
import { __E2E__ } from '../../../constants/env';

const DevSettings = ({
Expand All @@ -56,6 +56,15 @@ const DevSettings = ({
return warningsSelector(state, selectedWallet, selectedNetwork);
});

const clearWebRelayCache = (): void => {
const keys = storage.getAllKeys();
keys.forEach((key) => {
if (key.includes('WEB-RELAY-CLIENT')) {
storage.delete(key);
}
});
};

const exportLdkLogs = async (): Promise<void> => {
const result = await zipLogs({
includeJson: true,
Expand Down Expand Up @@ -143,9 +152,9 @@ const DevSettings = ({
title: 'App Cache',
data: [
{
title: 'Clear AsyncStorage',
title: 'Clear WebRelay Cache',
type: EItemType.button,
onPress: AsyncStorage.clear,
onPress: clearWebRelayCache,
},
{
title: "Clear UTXO's",
Expand Down
4 changes: 2 additions & 2 deletions src/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import {
__ENABLE_REDUX_LOGGER__,
__JEST__,
} from '../constants/env';
import mmkvStorage from './mmkv-storage';
import { reduxStorage } from './mmkv-storage';
import rootReducer, { RootReducer } from './reducers';
import migrations from './migrations';

Expand All @@ -30,7 +30,7 @@ if (__ENABLE_REDUX_LOGGER__) {

const persistConfig = {
key: 'root',
storage: mmkvStorage,
storage: reduxStorage,
// increase version after store shape changes
version: 43,
stateReconciler: autoMergeLevel2,
Expand Down
69 changes: 66 additions & 3 deletions src/store/mmkv-storage.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { MMKV } from 'react-native-mmkv';
import { Storage } from 'redux-persist';
import { MMKV } from 'react-native-mmkv';
import type { IteratorOptions } from 'level';

export const storage = new MMKV();

const mmkvStorage: Storage = {
export const reduxStorage: Storage = {
setItem: (key, value) => {
storage.set(key, value);
return Promise.resolve(true);
Expand All @@ -18,4 +19,66 @@ const mmkvStorage: Storage = {
},
};

export default mmkvStorage;
export class WebRelayCache {
location: string;

constructor(location: string) {
this.location = 'WEB-RELAY-CLIENT!' + location + '!';
}

private getKey(key: string): string {
return this.location + key;
}

async *iterator(
opts: IteratorOptions<string, Uint8Array>,
): AsyncIterable<[string, Uint8Array | undefined]> {
const allKeys = await storage.getAllKeys();
for (let key of allKeys) {
if (!key.startsWith(this.location)) {
continue;
}

const suffix = key.replace(this.location, '');

if (opts.gt && suffix <= opts.gt) {
continue;
}
if (opts.gte && suffix < opts.gte) {
continue;
}
if (opts.lt && suffix >= opts.lt) {
continue;
}
if (opts.lte && suffix > opts.lte) {
continue;
}

const buffer = await storage.getBuffer(key);

yield [key, buffer];
}
}

async get(key: string): Promise<Uint8Array | undefined> {
return storage.getBuffer(this.getKey(key));
}

async put(key: string, buffer: Uint8Array): Promise<void> {
return storage.set(this.getKey(key), buffer);
}

async del(key: string): Promise<void> {
return storage.delete(this.getKey(key));
}

batch(): WebRelayCache {
return this;
}

write(): WebRelayCache {
return this;
}

async close(): Promise<void> {}
}
6 changes: 1 addition & 5 deletions src/store/reducers/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { UnknownAction, combineReducers } from 'redux';
import AsyncStorage from '@react-native-async-storage/async-storage';

import { storage } from '../mmkv-storage';
import actions from '../actions/actions';
Expand Down Expand Up @@ -43,11 +42,8 @@ const rootReducer = (
): ReturnType<typeof appReducer> => {
if (action.type === actions.WIPE_APP) {
console.log('Wiping app data...');
// Clear mmkv persisted storage
// Clear MMKV persisted storage
storage.clearAll();
// Clear web relay client storage
AsyncStorage.clear().catch(() => {});

// Reset all stores
return appReducer(undefined, action);
}
Expand Down
32 changes: 11 additions & 21 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3835,17 +3835,6 @@ __metadata:
languageName: node
linkType: hard

"@react-native-async-storage/async-storage@npm:1.22.3":
version: 1.22.3
resolution: "@react-native-async-storage/async-storage@npm:1.22.3"
dependencies:
merge-options: ^3.0.4
peerDependencies:
react-native: ^0.0.0-0 || >=0.60 <1.0
checksum: bbf0f49c4441361d24f5c7a236862757d1addb7332d4c11ed7238b7023e882d2280290059602d9099cee094f60aeb11aad3f2017652ab6e143544e61dccadb73
languageName: node
linkType: hard

"@react-native-clipboard/clipboard@npm:1.14.1":
version: 1.14.1
resolution: "@react-native-clipboard/clipboard@npm:1.14.1"
Expand Down Expand Up @@ -6355,7 +6344,6 @@ __metadata:
"@gorhom/bottom-sheet": 4.6.3
"@ptsecurity/commitlint-config": ^2.0.0
"@radar/lnrpc": ^0.11.1-beta.1
"@react-native-async-storage/async-storage": 1.22.3
"@react-native-clipboard/clipboard": 1.14.1
"@react-native-community/blur": 4.4.0
"@react-native-community/netinfo": 11.3.1
Expand Down Expand Up @@ -6469,6 +6457,7 @@ __metadata:
react-native-zip-archive: 6.1.0
react-redux: 9.1.1
reactotron-react-native: ^5.1.6
reactotron-react-native-mmkv: ^0.2.6
reactotron-redux: ^3.1.9
readable-stream: 4.5.2
redux: 5.0.1
Expand Down Expand Up @@ -12072,15 +12061,6 @@ __metadata:
languageName: node
linkType: hard

"merge-options@npm:^3.0.4":
version: 3.0.4
resolution: "merge-options@npm:3.0.4"
dependencies:
is-plain-obj: ^2.1.0
checksum: d86ddb3dd6e85d558dbf25dc944f3527b6bacb944db3fdda6e84a3f59c4e4b85231095f58b835758b9a57708342dee0f8de0dffa352974a48221487fe9f4584f
languageName: node
linkType: hard

"merge-stream@npm:^2.0.0":
version: 2.0.0
resolution: "merge-stream@npm:2.0.0"
Expand Down Expand Up @@ -14576,6 +14556,16 @@ __metadata:
languageName: node
linkType: hard

"reactotron-react-native-mmkv@npm:^0.2.6":
version: 0.2.6
resolution: "reactotron-react-native-mmkv@npm:0.2.6"
peerDependencies:
react-native-mmkv: "*"
reactotron-core-client: "*"
checksum: e96aa47608e4ed361893203b72d604fa527fccd0e4c8c90f91ea8347bb31d71a8b6ccd3a4f4c839b625df7d73bb8fa41238494399206359465ed2c96f95b70df
languageName: node
linkType: hard

"reactotron-react-native@npm:^5.1.6":
version: 5.1.7
resolution: "reactotron-react-native@npm:5.1.7"
Expand Down

0 comments on commit d9e9e3d

Please sign in to comment.