Skip to content
This repository has been archived by the owner on Aug 9, 2022. It is now read-only.

Commit

Permalink
refactor(rns-buy): reduces component complexity
Browse files Browse the repository at this point in the history
  • Loading branch information
itofarina committed Feb 1, 2021
1 parent 2f9f01d commit 2b8e370
Showing 1 changed file with 90 additions and 85 deletions.
175 changes: 90 additions & 85 deletions src/components/pages/rns/buy/DomainOffersCheckoutPage.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import Login from 'components/atoms/Login'
import RifAddress from 'components/molecules/RifAddress'
import CombinedPriceCell from 'components/molecules/CombinedPriceCell'
import CheckoutPageTemplate from 'components/templates/CheckoutPageTemplate'
Expand All @@ -15,8 +14,8 @@ import MarketContext from 'context/Market'
import RnsOffersContext from 'context/Services/rns/OffersContext'
import Logger from 'utils/Logger'
import {
Card, CardActions, CardContent, CardHeader, createStyles, makeStyles, Table, TableBody,
TableCell, TableRow, Theme,
Card, CardActions, CardContent, CardHeader, createStyles, makeStyles, Table,
TableBody, TableCell, TableRow, Theme,
} from '@material-ui/core'
import Typography from '@material-ui/core/Typography'
import {
Expand All @@ -31,6 +30,7 @@ import Web3 from 'web3'
import ProgressOverlay from 'components/templates/ProgressOverlay'
import RoundBtn from 'components/atoms/RoundBtn'
import networkConfig from 'config'
import WithLoginCard from 'components/hoc/WithLoginCard'

const { rnsManagerUrl } = networkConfig

Expand Down Expand Up @@ -119,7 +119,7 @@ const DomainOffersCheckoutPage: FC = () => {

// check funds
useEffect(() => {
if (account && !isFundsConfirmed && order) {
if (!isFundsConfirmed && order) {
const {
item: {
paymentToken: { symbol: tokenSymbol },
Expand Down Expand Up @@ -175,7 +175,6 @@ const DomainOffersCheckoutPage: FC = () => {
}

const { tokenId } = order.item

const {
item: {
ownerAddress,
Expand All @@ -186,80 +185,89 @@ const DomainOffersCheckoutPage: FC = () => {
} = order
const isOwnDomain = account?.toLowerCase() === ownerAddress.toLowerCase()
const currency = crypto[symbol]

const priceCellProps = {
price: price.toString(),
priceFiat: price.mul(currency.rate).toString(),
currency: currency.displayName,
currencyFiat: currentFiat.displayName,
divider: ' ',
}
const PriceCell = <CombinedPriceCell {...priceCellProps} />

const displayName = domainName
? <ShortenTextTooltip value={domainName} maxLength={30} />
: <RifAddress pretext="Unknown RNS:" value={tokenId} />

const details = {
NAME: displayName,
SELLER: <RifAddress value={ownerAddress} />,
'RENEWAL DATE': expirationDate.toLocaleDateString(),
PRICE: PriceCell,
PRICE: (
<CombinedPriceCell
price={price.toString()}
priceFiat={price.mul(currency.rate).toString()}
currency={currency.displayName}
currencyFiat={currentFiat.displayName}
/>
),
}

const handleBuyDomain = async (): Promise<void> => {
if (web3 && account && domainName) {
try {
setProcessingTx(true)

const rnsContract = RNSContract.getInstance(web3, currency.symbol)
// GET PLACEMENT PRICE FROM CONTRACT
const tokenPrice = await rnsContract.getPriceString(tokenId, account)
.catch((error) => {
throw new UIError({
error,
id: 'contract-marketplace-getPlacement',
text: `Could not retrieve placement for ${domainName} from contract.`,
})
})

const transferReceipt = await rnsContract.buy(
marketPlaceAddress, tokenPrice, domainName,
tokenId, { from: account },
).catch((error) => {
try {
setProcessingTx(true)
const rnsContract = RNSContract.getInstance(
web3 as Web3, currency.symbol,
)
// GET PLACEMENT PRICE FROM CONTRACT
const tokenPrice = await rnsContract.getPriceString(tokenId, account)
.catch((error) => {
throw new UIError({
error,
id: 'contract-rns-buy',
text: `Could not buy domain ${domainName} from contract.`,
id: 'contract-marketplace-getPlacement',
text: `Could not retrieve placement for ${domainName} from contract.`,
})
})

logger.info('transferReceipt:', transferReceipt)
const transferReceipt = await rnsContract.buy(
marketPlaceAddress, tokenPrice, domainName as string,
tokenId, { from: account },
).catch((error) => {
throw new UIError({
error,
id: 'contract-rns-buy',
text: `Could not buy domain ${domainName} from contract.`,
})
})

if (transferReceipt) {
setTxOperationDone(true)
confirmationsDispatch({
type: 'NEW_REQUEST',
payload: {
contractAction: 'RNS_BUY',
txHash: transferReceipt.transactionHash,
contractActionData: { tokenId },
},
})
}
} catch (e) {
logger.error(e)
reportError(e)
} finally {
setProcessingTx(false)
logger.info('transferReceipt:', transferReceipt)

if (transferReceipt) {
setTxOperationDone(true)
confirmationsDispatch({
type: 'NEW_REQUEST',
payload: {
contractAction: 'RNS_BUY',
txHash: transferReceipt.transactionHash,
contractActionData: { tokenId },
},
})
}
} catch (e) {
logger.error(e)
reportError(e)
} finally {
setProcessingTx(false)
}
}

const buyingNameTitle = domainName
? shortenString(domainName, 30, 25)
: shortChecksumAddress(tokenId)

const renderNotEnoughFunds = (): JSX.Element | undefined => {
if (isFundsConfirmed && !hasFunds) {
return (
<Typography color="error">
You do not have enough
{' '}
{currency.displayName}
.
</Typography>
)
}
return undefined
}

return (
<CheckoutPageTemplate
className="domains-checkout-page"
Expand Down Expand Up @@ -295,35 +303,26 @@ const DomainOffersCheckoutPage: FC = () => {
</TableBody>
</Table>
</CardContent>
{account && isFundsConfirmed && !hasFunds && (
<Typography color="error">
You do not have enough
{' '}
{currency.displayName}
.
</Typography>
)}
{account
&& (
<CardActions className={classes.footer}>
{isOwnDomain && <p>You cannot purchase your own offer.</p>}
{
!isOwnDomain && hasFunds
&& <p>Your wallet will open and you will be asked to confirm the transaction for buying the domain.</p>
}
<Button
disabled={!hasFunds || isOwnDomain}
color="primary"
variant="contained"
rounded
shadow
onClick={handleBuyDomain}
>
Buy domain
</Button>
</CardActions>
)}
{!account && <Login />}
{
renderNotEnoughFunds()
}
<CardActions className={classes.footer}>
{isOwnDomain && <p>You cannot purchase your own offer.</p>}
{
!isOwnDomain && hasFunds
&& <p>Your wallet will open and you will be asked to confirm the transaction for buying the domain.</p>
}
<Button
disabled={!hasFunds || isOwnDomain}
color="primary"
variant="contained"
rounded
shadow
onClick={handleBuyDomain}
>
Buy domain
</Button>
</CardActions>
</Card>
<ProgressOverlay
title={`Buying the domain ${domainName}!`}
Expand All @@ -332,11 +331,13 @@ const DomainOffersCheckoutPage: FC = () => {
isDone={txOperationDone}
buttons={[
<RoundBtn
key="buy_another"
onClick={(): void => history.push(ROUTES.RNS.BUY.BASE)}
>
Buy another domain
</RoundBtn>,
<RoundBtn
key="go_to_rnsManager"
disabled={!rnsManagerUrl}
onClick={
(): void => {
Expand All @@ -355,4 +356,8 @@ const DomainOffersCheckoutPage: FC = () => {
)
}

export default DomainOffersCheckoutPage
export default WithLoginCard({
WrappedComponent: DomainOffersCheckoutPage,
title: 'Connect your wallet to buy the domain',
contentText: 'Please, connect your wallet in order to buy a new domain.',
})

0 comments on commit 2b8e370

Please sign in to comment.