Skip to content

Commit

Permalink
Merge pull request #493 from hemilabs/minor-improvements-strict-mode-pt2
Browse files Browse the repository at this point in the history
Type improvements for strict mode
  • Loading branch information
gndelia authored Aug 29, 2024
2 parents 18988c0 + 293bb5b commit 207bad1
Show file tree
Hide file tree
Showing 17 changed files with 38 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ export const ConfigurationUrl = function ({

const onClick = function () {
setCopied(true)
window.navigator.clipboard.writeText(href)
window.navigator.clipboard.writeText(href!)
}

return (
Expand All @@ -65,7 +65,11 @@ export const ConfigurationUrl = function ({
}}
trigger={['hover', 'focus']}
>
<button className="flex" onClick={onClick} type="button">
<button
className="flex"
onClick={href ? onClick : undefined}
type="button"
>
<Clipboard />
</button>
</Tooltip>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export const SubmitWhenConnectedToChain = function ({
{!connectedToL1 && (
<div className="flex flex-col gap-y-2">
<Button onClick={() => switchChain({ chainId })} type="button">
{t('common.connect-to-network', { network: targetChain.name })}
{t('common.connect-to-network', { network: targetChain?.name })}
</Button>
</div>
)}
Expand Down
5 changes: 3 additions & 2 deletions webapp/app/[locale]/tunnel/_hooks/useTunnelOperation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const isValidOperation = (value: string): value is Operation =>
validOperations.includes(value as Operation)

export const useTunnelOperation = function (): {
operation: Operation
operation: Operation | undefined
txHash: BtcTxHash | Hash | undefined
updateOperation: (
newOperation: (typeof validOperations)[number],
Expand All @@ -39,7 +39,8 @@ export const useTunnelOperation = function (): {

const isValid = isValidOperation(operation)
const isValidTxHash =
isHash(txHash) || (featureFlags.btcTunnelEnabled && isBtcTxHash(txHash))
!!txHash &&
(isHash(txHash) || (featureFlags.btcTunnelEnabled && isBtcTxHash(txHash)))

useEffect(
function updateDefaultParameters() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ export const Chain = function ({ chainId }: Props) {
return (
<div className="flex items-center gap-x-2">
<ChainLogo chainId={chainId} />
<span className="text-sm font-normal capitalize">{chain.name}</span>
<span className="text-sm font-normal capitalize">
{chain?.name ?? '-'}
</span>
</div>
)
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type Props = {
export const TxLink = function ({ chainId, txHash }: Props) {
const chain = useChain(chainId)
const hash = `${txHash.slice(0, 6)}...${txHash.slice(-4)}`
const href = `${chain.blockExplorers.default.url}/tx/${txHash}`
const href = `${chain?.blockExplorers?.default.url}/tx/${txHash}`
return (
<ExternalLink
className="cursor-pointer text-sm font-normal underline"
Expand Down
6 changes: 4 additions & 2 deletions webapp/components/addNetworkToWallet.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
'use client'

import { useHemi } from 'hooks/useHemi'
import { useIsConnectedToExpectedNetwork } from 'hooks/useIsConnectedToExpectedNetwork'
import { useTranslations } from 'next-intl'
import { useAccount, useWalletClient } from 'wagmi'

export function AddNetworkToWallet() {
const { chain, isConnected } = useAccount()
const { isConnected } = useAccount()
const hemi = useHemi()
const t = useTranslations()
const { data: walletClient, status } = useWalletClient()
const isConnectedToHemi = useIsConnectedToExpectedNetwork(hemi.id)

if (!isConnected || chain.id === hemi.id || status !== 'success') {
if (!isConnected || isConnectedToHemi || status !== 'success') {
return null
}

Expand Down
2 changes: 1 addition & 1 deletion webapp/components/appScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const AppScreen = function ({ children }: AppScreenProps) {

const toggleMenu = () => setIsMenuOpen(!isMenuOpen)

const onNavBarMenuItemClick = function (item: NavItemData) {
const onNavBarMenuItemClick = function (item?: NavItemData) {
// close the nav bar menu... unless we clicked an item with submenus
if (!item?.subMenus) {
toggleMenu()
Expand Down
4 changes: 2 additions & 2 deletions webapp/components/connectWallets/wallets.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ const ConnectWalletButton = ({
}: {
hoverClassName: string
icon: React.ReactNode
onClick: () => void
onClick: ReturnType<typeof useConnectModal>['openConnectModal']
rightIcon?: React.ReactNode
text: string
}) => (
Expand Down Expand Up @@ -114,7 +114,7 @@ export const BtcWallet = function () {
return (
<Box
description={
<ConnectedToWallet icon={<UnisatLogo />} wallet={connector?.name} />
<ConnectedToWallet icon={<UnisatLogo />} wallet={connector!.name} />
}
title={t('btc-wallet')}
>
Expand Down
2 changes: 1 addition & 1 deletion webapp/components/errorBoundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ type State = {

// See https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary
export class ErrorBoundary extends React.Component<Props, State> {
constructor(props) {
constructor(props: Props) {
super(props)
this.state = { hasError: false }
}
Expand Down
2 changes: 1 addition & 1 deletion webapp/components/networkSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { Menu } from './menu'

type Props = {
disabled: boolean
networkId: RemoteChain['id'] | undefined
networkId: RemoteChain['id']
networks: RemoteChain[]
onSelectNetwork: (network: RemoteChain['id']) => void
readonly?: boolean
Expand Down
5 changes: 3 additions & 2 deletions webapp/components/switchToNetwork.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ export const SwitchToNetwork = function ({ selectedNetworkId }: Props) {
return null
}

const expectedWalletIsEvm = isEvmNetwork(walletTargetNetwork)
const expectedWalletIsEvm =
!!walletTargetNetwork && isEvmNetwork(walletTargetNetwork)

const isWalletConnected = () =>
expectedWalletIsEvm
Expand Down Expand Up @@ -67,7 +68,7 @@ export const SwitchToNetwork = function ({ selectedNetworkId }: Props) {
onClick={switchToNetwork}
type="button"
>
{t('connect-to-network', { network: walletTargetNetwork.name })}
{t('connect-to-network', { network: walletTargetNetwork?.name })}
</button>
}
text={t('wrong-network')}
Expand Down
4 changes: 2 additions & 2 deletions webapp/context/tunnelHistoryContext/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const WithdrawalsStateUpdater = dynamic(
)

const isReadyOrSyncing = (status: SyncStatus | undefined) =>
['ready', 'syncing'].includes(status)
!!status && ['ready', 'syncing'].includes(status)

const isChainReadyOrSyncing =
(history: HistoryReducerState) => (chain: RemoteChain) =>
Expand Down Expand Up @@ -95,7 +95,7 @@ export const TunnelHistoryProvider = function ({ children }: Props) {
const historyChainSync = []

// We need to be ready or syncing to return workers
if (isConnected && ['ready', 'syncing'].includes(history.status)) {
if (isConnected && address && ['ready', 'syncing'].includes(history.status)) {
// Add workers for every pair L1-Hemi chain
historyChainSync.push(
...remoteNetworks
Expand Down
3 changes: 2 additions & 1 deletion webapp/hooks/useSyncHistory/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ export const useSyncHistory = function (l2ChainId: Chain['id']) {

useEffect(
function restoreFromLocalStorage() {
if (loadedFromLocalStorage || !supportedEvmChain) {
if (!address || loadedFromLocalStorage || !supportedEvmChain) {
return
}
setLoadedFromLocalStorage(true)
Expand Down Expand Up @@ -207,6 +207,7 @@ export const useSyncHistory = function (l2ChainId: Chain['id']) {
useEffect(
function offloadToStorage() {
if (
!address ||
!supportedEvmChain ||
!loadedFromLocalStorage ||
!['finished', 'syncing'].includes(history.status) ||
Expand Down
4 changes: 2 additions & 2 deletions webapp/hooks/useSyncHistory/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,15 @@ export const getTunnelHistoryWithdrawStorageKey = (
const removeDuplicates = <T extends TunnelOperation>(merged: T[]) =>
Array.from(new Set(merged.map(({ transactionHash }) => transactionHash))).map(
transactionHash =>
merged.find(operation => operation.transactionHash === transactionHash),
merged.find(operation => operation.transactionHash === transactionHash)!,
)

const mergeContent = <T extends TunnelOperation>(
oldContent: T[],
newContent: T[],
) =>
removeDuplicates(oldContent.concat(newContent)).sort(
(a, b) => b.timestamp - a.timestamp,
(a, b) => b.timestamp ?? 0 - (a.timestamp ?? 0),
)

export const syncContent = <
Expand Down
4 changes: 2 additions & 2 deletions webapp/tokenList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ const hemiTokens: Token[] = (hemilabsTokenList.tokens as EvmToken[])
const l1HemiTokens = hemiTokens
.filter(t => !!t.extensions?.bridgeInfo)
.flatMap(t =>
Object.keys(t.extensions.bridgeInfo).map(l1ChainId => ({
Object.keys(t.extensions!.bridgeInfo!).map(l1ChainId => ({
...t,
address: t.extensions.bridgeInfo[l1ChainId].tokenAddress,
address: t.extensions!.bridgeInfo![l1ChainId].tokenAddress,
chainId: Number(l1ChainId),
extensions: {
bridgeInfo: {
Expand Down
2 changes: 1 addition & 1 deletion webapp/utils/cacheStrategies.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ const cachePerMethod = [
},
]

const cacheIndexedData = cachePerMethod.reduce(
const cacheIndexedData: Record<string, string> = cachePerMethod.reduce(
(acc, { method, strategy }) => ({
...acc,
[getSignature(method)]: strategy,
Expand Down
6 changes: 3 additions & 3 deletions webapp/utils/sync-history/evm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const createEvmSync = function ({
withdrawalsSyncInfo,
}: HistorySyncer<BlockSyncType>) {
const getBlockNumber = async function (
toBlock: number,
toBlock: number | undefined,
provider: JsonRpcProvider,
) {
if (toBlock !== undefined) {
Expand Down Expand Up @@ -108,7 +108,7 @@ export const createEvmSync = function ({
deposit =>
async function () {
const block = await getEvmBlock(
deposit.blockNumber,
deposit.blockNumber!,
l1Chain.id,
)
return {
Expand Down Expand Up @@ -201,7 +201,7 @@ export const createEvmSync = function ({
withdrawal =>
async function () {
const [block, status] = await Promise.all([
getEvmBlock(withdrawal.blockNumber, l2Chain.id),
getEvmBlock(withdrawal.blockNumber!, l2Chain.id),
crossChainMessenger.getMessageStatus(
withdrawal.transactionHash,
// default value
Expand Down

0 comments on commit 207bad1

Please sign in to comment.