Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle auth and server error during swap #593

Merged
merged 7 commits into from
Dec 1, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/pages/restart/LightModeRestart.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { BeeModes } from '@ethersphere/bee-js'
import { Box, Grid, Typography } from '@material-ui/core'
import { useSnackbar } from 'notistack'
import { ReactElement, useContext, useEffect, useState } from 'react'
import { useNavigate } from 'react-router'
import { Waiting } from '../../components/Waiting'
Expand All @@ -12,6 +13,7 @@ export default function LightModeRestart(): ReactElement {
const [startedAt] = useState(Number.parseInt(localStorage.getItem(STARTED_UPGRADE_AT) ?? Date.now().toFixed()))
const { apiHealth, nodeInfo } = useContext(Context)
const navigate = useNavigate()
const { enqueueSnackbar } = useSnackbar()

useEffect(() => {
localStorage.setItem(STARTED_UPGRADE_AT, startedAt.toFixed())
Expand All @@ -23,10 +25,11 @@ export default function LightModeRestart(): ReactElement {
}

if (apiHealth && nodeInfo?.beeMode === BeeModes.LIGHT) {
enqueueSnackbar('Upgraded to light node', { variant: 'success' })
localStorage.removeItem(STARTED_UPGRADE_AT)
navigate(ROUTES.INFO)
}
}, [startedAt, navigate, nodeInfo, apiHealth])
}, [startedAt, navigate, nodeInfo, apiHealth, enqueueSnackbar])

