Skip to content

Commit

Permalink
Merge branch 'develop' into rif-relay-v2
Browse files Browse the repository at this point in the history
- Fixed merge conflicts
  • Loading branch information
jessgusclark committed Sep 28, 2023
2 parents 1c86087 + 48d9f9f commit 71f1fd1
Show file tree
Hide file tree
Showing 18 changed files with 252 additions and 82 deletions.
5 changes: 3 additions & 2 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@
"RPC_URL_MAINNET":"https://public-node.rsk.co",
"RPC_URL_TESTNET":"https://public-node.testnet.rsk.co",
"EXPLORER_ADDRESS_URL_MAINNET":"https://explorer.rsk.co",
"EXPLORER_ADDRESS_URL_TESTNET":"https://explorer.testnet.rsk.co"
}
"EXPLORER_ADDRESS_URL_TESTNET":"https://explorer.testnet.rsk.co",
"TERMS_AND_CONDITIONS_URL": "https://drive.google.com/file/d/1-jKY7K_93g9c7kNJ__cDYkGYp03PrOO8/view"
}
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
"@react-navigation/stack": "^6.0.9",
"@reduxjs/toolkit": "^1.9.0",
"@rsksmart/rif-id-mnemonic": "^0.1.1",
"@rsksmart/rif-relay-light-sdk": "1.0.9",
"@rsksmart/rif-relay-light-sdk": "^1.0.11",
"@rsksmart/rif-wallet-abi-enhancer": "^1.0.5",
"@rsksmart/rif-wallet-adapters": "^1.0.0",
"@rsksmart/rif-wallet-bitcoin": "^1.2.0",
Expand Down Expand Up @@ -142,7 +142,7 @@
},
"resolutions": {
"@types/react": "^17",
"@rsksmart/rif-relay-light-sdk": "1.0.9"
"@rsksmart/rif-relay-light-sdk": "1.0.11"
},
"jest": {
"preset": "react-native",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ interface GlobalErrorHandlerProviderType {
GlobalErrorHandlerViewComp?: FC
}

const GlobalErrorHandlerContext = createContext<GlobalErrorHandlerType>({
export const GlobalErrorHandlerContext = createContext<GlobalErrorHandlerType>({
setGlobalError: () => {},
globalError: null,
handleReload: () => {},
Expand Down
20 changes: 12 additions & 8 deletions src/core/CoreWithStore.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import { Provider } from 'react-redux'
import { PersistGate } from 'redux-persist/integration/react'

import { store, persistor } from 'store/store'
import { createNewStore } from 'store/store'

import { Core } from './Core'

export const CoreWithStore = () => (
<Provider store={store}>
<PersistGate persistor={persistor}>
<Core />
</PersistGate>
</Provider>
)
export const CoreWithStore = () => {
const { store, persistor } = createNewStore()

return (
<Provider store={store}>
<PersistGate persistor={persistor}>
<Core />
</PersistGate>
</Provider>
)
}
14 changes: 13 additions & 1 deletion src/core/hooks/bitcoin/initializeBitcoin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ const onNoNetworksPresent = (chainId: ChainTypesByIdType) => {
return BitcoinNetworkStore.getStoredNetworks()
}

const BITCOIN_CHAINID_MAP: Record<ChainTypesByIdType, string> = {
30: bitcoinMainnet.name,
31: bitcoinTestnet.name,
}

/**
* Will return networks as an array, networks as a map (networksMap) and a function to refresh networks from the storage
* This hook will also instantiate the bitcoin networks with a BIPWithRequest class that will handle the payments for the onRequest method
Expand All @@ -48,7 +53,6 @@ const onNoNetworksPresent = (chainId: ChainTypesByIdType) => {
* @param fetcher
* @param chainId
*/

export const initializeBitcoin = (
mnemonic: string,
dispatch: AppDispatch,
Expand All @@ -69,6 +73,14 @@ export const initializeBitcoin = (
networksMap = onNoNetworksPresent(chainId)
}

// if there is a network created but does not match current chainId - create it
if (!networksMap[BITCOIN_CHAINID_MAP[chainId]]) {
networksMap = onNoNetworksPresent(chainId)
}
// Due to how the bitcoin logic is implemented... I'll transform the networksMap to only include the btc network we need
networksMap = {
[BITCOIN_CHAINID_MAP[chainId]]: networksMap[BITCOIN_CHAINID_MAP[chainId]],
}
const transformNetwork = (
network: StoredBitcoinNetworkValue,
mnemonicText: string,
Expand Down
15 changes: 9 additions & 6 deletions src/core/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,21 @@ import { RIFWallet } from '@rsksmart/rif-wallet-core'
import { KeyManagementSystem } from 'lib/core'

import { saveKeys } from 'storage/SecureStorage'

import { MMKVStorage } from '../storage/MMKVStorage'
import { ChainTypesByIdType } from 'shared/constants/chainConstants'
import { MMKVStorage } from 'storage/MMKVStorage'

type CreateRIFWallet = (wallet: Wallet) => Promise<RIFWallet>

export const loadExistingWallet =
(createRIFWallet: CreateRIFWallet) => async (serializedKeys: string) => {
(createRIFWallet: CreateRIFWallet) =>
async (serializedKeys: string, chainId: ChainTypesByIdType) => {
try {
const { kms, wallets } =
KeyManagementSystem.fromSerialized(serializedKeys)
const { kms, wallets } = KeyManagementSystem.fromSerialized(
serializedKeys,
chainId,
)

const rifWallet = await createRIFWallet(Object.values(wallets)[0])
const rifWallet = await createRIFWallet(wallets[0])
const rifWalletIsDeployed =
await rifWallet.smartWalletFactory.isDeployed()

Expand Down
1 change: 1 addition & 0 deletions src/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ export enum SETTINGS {
RIF_WALLET_KEY = 'RIF_WALLET_KEY',
WALLETCONNECT2_PROJECT_ID = 'WALLETCONNECT2_PROJECT_ID',
BTC_EXPLORER_ADDRESS_URL = 'BTC_EXPLORER_ADDRESS_URL',
TERMS_AND_CONDITIONS_URL = 'TERMS_AND_CONDITIONS_URL',
}
44 changes: 39 additions & 5 deletions src/lib/core/KeyManagementSystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,28 +84,45 @@ export class KeyManagementSystem implements IKeyManagementSystem {
/**
* Use this method to recover a stored serialized wallet
* @param serialized the serialized string
* @param chainId
* @returns the KeyManagementSystem that was serialized
*/
static fromSerialized (serialized: string): { kms: KeyManagementSystem, wallets: Wallet[] } {
static fromSerialized (serialized: string, chainId: number): { kms: KeyManagementSystem, wallets: Wallet[] } {
const { mnemonic, state }: KeyManagementSystemSerialization = JSON.parse(serialized)

const kms = new KeyManagementSystem(mnemonic, state)
// If for some reason the chainId that was passed has not been generated, generate and save it
if (!state.lastDerivedAccountIndex[chainId]) {
const newChain = kms.getWalletByChainIdAccountIndex(chainId, 0)
newChain.save()
}
// @TODO Save this state using saveKeys() function
// This is for incremental rollout, we should add both chains when an user creates a wallet

// Now, get the derivation path and use that one to return the wallet
const derivationPath = getDPathByChainId(chainId, 0)
// try to create the wallet using the private key which is faster, if it fails, the fallback
// is to use the derivedPath and mnemonic to regenerate the private key and then wallet
const wallets = Object.keys(state.derivedPaths)
let wallet
try {
wallet = new Wallet(state.derivedPaths[derivationPath])
} catch (_error) {
const derivedWalletContainer = kms.deriveWallet(derivationPath)
wallet = derivedWalletContainer.wallet
}
// Old logic, should be analyzed to see if it can be removed or the app modified
/*const wallets = Object.keys(state.derivedPaths)
.map((derivedPath: string) => {
try {
return new Wallet(state.derivedPaths[derivedPath])
} catch (_error) {
const { wallet } = kms.deriveWallet(derivedPath)
return wallet
}
})

})*/
return {
kms,
wallets
wallets: [wallet]
}
}

Expand Down Expand Up @@ -160,6 +177,23 @@ export class KeyManagementSystem implements IKeyManagementSystem {
}
}

/**
* This will get the wallet according to the chain id and accountIndex passed to the function
* @param chainId
* @param accountIndex
*/
getWalletByChainIdAccountIndex(chainId: number, accountIndex: number): SaveableWallet {
const derivationPath = getDPathByChainId(chainId, accountIndex)
const { wallet, privateKey } = this.deriveWallet(derivationPath)
return {
derivationPath,
wallet,
save: () => {
this.state.derivedPaths[derivationPath] = privateKey
}
}
}

/**
* Get the account for an arbitrary derivation path
* @param derivationPath an arbitrary derivation path
Expand Down
1 change: 1 addition & 0 deletions src/lib/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,7 @@ const resources = {
'We strongly advise exercising caution, employing the best security practices,and safeguarding your assets diligently."',
security_i_agree: 'I agree with the conditions. ',
security_info_btn: 'Continue',
security_terms_and_conditions: 'Terms and Conditions',
android_qr_alert_title: 'Error reading QR',
android_qr_alert_desc: 'The QR could not be parsed. Please try again.',
android_qr_loading_camera: 'Loading camera',
Expand Down
67 changes: 32 additions & 35 deletions src/redux/rootReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { persistReducer, createMigrate, PersistConfig } from 'redux-persist'
import { reduxStorage } from 'storage/ReduxStorage'
import { contactsReducer } from 'store/slices/contactsSlice'
import { ProfileStatus } from 'navigation/profileNavigator/types'
import { getCurrentChainId } from 'storage/ChainStorage'

import { accountsReducer } from './slices/accountsSlice'
import { balancesReducer } from './slices/balancesSlice'
Expand All @@ -28,41 +29,37 @@ const migrations = {
}),
}

const settingsPersistConfig: PersistConfig<SettingsSlice> = {
key: 'settings',
whitelist: [
'pin',
'chainId',
'keysExist',
'isFirstLaunch',
'usedBitcoinAddresses',
],
storage: reduxStorage,
}
export const createRootReducer = () => {
const settingsPersistConfig: PersistConfig<SettingsSlice> = {
key: 'settings',
whitelist: ['pin', 'keysExist', 'isFirstLaunch', 'usedBitcoinAddresses'],
storage: reduxStorage(getCurrentChainId()),
}

const rootPersistConfig = {
key: 'root',
storage: reduxStorage,
version: 0,
migrate: createMigrate(migrations),
whitelist: [
'profile',
'accounts',
'contacts',
'balances',
'usdPrices',
'transactions',
],
}
const rootPersistConfig = {
key: 'root',
version: 0,
migrate: createMigrate(migrations),
whitelist: [
'profile',
'accounts',
'contacts',
'balances',
'usdPrices',
'transactions',
],
storage: reduxStorage(getCurrentChainId()),
}

const reducers = combineReducers({
usdPrices: usdPriceReducer,
balances: balancesReducer,
transactions: transactionsReducer,
settings: persistReducer(settingsPersistConfig, settingsSliceReducer),
profile: profileReducer,
accounts: accountsReducer,
contacts: contactsReducer,
})
const reducers = combineReducers({
usdPrices: usdPriceReducer,
balances: balancesReducer,
transactions: transactionsReducer,
settings: persistReducer(settingsPersistConfig, settingsSliceReducer),
profile: profileReducer,
accounts: accountsReducer,
contacts: contactsReducer,
})

export const rootReducer = persistReducer(rootPersistConfig, reducers)
return persistReducer(rootPersistConfig, reducers)
}
21 changes: 16 additions & 5 deletions src/redux/slices/settingsSlice/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,12 @@ import {
SocketsEvents,
socketsEvents,
} from 'src/subscriptions/rifSockets'
import { ChainTypesByIdType } from 'shared/constants/chainConstants'
import {
chainTypesById,
ChainTypesByIdType,
} from 'shared/constants/chainConstants'
import { getCurrentChainId } from 'storage/ChainStorage'
import { resetReduxStorage } from 'storage/ReduxStorage'

import {
Bitcoin,
Expand Down Expand Up @@ -195,8 +200,7 @@ export const unlockApp = createAsyncThunk<
request => thunkAPI.dispatch(onRequest({ request })),
chainId,
),
)(serializedKeys)

)(serializedKeys, chainId)
if (!existingWallet) {
return thunkAPI.rejectWithValue('No Existing Wallet')
}
Expand Down Expand Up @@ -268,6 +272,7 @@ export const resetApp = createAsyncThunk(
thunkAPI.dispatch(setPinState(null))
thunkAPI.dispatch(setKeysExist(false))
resetMainStorage()
resetReduxStorage()
return 'deleted'
} catch (err) {
return thunkAPI.rejectWithValue(err)
Expand Down Expand Up @@ -330,9 +335,15 @@ const initialState: SettingsSlice = {
usedBitcoinAddresses: {},
}

const createInitialState = () => ({
...initialState,
chainId: getCurrentChainId(),
chainType: chainTypesById[getCurrentChainId()],
})

const settingsSlice = createSlice({
name: 'settings',
initialState,
initialState: createInitialState,
reducers: {
setKeysExist: (state, { payload }: PayloadAction<boolean>) => {
state.keysExist = payload
Expand Down Expand Up @@ -431,7 +442,7 @@ const settingsSlice = createSlice({
deleteKeys()
deleteDomains()
deleteCache()
return initialState
return createInitialState()
},
setFullscreen: (state, { payload }: PayloadAction<boolean>) => {
state.fullscreen = payload
Expand Down
14 changes: 10 additions & 4 deletions src/redux/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,13 @@ import {
// REGISTER,
} from 'redux-persist'

import { rootReducer } from './rootReducer'
import { createRootReducer } from './rootReducer'

// Must use redux-debugger plugin in flipper for the redux debugger to work

export const createStore = (preloadedState = {}) =>
configureStore({
reducer: rootReducer,
reducer: createRootReducer(),
preloadedState,
middleware: getDefaultMiddlewares => {
const middlewares = getDefaultMiddlewares({
Expand All @@ -31,8 +31,14 @@ export const createStore = (preloadedState = {}) =>

export const store = createStore()

export const persistor = persistStore(store)

export const createNewStore = () => {
const newStore = createStore()
const newPersistor = persistStore(newStore)
return {
store: newStore,
persistor: newPersistor,
}
}
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>
// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
Expand Down
Loading

0 comments on commit 71f1fd1

Please sign in to comment.