Skip to content

Commit

Permalink
refactor: commitment logic of RnsProcessor
Browse files Browse the repository at this point in the history
  • Loading branch information
TravellerOnTheRun committed Feb 6, 2024
1 parent 5ec2145 commit 938fc41
Show file tree
Hide file tree
Showing 9 changed files with 92 additions and 111 deletions.
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Dispatch, SetStateAction } from 'react'
import { Dispatch, SetStateAction, useCallback } from 'react'
import { FC, ReactNode, createContext, useState, useContext } from 'react'

import GlobalErrorHandlerView from './GlobalErrorHandlerView'
Expand Down Expand Up @@ -26,10 +26,11 @@ const GlobalErrorHandlerProvider: React.FC<GlobalErrorHandlerProviderType> = ({
}) => {
const [globalError, setGlobalError] = useState<string | null>(null)
const [compKey, setCompKey] = useState(0)
const handleReload = () => {

const handleReload = useCallback(() => {
setGlobalError(null)
setCompKey(curKey => curKey + 1)
}
}, [])

return (
<GlobalErrorHandlerContext.Provider
Expand Down
4 changes: 2 additions & 2 deletions src/lib/rns/RnsProcessor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,7 @@ export class RnsProcessor {
// This to avoid request load
if (
this.index[domain]?.commitmentConfirmed ||
(!isWaitingForCommitmentTransaction &&
this.isDomainAllowedToPingRskRegistrarCanReveal(domain))
!isWaitingForCommitmentTransaction
) {
const canReveal = await this.rskRegistrar.canReveal(
this.index[domain].hash,
Expand All @@ -172,6 +171,7 @@ export class RnsProcessor {
throw new Error((err as Error).message)
}
}

public price = async (domain: string) => {
if (this.index[domain]) {
const alias = this.index[domain]?.domain
Expand Down
92 changes: 41 additions & 51 deletions src/redux/slices/profileSlice/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'

import { DomainRegistrationEnum, RnsProcessor } from 'lib/rns'
import { DomainRegistrationEnum } from 'lib/rns'

import { ProfileStatus } from 'navigation/profileNavigator/types'
import { Wallet } from 'shared/wallet'
import { AppDispatch } from 'store/store'
import { AppDispatch, AsyncThunkWithTypes } from 'store/store'
import {
OnSetTransactionStatusChange,
TransactionStatus,
} from 'store/shared/types'
import { abiEnhancer } from 'core/setup'
import { handleTransactionStatusChange } from 'store/shared/utils'
import { delay } from 'shared/utils'

import {
CommitmentRnsProcess,
DeleteRnsProcess,
ProfileStore,
PurchaseUsername,
Expand All @@ -39,14 +41,20 @@ export const handleDomainTransactionStatusChange =
handleTransactionStatusChange(dispatch)(txTransformed)
}

export const requestUsername = createAsyncThunk(
export const requestUsername = createAsyncThunk<
unknown,
RequestUsername,
AsyncThunkWithTypes
>(
'profile/requestUsername',
async ({ alias, duration, getRnsProcessor }: RequestUsername, thunkAPI) => {
async ({ alias, duration, getRnsProcessor }, thunkAPI) => {
try {
const rnsProcessor = getRnsProcessor()

if (!rnsProcessor) {
return thunkAPI.rejectWithValue('No RNS Processor created')
}

thunkAPI.dispatch(setAlias(`${alias}.rsk`))
thunkAPI.dispatch(setDuration(duration))

Expand All @@ -61,12 +69,9 @@ export const requestUsername = createAsyncThunk(
indexStatus = rnsProcessor.getStatus(alias)

if (indexStatus.commitmentRequested) {
return await commitment(
rnsProcessor,
alias,
IntervalProcessOrigin.RNS_ORIGINAL_TRANSACTION,
)
return await thunkAPI.dispatch(commitment({ alias, getRnsProcessor }))
}

return null
} catch (err) {
return thunkAPI.rejectWithValue(err)
Expand Down Expand Up @@ -112,6 +117,33 @@ export const deleteRnsProcess = createAsyncThunk(
},
)

export const commitment = createAsyncThunk<
DomainRegistrationEnum.COMMITMENT_READY,
CommitmentRnsProcess,
AsyncThunkWithTypes
>('profile/commitment', async ({ alias, getRnsProcessor }, thunkAPI) => {
try {
const rnsProcessor = getRnsProcessor()

if (!rnsProcessor) {
return thunkAPI.rejectWithValue('No RNS Processor created')
}

let response = await rnsProcessor.canReveal(alias)

while (response !== DomainRegistrationEnum.COMMITMENT_READY) {
await delay(3000)
response = await rnsProcessor.canReveal(alias)
}

thunkAPI.dispatch(setStatus(ProfileStatus.READY_TO_PURCHASE))

return DomainRegistrationEnum.COMMITMENT_READY
} catch (err) {
return thunkAPI.dispatch(err)
}
})

const initialState: ProfileStore = {
alias: '',
phone: '',
Expand Down Expand Up @@ -166,48 +198,6 @@ const profileSlice = createSlice({
},
})

export enum IntervalProcessOrigin {
NONE = 'NONE',
RNS_ORIGINAL_TRANSACTION = 'RNS_ORIGINAL_TRANSACTION',
PROFILE_CREATE_EFFECT = 'PROFILE_CREATE_EFFECT',
}
const commitmentIntervalProcess: {
interval?: ReturnType<typeof setInterval>
intervalOrigin: IntervalProcessOrigin
} = {
intervalOrigin: IntervalProcessOrigin.NONE,
}

export const commitment = (
rnsProcessor: RnsProcessor,
alias: string,
intervalProcessOrigin: IntervalProcessOrigin,
): Promise<ProfileStatus> => {
return new Promise((resolve, reject) => {
if (commitmentIntervalProcess.interval) {
reject('Interval is already running.')
}
commitmentIntervalProcess.intervalOrigin = intervalProcessOrigin
commitmentIntervalProcess.interval = setInterval(() => {
rnsProcessor
.canReveal(
alias,
intervalProcessOrigin ===
IntervalProcessOrigin.RNS_ORIGINAL_TRANSACTION,
)
.then(canRevealResponse => {
if (canRevealResponse === DomainRegistrationEnum.COMMITMENT_READY) {
clearInterval(commitmentIntervalProcess.interval)
commitmentIntervalProcess.interval = undefined
commitmentIntervalProcess.intervalOrigin =
IntervalProcessOrigin.NONE
resolve(ProfileStatus.READY_TO_PURCHASE)
}
})
}, 1000)
})
}

export const {
setProfile,
setStatus,
Expand Down
5 changes: 5 additions & 0 deletions src/redux/slices/profileSlice/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,8 @@ export interface DeleteRnsProcess {
getRnsProcessor: GetRnsProcessor
domain: string
}

export interface CommitmentRnsProcess {
getRnsProcessor: GetRnsProcessor
alias: string
}
60 changes: 22 additions & 38 deletions src/screens/profile/ProfileCreateScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import Clipboard from '@react-native-community/clipboard'
import Icon from 'react-native-vector-icons/FontAwesome'
import MaterialIcon from 'react-native-vector-icons/MaterialIcons'

import { RnsProcessor } from 'lib/rns'

import {
BarButtonGroupContainer,
BarButtonGroupIcon,
Expand All @@ -33,20 +31,14 @@ import {
} from 'shared/constants'
import { sharedStyles } from 'shared/styles'
import { castStyle } from 'shared/utils'
import {
commitment,
IntervalProcessOrigin,
setProfile,
setStatus,
} from 'store/slices/profileSlice'
import { commitment, setProfile, setStatus } from 'store/slices/profileSlice'
import { selectProfile } from 'store/slices/profileSlice/selector'
import { selectChainId, selectRequests } from 'store/slices/settingsSlice'
import { useAppDispatch, useAppSelector } from 'store/storeUtils'
import { AppSpinner } from 'components/index'
import { AvatarIcon } from 'components/icons/AvatarIcon'
import { rootTabsRouteNames } from 'navigation/rootNavigator'
import { RNS_ADDRESSES_BY_CHAIN_ID } from 'screens/rnsManager/types'
import { useWallet } from 'shared/wallet'
import { useGetRnsProcessor, useWallet } from 'shared/wallet'
import { useAddress } from 'shared/hooks'

import { rnsManagerStyles } from '../rnsManager/rnsManagerStyles'
Expand All @@ -56,6 +48,7 @@ export const ProfileCreateScreen = ({
}: ProfileStackScreenProps<profileStackRouteNames.ProfileCreateScreen>) => {
const wallet = useWallet()
const address = useAddress(wallet)
const getRnsProcessor = useGetRnsProcessor()

const dispatch = useAppDispatch()
const profile = useAppSelector(selectProfile)
Expand Down Expand Up @@ -137,36 +130,27 @@ export const ProfileCreateScreen = ({
}, [navigation])

useEffect(() => {
if (
wallet &&
profile.alias &&
profile.status === ProfileStatus.REQUESTING
) {
const rns = new RnsProcessor({
wallet,
address,
rnsAddresses: RNS_ADDRESSES_BY_CHAIN_ID[chainId],
})
commitment(
rns,
profile.alias.split('.rsk')[0],
IntervalProcessOrigin.PROFILE_CREATE_EFFECT,
)
.then(profileStatus => dispatch(setStatus(profileStatus)))
.catch(error => {
console.log(error)
})
}
if (requests.length === 0) {
if (profile.status === ProfileStatus.WAITING_FOR_USER_COMMIT) {
// User got stuck in requesting the commit - set profileStatus back to 0
dispatch(setStatus(ProfileStatus.NONE))
(async () => {

Check failure on line 133 in src/screens/profile/ProfileCreateScreen.tsx

View workflow job for this annotation

GitHub Actions / test

Insert `;`
if (profile.alias && profile.status === ProfileStatus.REQUESTING) {
await dispatch(
commitment({
alias: profile.alias.split('.rsk')[0],
getRnsProcessor,
}),
).unwrap()
}
if (profile.status === ProfileStatus.PURCHASING) {
// User got stuck in requesting the purchase - set profileStatus back to 3
dispatch(setStatus(ProfileStatus.READY_TO_PURCHASE))

if (requests.length === 0) {
if (profile.status === ProfileStatus.WAITING_FOR_USER_COMMIT) {
// User got stuck in requesting the commit - set profileStatus back to 0
dispatch(setStatus(ProfileStatus.NONE))
}
if (profile.status === ProfileStatus.PURCHASING) {
// User got stuck in requesting the purchase - set profileStatus back to 3
dispatch(setStatus(ProfileStatus.READY_TO_PURCHASE))
}
}
}
})()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

Expand Down
14 changes: 6 additions & 8 deletions src/screens/rnsManager/DomainInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { StyleSheet, Text } from 'react-native'
import { FieldError } from 'react-hook-form'
import { RSKRegistrar } from '@rsksmart/rns-sdk'

import {
AddressValidationMessage,
Expand All @@ -20,8 +21,7 @@ interface Props {
inputName: string
domainValue: string
error: FieldError | undefined
searchAvailability: (domain: string) => Promise<string>
searchOwnerOf: (domain: string) => Promise<string>
rskRegistrar: RSKRegistrar
onDomainAvailable: (domain: string, valid: boolean) => void
onDomainOwned: (owned: boolean) => void
onResetValue: () => void
Expand All @@ -47,8 +47,7 @@ export const DomainInput = ({
address,
inputName,
domainValue,
searchAvailability,
searchOwnerOf,
rskRegistrar,
onDomainAvailable,
onDomainOwned,
onResetValue,
Expand All @@ -70,10 +69,10 @@ export const DomainInput = ({
setDomainAvailability(DomainStatus.NONE)
onDomainAvailable(domain, false)
} else {
const available = await searchAvailability(domain)
const available = await rskRegistrar.available(domain)

if (!available) {
const ownerAddress = await searchOwnerOf(domain)
const ownerAddress = await rskRegistrar.ownerOf(domain)

if (address === ownerAddress) {
setDomainAvailability(DomainStatus.OWNED)
Expand All @@ -92,8 +91,7 @@ export const DomainInput = ({
errorType,
errorMessage,
onDomainAvailable,
searchOwnerOf,
searchAvailability,
rskRegistrar,
address,
onDomainOwned,
],
Expand Down
3 changes: 1 addition & 2 deletions src/screens/rnsManager/SearchDomainScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -222,8 +222,7 @@ export const SearchDomainScreen = ({ navigation }: Props) => {
{rnsProcessor ? (
<DomainInput
address={address}
searchAvailability={rnsProcessor.rskRegistrar.available}
searchOwnerOf={rnsProcessor.rskRegistrar.ownerOf}
rskRegistrar={rnsProcessor.rskRegistrar}
inputName={'domain'}
error={errors.domain}
domainValue={domain}
Expand Down
5 changes: 3 additions & 2 deletions src/screens/settings/SettingsScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,12 @@ export const SettingsScreen = ({
const { t } = useTranslation()

const { handleReload } = useContext(GlobalErrorHandlerContext)
const onSwitchChains = () => {

const onSwitchChains = useCallback(() => {
const currentChainId = getCurrentChainId()
setCurrentChainId(currentChainId === 31 ? 30 : 31)
handleReload()
}
}, [handleReload])
return (
<ScrollView style={styles.container}>
<View style={styles.mainView}>
Expand Down
Loading

0 comments on commit 938fc41

Please sign in to comment.