Skip to content

Commit

Permalink
feat: run alias registration in the background #334 (#390)
Browse files Browse the repository at this point in the history
* feat: run alias registration in the background

* fix: add custome hook

* fix: request domain code to the custom hook

* fix: request domain code to the custom hook

* fix: request domain code to the custom hook

* refactor: use new storage

* fix: changes due storage refactor

* fix: typo

* fix: merge

* fix: add missing code

* fix: add missing code

* fix: add missing code
  • Loading branch information
lucachaco authored Dec 16, 2022
1 parent 8315f74 commit 4763fdc
Show file tree
Hide file tree
Showing 8 changed files with 165 additions and 33 deletions.
70 changes: 70 additions & 0 deletions src/core/hooks/useAliasRegistration.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { RSKRegistrar } from '@rsksmart/rns-sdk'

import {
getAliasRegistration,
hasAliasRegistration,
IProfileRegistrationStore,
saveAliasRegistration,
} from 'src/storage/AliasRegistrationStore'
import addresses from '../../screens/rnsManager/addresses.json'
import { RIFWallet } from 'lib/core'

export function useAliasRegistration(wallet: RIFWallet) {
const rskRegistrar = new RSKRegistrar(
addresses.rskOwnerAddress,
addresses.fifsAddrRegistrarAddress,
addresses.rifTokenAddress,
wallet,
)

const registrationStarted = () => {
const hasStartedRegistration = hasAliasRegistration()

if (hasStartedRegistration) {
const myAliasRegistration = getAliasRegistration()
const hash = myAliasRegistration.commitToRegisterHash
return !!hash
} else {
return false
}
}
const readyToRegister = async (_hash?: string) => {
if (registrationStarted()) {
const myAliasRegistration: IProfileRegistrationStore =
getAliasRegistration()
const hash = _hash || myAliasRegistration.commitToRegisterHash
const canReveal = await rskRegistrar.canReveal(hash)
return await canReveal()
} else {
return false
}
}
const getRegistrationData = getAliasRegistration

const setRegistrationData = async (
alias: string,
duration: number,
): Promise<IProfileRegistrationStore> => {
const response = await rskRegistrar.commitToRegister(
alias,
wallet.smartWallet.address,
)

saveAliasRegistration({
alias: alias,
duration: duration,
commitToRegisterSecret: response.secret,
commitToRegisterHash: response.hash,
})
await response.makeCommitmentTransaction.wait()
console.log('commitToRegister succesfull')
return getRegistrationData()
}

return {
registrationStarted,
readyToRegister,
getRegistrationData,
setRegistrationData,
}
}
1 change: 1 addition & 0 deletions src/screens/profile/ProfileCreateScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { useCallback, useState } from 'react'

import MaterialIcon from 'react-native-vector-icons/MaterialIcons'

import {
Expand Down
14 changes: 9 additions & 5 deletions src/screens/rnsManager/AliasBoughtScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useEffect, useState } from 'react'

import { Clipboard, Image, Linking, StyleSheet, View } from 'react-native'
import { rnsManagerStyles } from './rnsManagerStyles'
import { navigationContainerRef } from 'src/core/Core'

