Skip to content

Commit

Permalink
US-1574 Mainnet!!! (#740)
Browse files Browse the repository at this point in the history
* US-1574 Mainnet!!!

* Will now have mainnet wallet

* Fixed config.json

* Creted inversed object map

* Updated rif relay version

* Removed chainId from Redux Persist

* Linted

* Updated rif-relay sdk to version 11
  • Loading branch information
Freshenext authored Sep 27, 2023
1 parent 33fec1c commit 7843a37
Show file tree
Hide file tree
Showing 14 changed files with 208 additions and 77 deletions.
2 changes: 1 addition & 1 deletion config.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"SMART_WALLET_FACTORY_ADDRESS_TESTNET":"0xBaDb31cAf5B95edd785446B76219b60fB1f07233",
"RELAY_VERIFIER_ADDRESS_MAINNET":"0x5C9c7d96E6C59E55dA4dCf7F791AE58dAF8DBc86",
"RELAY_VERIFIER_ADDRESS_TESTNET":"0x5897E84216220663F306676458Afc7bf2A6A3C52",
"DEPLOY_VERIFIER_ADDRESS_MAINET":"0x2fd633e358bc50ccf6bf926d621e8612b55264c9",
"DEPLOY_VERIFIER_ADDRESS_MAINNET":"0x2fd633e358bc50ccf6bf926d621e8612b55264c9",
"DEPLOY_VERIFIER_ADDRESS_TESTNET":"0xAe59e767768c6c25d64619Ee1c498Fd7D83e3c24",
"BTC_EXPLORER_ADDRESS_URL_MAINNET":"https://explorer.btc.com/btc/transaction",
"BTC_EXPLORER_ADDRESS_URL_TESTNET":"https://live.blockcypher.com/btc-testnet",
Expand Down
5 changes: 3 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.3",
"@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 @@ -141,7 +141,8 @@
"wait-for-expect": "^3.0.2"
},
"resolutions": {
"@types/react": "^17"
"@types/react": "^17",
"@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>
)
}
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
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
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)
}
15 changes: 11 additions & 4 deletions src/redux/slices/settingsSlice/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ 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 {
Bitcoin,
Expand Down Expand Up @@ -195,8 +199,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 @@ -332,7 +335,11 @@ const initialState: SettingsSlice = {

const settingsSlice = createSlice({
name: 'settings',
initialState,
initialState: () => ({
...initialState,
chainId: getCurrentChainId(),
chainType: chainTypesById[getCurrentChainId()],
}),
reducers: {
setKeysExist: (state, { payload }: PayloadAction<boolean>) => {
state.keysExist = 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
28 changes: 26 additions & 2 deletions src/screens/settings/SettingsScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { version } from 'package.json'
import { useCallback, useEffect, useMemo } from 'react'
import { useCallback, useContext, useEffect, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { Platform, ScrollView, StyleSheet, View } from 'react-native'

Expand All @@ -15,17 +15,26 @@ import { sharedColors, sharedStyles } from 'shared/constants'
import { castStyle } from 'shared/utils'
import {
selectChainId,
selectChainType,
selectPin,
selectWalletIsDeployed,
} from 'store/slices/settingsSlice'
import { useAppSelector } from 'store/storeUtils'
import { chainTypesById } from 'shared/constants/chainConstants'
import { ChainTypeEnum, chainTypesById } from 'shared/constants/chainConstants'
import { GlobalErrorHandlerContext } from 'components/GlobalErrorHandler/GlobalErrorHandlerContext'
import { getCurrentChainId, setCurrentChainId } from 'storage/ChainStorage'

const ChainTypesInversed = {
[ChainTypeEnum.TESTNET]: ChainTypeEnum.MAINNET,
[ChainTypeEnum.MAINNET]: ChainTypeEnum.TESTNET,
}

export const SettingsScreen = ({
navigation,
}: SettingsScreenProps<settingsStackRouteNames.SettingsScreen>) => {
const statePIN = useAppSelector(selectPin)
const chainId = useAppSelector(selectChainId)
const chainType = useAppSelector(selectChainType)
const walletIsDeployed = useAppSelector(selectWalletIsDeployed)

const smartWalletFactoryAddress = useMemo(
Expand Down Expand Up @@ -78,6 +87,12 @@ export const SettingsScreen = ({
}, [navigation])
const { t } = useTranslation()

const { handleReload } = useContext(GlobalErrorHandlerContext)
const onSwitchChains = () => {
const currentChainId = getCurrentChainId()
setCurrentChainId(currentChainId === 31 ? 30 : 31)
handleReload()
}
return (
<ScrollView style={styles.container}>
<View style={styles.mainView}>
Expand Down Expand Up @@ -129,6 +144,15 @@ export const SettingsScreen = ({
</AppTouchable>
)}
</View>
<AppTouchable
width={'100%'}
accessibilityLabel="Wallet Backup"
style={styles.settingsItem}
onPress={onSwitchChains}>
<Typography type={'h3'}>
Switch to {ChainTypesInversed[chainType]}
</Typography>
</AppTouchable>
<View style={styles.bottomView}>
<AppTouchable
width={'100%'}
Expand Down
9 changes: 9 additions & 0 deletions src/storage/ChainStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { ChainTypesByIdType } from 'shared/constants/chainConstants'

import { MainStorage } from './MainStorage'

export const getCurrentChainId: () => ChainTypesByIdType = () =>
MainStorage.get('chainId') || 31

export const setCurrentChainId = (chainId: ChainTypesByIdType) =>
MainStorage.set('chainId', chainId)
Loading

0 comments on commit 7843a37

Please sign in to comment.