return (
<Grid container direction="column" justifyContent="center" alignItems="center">
Expand Down
7 changes: 3 additions & 4 deletions src/pages/top-up/GiftCardFund.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { BeeModes } from '@ethersphere/bee-js'
import { Box, Typography } from '@material-ui/core'
import { useSnackbar } from 'notistack'
import { ReactElement, useContext, useEffect, useState } from 'react'
import Check from 'remixicon-react/CheckLineIcon'
import ArrowDown from 'remixicon-react/ArrowDownLineIcon'
import { useNavigate, useParams } from 'react-router'
import ArrowDown from 'remixicon-react/ArrowDownLineIcon'
import Check from 'remixicon-react/CheckLineIcon'
import ExpandableListItem from '../../components/ExpandableListItem'
import ExpandableListItemKey from '../../components/ExpandableListItemKey'
import { HistoryHeader } from '../../components/HistoryHeader'
Expand All @@ -18,7 +19,6 @@ import { ROUTES } from '../../routes'
import { sleepMs } from '../../utils'
import { restartBeeNode, upgradeToLightNode } from '../../utils/desktop'
import { ResolvedWallet } from '../../utils/wallet'
import { BeeModes } from '@ethersphere/bee-js'

export function GiftCardFund(): ReactElement {
const { nodeAddresses, nodeInfo } = useContext(BeeContext)
Expand Down Expand Up @@ -52,7 +52,6 @@ export function GiftCardFund(): ReactElement {
await sleepMs(5_000)
await upgradeToLightNode(desktopUrl, rpcProviderUrl)
await restartBeeNode(desktopUrl)
enqueueSnackbar('Upgraded to light node', { variant: 'success' })
navigate(ROUTES.RESTART_LIGHT)
} catch (error) {
console.error(error) // eslint-disable-line
Expand Down
29 changes: 24 additions & 5 deletions src/pages/top-up/Swap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,31 +126,50 @@ export function Swap({ header }: Props): ReactElement {
async function restart() {
try {
await sleepMs(5_000)
await upgradeToLightNode(desktopUrl, rpcProviderUrl)
await restartBeeNode(desktopUrl)

enqueueSnackbar('Upgraded to light node', { variant: 'success' })
navigate(ROUTES.RESTART_LIGHT)
} catch (error) {
console.error(error) // eslint-disable-line
enqueueSnackbar(`Failed to upgrade: ${error}`, { variant: 'error' })
}
}

async function sendSwapRequest(daiToSwap: DaiToken) {
try {
await performSwap(desktopUrl, daiToSwap.toString)
} catch (error) {
// eslint-disable-next-line no-console
console.error(error)
throw error
}
}

async function performSwapWithChecks(daiToSwap: DaiToken) {
const desktopConfiguration = await wrapWithSwapError(
if (!localStorage.getItem('apiKey')) {
throw new SwapError('API key is not set, reopen dashboard through the desktop app')
}

let desktopConfiguration = await wrapWithSwapError(
getDesktopConfiguration(desktopUrl),
'Unable to reach Desktop API. Is Swarm Desktop running?',
'Unable to reach Desktop API - Swarm Desktop may not be running or API key is wrong',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should be able to distinguish if the API key is wrong or Swarm Desktop server is not running, no?

)

if (canUpgradeToLightNode) {
desktopConfiguration = await wrapWithSwapError(
upgradeToLightNode(desktopUrl, rpcProviderUrl),
'Failed to update the configuration file with the new swap values using the Desktop API',
)
}

if (!desktopConfiguration['swap-endpoint']) {
throw new SwapError('Swap endpoint is not configured in Swarm Desktop')
}
await wrapWithSwapError(
Rpc.getNetworkChainId(desktopConfiguration['swap-endpoint']),
`Swap endpoint not reachable at ${desktopConfiguration['swap-endpoint']}`,
)
await wrapWithSwapError(performSwap(desktopUrl, daiToSwap.toString), GENERIC_SWAP_FAILED_ERROR_MESSAGE)
await wrapWithSwapError(sendSwapRequest(daiToSwap), GENERIC_SWAP_FAILED_ERROR_MESSAGE)
}

async function onSwap() {
Expand Down
17 changes: 8 additions & 9 deletions src/pages/top-up/index.tsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
import { BeeModes } from '@ethersphere/bee-js'
import { Box, createStyles, Grid, makeStyles, Typography } from '@material-ui/core'
import { useSnackbar } from 'notistack'
import { ReactElement, useContext, useState } from 'react'
import { useNavigate } from 'react-router'
import BankCard from 'remixicon-react/BankCard2LineIcon'
import Check from 'remixicon-react/CheckLineIcon'
import Download from 'remixicon-react/DownloadLineIcon'
import BankCard from 'remixicon-react/BankCard2LineIcon'
import MoneyDollarCircle from 'remixicon-react/MoneyDollarCircleLineIcon'
import Gift from 'remixicon-react/GiftLineIcon'
import { useNavigate } from 'react-router'
import MoneyDollarCircle from 'remixicon-react/MoneyDollarCircleLineIcon'
import ExpandableListItemActions from '../../components/ExpandableListItemActions'
import { HistoryHeader } from '../../components/HistoryHeader'
import { Loading } from '../../components/Loading'
import { SwarmButton } from '../../components/SwarmButton'
import { ROUTES } from '../../routes'
import TroubleshootConnectionCard from '../../components/TroubleshootConnectionCard'
import { CheckState, Context as BeeContext } from '../../providers/Bee'
import { Context as SettingsContext } from '../../providers/Settings'
import { Context as BalanceProvider } from '../../providers/WalletBalance'
import { BeeModes } from '@ethersphere/bee-js'
import { ROUTES } from '../../routes'
import { restartBeeNode, upgradeToLightNode } from '../../utils/desktop'
import { Loading } from '../../components/Loading'
import { useSnackbar } from 'notistack'
import TroubleshootConnectionCard from '../../components/TroubleshootConnectionCard'

const useStyles = makeStyles(() =>
createStyles({
Expand Down Expand Up @@ -57,7 +57,6 @@ export default function TopUp(): ReactElement {
try {
await upgradeToLightNode(desktopUrl, rpcProviderUrl)
await restartBeeNode(desktopUrl)
enqueueSnackbar('Upgraded to light node', { variant: 'success' })
navigate(ROUTES.RESTART_LIGHT)
} catch (error) {
console.error(error) // eslint-disable-line
Expand Down
8 changes: 4 additions & 4 deletions src/utils/desktop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ export async function getBzzPriceAsDai(desktopUrl: string): Promise<Token> {
return DaiToken.fromDecimal(response.data)
}

export async function upgradeToLightNode(desktopUrl: string, rpcProvider: string): Promise<void> {
await updateDesktopConfiguration(desktopUrl, {
export function upgradeToLightNode(desktopUrl: string, rpcProvider: string): Promise<BeeConfig> {
return updateDesktopConfiguration(desktopUrl, {
'swap-enable': true,
'swap-endpoint': rpcProvider,
})
Expand All @@ -43,8 +43,8 @@ export function getDesktopConfiguration(desktopUrl: string): Promise<BeeConfig>
return getJson(`${desktopUrl}/config`)
}

async function updateDesktopConfiguration(desktopUrl: string, values: Record<string, unknown>): Promise<void> {
await postJson(`${desktopUrl}/config`, values)
function updateDesktopConfiguration(desktopUrl: string, values: Record<string, unknown>): Promise<BeeConfig> {
return postJson(`${desktopUrl}/config`, values)
}

export async function restartBeeNode(desktopUrl: string): Promise<void> {
Expand Down
8 changes: 7 additions & 1 deletion src/utils/net.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export function getJson<T extends Record<string, any>>(url: string): Promise<T>
return sendRequest(url, 'GET') as Promise<T>
}

export function postJson<T extends Record<string, any>>(url: string, data?: T): Promise<T> {
export function postJson<T extends Record<string, any>>(url: string, data?: Record<string, any>): Promise<T> {
return sendRequest(url, 'POST', data) as Promise<T>
}

Expand All @@ -27,6 +27,12 @@ export async function sendRequest(
method,
headers,
data,
}).catch(error => {
if (error?.response?.data) {
throw Error(JSON.stringify(error.response.data))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would provide a bit nicer Error 😅 At least format it like suggested. Maybe include path of the request as well?

Suggested change
throw Error(JSON.stringify(error.response.data))
throw Error(`Request failed! Response: ${JSON.stringify(error.response.data)}`)

} else {
throw error
}
})

return response.data
Expand Down