Skip to content

Commit

Permalink
Add Safenet Check Summary to Signature Form (#4419)
Browse files Browse the repository at this point in the history
* Add SafeNet Check Summary to Signature Form

This PR adds the SafeNet checks to the transaction execution flow in the
wallet interface.

Currently, the checks are shown for any Safe that has SafeNet enabled
(i.e. has the SafeNet guard set on a supported chain). The checks are
done using the SafeNet service backend.

Results are grouped into categories which allows the UI to show high
level summaries based on a collection of guarantees as well as grouping
any unknown guarantees into an "other" category.

Note that I implemented SafeTx hash computation as I couldn't find a
ulitity method that did it for me anywhere - which was surprising. If
there is an existing utility method for this - please let me know and I
will change my code to use it.

* use Typography instead of p
  • Loading branch information
nlordell authored Oct 25, 2024
1 parent 53bab84 commit c325be5
Show file tree
Hide file tree
Showing 6 changed files with 254 additions and 1 deletion.
29 changes: 29 additions & 0 deletions src/components/tx/SignOrExecuteForm/SafeNetTxChecks.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { type ReactElement, useContext } from 'react'
import { SafeNetTxSimulation } from '@/components/tx/security/safenet'
import TxCard from '@/components/tx-flow/common/TxCard'
import { SafeTxContext } from '@/components/tx-flow/SafeTxProvider'
import useIsSafeNetEnabled from '@/hooks/useIsSafeNetEnabled'
import { Typography } from '@mui/material'
import useChainId from '@/hooks/useChainId'
import useSafeAddress from '@/hooks/useSafeAddress'

const SafeNetTxChecks = (): ReactElement | null => {
const safe = useSafeAddress()
const chainId = useChainId()
const { safeTx } = useContext(SafeTxContext)
const isSafeNetEnabled = useIsSafeNetEnabled()

if (!isSafeNetEnabled) {
return null
}

return (
<TxCard>
<Typography variant="h5">SafeNet checks</Typography>

<SafeNetTxSimulation safe={safe} chainId={chainId} safeTx={safeTx} />
</TxCard>
)
}

export default SafeNetTxChecks
3 changes: 3 additions & 0 deletions src/components/tx/SignOrExecuteForm/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import SignForm from './SignForm'
import { SafeTxContext } from '@/components/tx-flow/SafeTxProvider'
import ErrorMessage from '../ErrorMessage'
import TxChecks from './TxChecks'
import SafeNetTxChecks from './SafeNetTxChecks'
import TxCard from '@/components/tx-flow/common/TxCard'
import ConfirmationTitle, { ConfirmationTitleTypes } from '@/components/tx/SignOrExecuteForm/ConfirmationTitle'
import { useAppSelector } from '@/store'
Expand Down Expand Up @@ -199,6 +200,8 @@ export const SignOrExecuteForm = ({

{!isCounterfactualSafe && !props.isRejection && <TxChecks />}

<SafeNetTxChecks />

<TxCard>
<ConfirmationTitle
variant={willExecute ? ConfirmationTitleTypes.execute : ConfirmationTitleTypes.sign}
Expand Down
148 changes: 148 additions & 0 deletions src/components/tx/security/safenet/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { CircularProgress, List, ListItem, ListItemIcon, ListItemText, Paper, SvgIcon, Typography } from '@mui/material'
import type { SafeTransaction } from '@safe-global/safe-core-sdk-types'
import useDecodeTx from '@/hooks/useDecodeTx'
import CheckIcon from '@/public/images/common/check.svg'
import CloseIcon from '@/public/images/common/close.svg'
import type { SafeNetSimulationResponse } from '@/store/safenet'
import { useLazySimulateSafeNetTxQuery } from '@/store/safenet'
import { useEffect, type ReactElement } from 'react'
import css from './styles.module.css'
import { hashTypedData } from '@/utils/web3'

export type SafeNetTxSimulationProps = {
safe: string
chainId: string
safeTx?: SafeTransaction
}

function _getGuaranteeDisplayName(guarantee: string): string {
switch (guarantee) {
case 'no_delegatecall':
return 'Fraud verification'
case 'no_contract_recipient':
case 'recipient_signature':
return 'Recipient verification'
default:
return 'Other'
}
}

function _groupResultGuarantees({
results,
}: Pick<SafeNetSimulationResponse, 'results'>): { display: string; success: boolean }[] {
const groups = results.reduce((groups, { guarantee, success }) => {
const display = _getGuaranteeDisplayName(guarantee)
return {
...groups,
[display]: (groups[display] ?? true) && success,
}
}, {} as Record<string, boolean>)
return Object.entries(groups)
.map(([display, success]) => ({ display, success }))
.sort((a, b) => a.display.localeCompare(b.display))
}

function _getSafeTxHash({ safe, chainId, safeTx }: Required<SafeNetTxSimulationProps>): string {
return hashTypedData({
domain: {
chainId,
verifyingContract: safe,
},
types: {
SafeTx: [
{ type: 'address', name: 'to' },
{ type: 'uint256', name: 'value' },
{ type: 'bytes', name: 'data' },
{ type: 'uint8', name: 'operation' },
{ type: 'uint256', name: 'safeTxGas' },
{ type: 'uint256', name: 'baseGas' },
{ type: 'uint256', name: 'gasPrice' },
{ type: 'address', name: 'gasToken' },
{ type: 'address', name: 'refundReceiver' },
{ type: 'uint256', name: 'nonce' },
],
},
message: { ...safeTx.data },
})
}

const SafeNetTxTxSimulationSummary = ({ simulation }: { simulation: SafeNetSimulationResponse }): ReactElement => {
if (simulation.results.length === 0) {
return <Typography>No SafeNet checks enabled...</Typography>
}

const guarantees = _groupResultGuarantees(simulation)

return (
<Paper variant="outlined" className={css.wrapper}>
{simulation.hasError && (
<Typography color="error" className={css.errorSummary}>
One or more SafeNet checks failed!
</Typography>
)}

<List>
{guarantees.map(({ display, success }) => (
<ListItem key={display}>
<ListItemIcon>
{success ? (
<SvgIcon component={CheckIcon} inheritViewBox fontSize="small" color="success" />
) : (
<SvgIcon component={CloseIcon} inheritViewBox fontSize="small" color="error" />
)}
</ListItemIcon>
<ListItemText>{display}</ListItemText>
</ListItem>
))}
</List>
</Paper>
)
}

export const SafeNetTxSimulation = ({ safe, chainId, safeTx }: SafeNetTxSimulationProps): ReactElement | null => {
const [dataDecoded] = useDecodeTx(safeTx)
const [simulate, { data: simulation, status }] = useLazySimulateSafeNetTxQuery()

useEffect(() => {
if (!safeTx || !dataDecoded) {
return
}

const safeTxHash = _getSafeTxHash({ safe, chainId, safeTx })
simulate({
chainId,
tx: {
safe,
safeTxHash,
to: safeTx.data.to,
value: safeTx.data.value,
data: safeTx.data.data,
operation: safeTx.data.operation,
safeTxGas: safeTx.data.safeTxGas,
baseGas: safeTx.data.baseGas,
gasPrice: safeTx.data.gasPrice,
gasToken: safeTx.data.gasToken,
refundReceiver: safeTx.data.refundReceiver,
// We don't send confirmations, as we want to simulate the transaction before signing.
// In the future, we can consider sending the already collected signatures, but this is not
// necessary at the moment.
confirmations: [],
dataDecoded,
},
})
}, [safe, chainId, safeTx, dataDecoded, simulate])

switch (status) {
case 'fulfilled':
return <SafeNetTxTxSimulationSummary simulation={simulation!} />
case 'rejected':
return (
<Typography color="error">
<SvgIcon component={CloseIcon} inheritViewBox fontSize="small" sx={{ verticalAlign: 'middle', mr: 1 }} />
Unexpected error simulating with SafeNet!
</Typography>
)
default:
return <CircularProgress size={22} sx={{ color: ({ palette }) => palette.text.secondary }} />
}
}
11 changes: 11 additions & 0 deletions src/components/tx/security/safenet/styles.module.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
.wrapper {
display: flex;
flex-direction: column;
justify-content: space-between;
padding: var(--space-1) var(--space-2);
border-width: 1px;
}

.errorSummary {
padding: calc(var(--space-1) * 2) calc(var(--space-2) * 2) var(--space-1) calc(var(--space-2) * 2);
}
12 changes: 12 additions & 0 deletions src/hooks/useIsSafeNetEnabled.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import useSafeInfo from '@/hooks/useSafeInfo'
import { useGetSafeNetConfigQuery } from '@/store/safenet'
import { sameAddress } from '@/utils/addresses'

const useIsSafeNetEnabled = () => {
const { safe } = useSafeInfo()
const { data: safeNetConfig } = useGetSafeNetConfigQuery()

return sameAddress(safe.guard?.value, safeNetConfig?.guards[safe.chainId])
}

export default useIsSafeNetEnabled
52 changes: 51 additions & 1 deletion src/store/safenet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,41 @@ export type SafeNetBalanceEntity = {
[tokenSymbol: string]: string
}

export type SafeNetSimulateTx = {
safe: string
safeTxHash: string
to: string
value: string
data: string
operation: number
safeTxGas: string
baseGas: string
gasPrice: string
gasToken: string
refundReceiver: string
confirmations: []
dataDecoded: unknown
}

export type SafeNetSimulationResultSuccess = {
success: true
}

export type SafeNetSimulationResultFailure = {
success: false
message: string
}

export type SafeNetSimulationResult = {
guarantee: string
success: boolean
} & (SafeNetSimulationResultSuccess | SafeNetSimulationResultFailure)

export type SafeNetSimulationResponse = {
hasError: boolean
results: SafeNetSimulationResult[]
}

export const getSafeNetBalances = async (chainId: string, safeAddress: string): Promise<SafeNetBalanceEntity> => {
const response = await fetch(`${SAFENET_API_URL}/safenet/balances/${chainId}/${safeAddress}`)
const data = await response.json()
Expand All @@ -31,7 +66,7 @@ export const getSafeNetBalances = async (chainId: string, safeAddress: string):
export const safenetApi = createApi({
reducerPath: 'safenetApi',
baseQuery: fetchBaseQuery({ baseUrl: `${SAFENET_API_URL}/safenet` }),
tagTypes: ['SafeNetConfig', 'SafeNetOffchainStatus', 'SafeNetBalance'],
tagTypes: ['SafeNetConfig', 'SafeNetOffchainStatus', 'SafeNetBalance', 'SafeNetSimulation'],
endpoints: (builder) => ({
getSafeNetConfig: builder.query<SafeNetConfigEntity, void>({
query: () => `/config/`,
Expand All @@ -56,6 +91,20 @@ export const safenetApi = createApi({
query: ({ chainId, safeAddress }) => `/balances/${chainId}/${safeAddress}`,
providesTags: (_, __, arg) => [{ type: 'SafeNetBalance', id: arg.safeAddress }],
}),
simulateSafeNetTx: builder.query<
SafeNetSimulationResponse,
{
chainId: string
tx: SafeNetSimulateTx
}
>({
query: ({ chainId, tx }) => ({
url: `/tx/simulate/${chainId}`,
method: 'POST',
body: tx,
}),
providesTags: (_, __, arg) => [{ type: 'SafeNetSimulation', id: arg.tx.safeTxHash }],
}),
}),
})

Expand All @@ -64,4 +113,5 @@ export const {
useRegisterSafeNetMutation,
useGetSafeNetConfigQuery,
useLazyGetSafeNetBalanceQuery,
useLazySimulateSafeNetTxQuery,
} = safenetApi

0 comments on commit c325be5

Please sign in to comment.