import {
rootStackRouteNames,
Expand All @@ -17,7 +18,6 @@ import { useAppDispatch, useAppSelector } from 'store/storeUtils'
import { ScreenWithWallet } from '../types'

export const AliasBoughtScreen = ({
navigation,
route,
}: RootStackScreenProps<'AliasBought'> & ScreenWithWallet) => {
const { alias, tx } = route.params
Expand All @@ -30,7 +30,10 @@ export const AliasBoughtScreen = ({
const dispatch = useAppDispatch()
const profile = useAppSelector(selectProfile)

const explorerUrl = getWalletSetting(SETTINGS.EXPLORER_ADDRESS_URL, chainId)
const explorerUrl = getWalletSetting(
SETTINGS.EXPLORER_ADDRESS_URL,
chainId ?? 31,
)

const copyHashAndOpenExplorer = (hash: string) => {
Clipboard.setString(hash)
Expand All @@ -39,9 +42,8 @@ export const AliasBoughtScreen = ({

useEffect(() => {
if (profile) {
dispatch(setProfile({ ...profile, alias }))
dispatch(setProfile({ ...profile, alias: `${alias}.rsk` }))
}

const fetchData = async () => {
await tx.wait()
setRegisterDomainInfo('Your alias has been registered successfully')
Expand Down Expand Up @@ -81,7 +83,9 @@ export const AliasBoughtScreen = ({
</View>
<SecondaryButton
onPress={() =>
navigation.navigate(rootStackRouteNames.ProfileDetailsScreen)
navigationContainerRef.navigate(
rootStackRouteNames.ProfileDetailsScreen,
)
}
accessibilityLabel="close"
title={'Close'}
Expand Down
3 changes: 2 additions & 1 deletion src/screens/rnsManager/BuyDomainScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import TitleStatus from './TitleStatus'
import { TokenImage } from '../home/TokenImage'
import { AvatarIcon } from '../../components/icons/AvatarIcon'
import { errorHandler } from 'shared/utils'
import { deleteAliasRegistration } from '../../storage/AliasRegistrationStore'

type Props = RootStackScreenProps<rootStackRouteNames.BuyDomain> &
ScreenWithWallet
Expand Down Expand Up @@ -66,7 +67,7 @@ export const BuyDomainScreen = ({ wallet, navigation, route }: Props) => {
durationToRegister,
domainPrice,
)

deleteAliasRegistration()
setRegisterDomainInfo('Transaction sent. Please wait...')
setRegisterInProcess(true)

Expand Down
43 changes: 27 additions & 16 deletions src/screens/rnsManager/RequestDomainScreen.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import { RSKRegistrar } from '@rsksmart/rns-sdk'
import { useEffect, useState } from 'react'
import * as Progress from 'react-native-progress'
import MaterialIcon from 'react-native-vector-icons/MaterialIcons'
Expand All @@ -16,44 +15,58 @@ import {
RootStackScreenProps,
} from 'navigation/rootNavigator/types'
import { ScreenWithWallet } from '../types'
import addresses from './addresses.json'
import TitleStatus from './TitleStatus'
import { IProfileRegistrationStore } from '../../storage/AliasRegistrationStore'
import { useAliasRegistration } from '../../core/hooks/useAliasRegistration'

type Props = RootStackScreenProps<rootStackRouteNames.RequestDomain> &
ScreenWithWallet

export const RequestDomainScreen = ({ wallet, navigation, route }: Props) => {
const {
registrationStarted,
readyToRegister,
getRegistrationData,
setRegistrationData,
} = useAliasRegistration(wallet)
const { alias, duration } = route.params
const fullAlias = alias + '.rsk'

const rskRegistrar = new RSKRegistrar(
addresses.rskOwnerAddress,
addresses.fifsAddrRegistrarAddress,
addresses.rifTokenAddress,
wallet,
)
const [commitToRegisterInfo, setCommitToRegisterInfo] = useState('')
const [commitToRegisterInfo2, setCommitToRegisterInfo2] = useState('')
const [processing, setProcessing] = useState(false)
const [progress, setProgress] = useState(0.0)

const getUpToDateRegistrationData = async () => {
if (await registrationStarted()) {
setCommitToRegisterInfo('loading registration process status')
setProgress(0.3)
return await getRegistrationData()
} else {
setCommitToRegisterInfo('committing to register...')
setProgress(0)
return await setRegistrationData(alias, parseInt(duration, 10))
}
}

const commitToRegister = async () => {
setProcessing(true)
try {
const { makeCommitmentTransaction, secret, canReveal } =
await rskRegistrar.commitToRegister(alias, wallet.smartWallet.address)

const profileRegistrationStore: IProfileRegistrationStore =
await getUpToDateRegistrationData()
setCommitToRegisterInfo('registering your alias...')
setCommitToRegisterInfo2('estimated wait: 3 minutes')

const intervalId = setInterval(async () => {
const ready = await canReveal()
setProgress(prev => prev + 0.009)
const ready = await readyToRegister(
profileRegistrationStore.commitToRegisterHash,
)
if (ready) {
setProgress(1)
setProcessing(false)
navigation.navigate(rootStackRouteNames.BuyDomain, {
alias,
domainSecret: secret,
domainSecret: profileRegistrationStore.commitToRegisterSecret,
duration,
})
setCommitToRegisterInfo(
Expand All @@ -62,8 +75,6 @@ export const RequestDomainScreen = ({ wallet, navigation, route }: Props) => {
clearInterval(intervalId)
}
}, 1000)
await makeCommitmentTransaction.wait()
setCommitToRegisterInfo('Transaction confirmed. Please wait...')
} catch (e: unknown) {
setProcessing(false)
setCommitToRegisterInfo(e?.message || '')
Expand Down
22 changes: 22 additions & 0 deletions src/storage/AliasRegistrationStore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { MainStorage } from './MainStorage'

const key = 'ALIAS_REGISTRATION'
export type IProfileRegistrationStore = {
alias: string
duration: number
commitToRegisterHash: string
commitToRegisterSecret: string
}
export const hasAliasRegistration = () => MainStorage.has(key)

export const getAliasRegistration = () => {
const jsonProfile = MainStorage.has(key) ? MainStorage.get(key) : '{}'
const store: IProfileRegistrationStore = JSON.parse(jsonProfile || '{}')
return store
}

export const deleteAliasRegistration = () => MainStorage.delete(key)

export const saveAliasRegistration = (
aliasRegistration: IProfileRegistrationStore,
) => MainStorage.set(key, JSON.stringify(aliasRegistration))
43 changes: 33 additions & 10 deletions src/ux/appHeader/ProfileHandler.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,45 @@ import { useAppSelector } from 'src/redux/storeUtils'
import { RegularText } from '../../components'
import { AvatarIcon } from '../../components/icons/AvatarIcon'
import { colors } from '../../styles'

export const ProfileHandler = () => {
import { useAliasRegistration } from 'core/hooks/useAliasRegistration'
import { RIFWallet } from 'lib/core'
import React from 'react'
interface Props {
wallet: RIFWallet
}
export const ProfileHandler: React.FC<Props> = ({ wallet }) => {
const profile = useAppSelector(selectProfile)
const profileCreated = !!profile

const { registrationStarted, readyToRegister, getRegistrationData } =
useAliasRegistration(wallet)
const routeNextStep = async () => {
if (await readyToRegister()) {
const myAliasRegistration = await getRegistrationData()
navigationContainerRef.navigate(rootStackRouteNames.BuyDomain, {
alias: myAliasRegistration?.alias,
domainSecret: myAliasRegistration?.commitToRegisterSecret,
duration: myAliasRegistration?.duration,
})
} else if (await registrationStarted()) {
const myAliasRegistration = await getRegistrationData()
navigationContainerRef.navigate(rootStackRouteNames.RequestDomain, {
alias: myAliasRegistration?.alias,
duration: myAliasRegistration?.duration,
})
} else {
navigationContainerRef.navigate(
profileCreated
? rootStackRouteNames.ProfileDetailsScreen
: rootStackRouteNames.ProfileCreateScreen,
)
}
}
return (
<TouchableOpacity
style={styles.profileHandler}
accessibilityLabel="profile"
onPress={() =>
navigationContainerRef.navigate(
profileCreated
? rootStackRouteNames.ProfileDetailsScreen
: rootStackRouteNames.ProfileCreateScreen,
{ editProfile: profileCreated },
)
}>
onPress={routeNextStep}>
{profile?.alias ? (
<>
<AvatarIcon value={profile.alias + '.rsk'} size={30} />
Expand Down
2 changes: 1 addition & 1 deletion src/ux/appHeader/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const AppHeader = () => {
...styles.column,
...styles.walletInfo,
}}>
<ProfileHandler />
{wallet && <ProfileHandler wallet={wallet} />}
</View>
<View style={styles.column}>
{wallet && (
Expand Down

0 comments on commit 4763fdc

Please sign in to comment.