@@ -68,7 +73,7 @@ export const AddressWrapper = (props: Props): React.ReactElement => {
className="safeListMakeDefaultButton"
textSize="sm"
onClick={() => {
- setDefaultSafe(safe.address)
+ setDefaultSafeAction(safe.address)
}}
color="primary"
>
diff --git a/src/components/SafeListSidebar/SafeList/index.tsx b/src/components/SafeListSidebar/SafeList/index.tsx
index 57b60238..3a664d56 100644
--- a/src/components/SafeListSidebar/SafeList/index.tsx
+++ b/src/components/SafeListSidebar/SafeList/index.tsx
@@ -6,12 +6,11 @@ import * as React from 'react'
import styled from 'styled-components'
import { SafeRecord } from 'src/logic/safe/store/models/safe'
import { DefaultSafe } from 'src/routes/safe/store/reducer/types/safe'
-import { SetDefaultSafe } from 'src/logic/safe/store/actions/setDefaultSafe'
import Hairline from 'src/components/layout/Hairline'
import Link from 'src/components/layout/Link'
import { sameAddress } from 'src/logic/wallets/ethAddresses'
import { SAFELIST_ADDRESS } from 'src/routes/routes'
-import { AddressWrapper } from './AddresWrapper'
+import { AddressWrapper } from 'src/components/SafeListSidebar/SafeList/AddressWrapper'
export const SIDEBAR_SAFELIST_ROW_TESTID = 'SIDEBAR_SAFELIST_ROW_TESTID'
const StyledIcon = styled(Icon)`
@@ -46,10 +45,9 @@ type Props = {
defaultSafe: DefaultSafe
safes: SafeRecord[]
onSafeClick: () => void
- setDefaultSafe: SetDefaultSafe
}
-const SafeList = ({ currentSafe, defaultSafe, onSafeClick, safes, setDefaultSafe }: Props): React.ReactElement => {
+export const SafeList = ({ currentSafe, defaultSafe, onSafeClick, safes }: Props): React.ReactElement => {
const classes = useStyles()
return (
@@ -67,7 +65,7 @@ const SafeList = ({ currentSafe, defaultSafe, onSafeClick, safes, setDefaultSafe
) : (
placeholder
)}
-
+
@@ -76,5 +74,3 @@ const SafeList = ({ currentSafe, defaultSafe, onSafeClick, safes, setDefaultSafe
)
}
-
-export default SafeList
diff --git a/src/components/SafeListSidebar/index.tsx b/src/components/SafeListSidebar/index.tsx
index 8aeeb77b..9846f170 100644
--- a/src/components/SafeListSidebar/index.tsx
+++ b/src/components/SafeListSidebar/index.tsx
@@ -1,10 +1,10 @@
-import React, { useEffect, useMemo, useState } from 'react'
+import React, { useEffect, useMemo, useState, ReactElement } from 'react'
import Drawer from '@material-ui/core/Drawer'
import SearchIcon from '@material-ui/icons/Search'
import SearchBar from 'material-ui-search-bar'
-import { connect } from 'react-redux'
+import { useSelector } from 'react-redux'
-import SafeList from './SafeList'
+import { SafeList } from './SafeList'
import { sortedSafeListSelector } from './selectors'
import useSidebarStyles from './style'
@@ -15,11 +15,9 @@ import Hairline from 'src/components/layout/Hairline'
import Link from 'src/components/layout/Link'
import Row from 'src/components/layout/Row'
import { WELCOME_ADDRESS } from 'src/routes/routes'
-import setDefaultSafe from 'src/logic/safe/store/actions/setDefaultSafe'
import { useAnalytics, SAFE_NAVIGATION_EVENT } from 'src/utils/googleAnalytics'
import { defaultSafeSelector, safeParamAddressFromStateSelector } from 'src/logic/safe/store/selectors'
-import { AppReduxState } from 'src/store'
export const SafeListSidebarContext = React.createContext({
isOpen: false,
@@ -34,9 +32,17 @@ const filterBy = (filter, safes) =>
safe.name.toLowerCase().includes(filter.toLowerCase()),
)
-const SafeListSidebar = ({ children, currentSafe, defaultSafe, safes, setDefaultSafeAction }) => {
+type Props = {
+ children: ReactElement
+}
+
+export const SafeListSidebar = ({ children }: Props): ReactElement => {
const [isOpen, setIsOpen] = useState(false)
const [filter, setFilter] = useState('')
+ const safes = useSelector(sortedSafeListSelector)
+ const defaultSafe = useSelector(defaultSafeSelector)
+ const currentSafe = useSelector(safeParamAddressFromStateSelector)
+
const classes = useSidebarStyles()
const { trackEvent } = useAnalytics()
@@ -118,19 +124,9 @@ const SafeListSidebar = ({ children, currentSafe, defaultSafe, safes, setDefault
defaultSafe={defaultSafe}
onSafeClick={toggleSidebar}
safes={filteredSafes}
- setDefaultSafe={setDefaultSafeAction}
/>
{children}
)
}
-
-export default connect(
- (state: AppReduxState) => ({
- safes: sortedSafeListSelector(state),
- defaultSafe: defaultSafeSelector(state),
- currentSafe: safeParamAddressFromStateSelector(state),
- }),
- { setDefaultSafeAction: setDefaultSafe },
-)(SafeListSidebar)
diff --git a/src/components/TransactionFailText/index.tsx b/src/components/TransactionFailText/index.tsx
new file mode 100644
index 00000000..d61664cc
--- /dev/null
+++ b/src/components/TransactionFailText/index.tsx
@@ -0,0 +1,56 @@
+import { createStyles, makeStyles } from '@material-ui/core'
+import { sm } from 'src/theme/variables'
+import { EstimationStatus } from 'src/logic/hooks/useEstimateTransactionGas'
+import Row from 'src/components/layout/Row'
+import Paragraph from 'src/components/layout/Paragraph'
+import Img from 'src/components/layout/Img'
+import InfoIcon from 'src/assets/icons/info_red.svg'
+import React from 'react'
+import { useSelector } from 'react-redux'
+import { safeThresholdSelector } from 'src/logic/safe/store/selectors'
+
+const styles = createStyles({
+ executionWarningRow: {
+ display: 'flex',
+ alignItems: 'center',
+ },
+ warningIcon: {
+ marginRight: sm,
+ },
+})
+
+const useStyles = makeStyles(styles)
+
+type TransactionFailTextProps = {
+ txEstimationExecutionStatus: EstimationStatus
+ isExecution: boolean
+}
+
+export const TransactionFailText = ({
+ txEstimationExecutionStatus,
+ isExecution,
+}: TransactionFailTextProps): React.ReactElement | null => {
+ const classes = useStyles()
+ const threshold = useSelector(safeThresholdSelector)
+
+ if (txEstimationExecutionStatus !== EstimationStatus.FAILURE) {
+ return null
+ }
+
+ let errorMessage = 'To save gas costs, avoid creating the transaction.'
+ if (isExecution) {
+ errorMessage =
+ threshold && threshold > 1
+ ? `To save gas costs, cancel this transaction`
+ : `To save gas costs, avoid executing the transaction.`
+ }
+
+ return (
+
+
+
+ This transaction will most likely fail. {errorMessage}
+
+
+ )
+}
diff --git a/src/components/TransactionsFees/index.tsx b/src/components/TransactionsFees/index.tsx
new file mode 100644
index 00000000..372c8b52
--- /dev/null
+++ b/src/components/TransactionsFees/index.tsx
@@ -0,0 +1,54 @@
+import React from 'react'
+import { EstimationStatus } from 'src/logic/hooks/useEstimateTransactionGas'
+import Paragraph from 'src/components/layout/Paragraph'
+import { getNetworkInfo } from 'src/config'
+import { TransactionFailText } from 'src/components/TransactionFailText'
+import { useSelector } from 'react-redux'
+import { providerNameSelector } from 'src/logic/wallets/store/selectors'
+import { sameString } from 'src/utils/strings'
+import { WALLETS } from 'src/config/networks/network.d'
+
+type TransactionFailTextProps = {
+ txEstimationExecutionStatus: EstimationStatus
+ gasCostFormatted: string
+ isExecution: boolean
+ isCreation: boolean
+ isOffChainSignature: boolean
+}
+const { nativeCoin } = getNetworkInfo()
+
+export const TransactionFees = ({
+ gasCostFormatted,
+ isExecution,
+ isCreation,
+ isOffChainSignature,
+ txEstimationExecutionStatus,
+}: TransactionFailTextProps): React.ReactElement | null => {
+ const providerName = useSelector(providerNameSelector)
+
+ let transactionAction
+ if (isCreation) {
+ transactionAction = 'create'
+ } else if (isExecution) {
+ transactionAction = 'execute'
+ } else {
+ transactionAction = 'approve'
+ }
+
+ // FIXME this should be removed when estimating with WalletConnect correctly
+ if (!providerName || sameString(providerName, WALLETS.WALLET_CONNECT)) {
+ return null
+ }
+
+ return (
+ <>
+
+ You're about to {transactionAction} a transaction and will have to confirm it with your currently connected
+ wallet.
+ {!isOffChainSignature &&
+ ` Make sure you have ${gasCostFormatted} (fee price) ${nativeCoin.name} in this wallet to fund this confirmation.`}
+
+
+ >
+ )
+}
diff --git a/src/components/forms/Field/DebounceValidationField.tsx b/src/components/forms/Field/DebounceValidationField.tsx
deleted file mode 100644
index 7996e59c..00000000
--- a/src/components/forms/Field/DebounceValidationField.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-// source: https://github.com/final-form/react-final-form/issues/369#issuecomment-439823584
-
-import React from 'react'
-import { Field } from 'react-final-form'
-
-import { trimSpaces } from 'src/utils/strings'
-
-const DebounceValidationField = ({ debounce = 1000, validate, ...rest }: any) => {
- let clearTimeout
-
- const localValidation = (value, values, fieldState) => {
- const url = trimSpaces(value)
-
- if (fieldState.active) {
- return new Promise((resolve) => {
- if (clearTimeout) clearTimeout()
- const timerId = setTimeout(() => {
- resolve(validate(url, values, fieldState))
- }, debounce)
- clearTimeout = () => {
- clearTimeout(timerId)
- resolve()
- }
- })
- } else {
- return validate(url, values, fieldState)
- }
- }
-
- return
-}
-
-export default DebounceValidationField
diff --git a/src/components/forms/Field/index.tsx b/src/components/forms/Field/index.tsx
index 9a2868f4..38f424fb 100644
--- a/src/components/forms/Field/index.tsx
+++ b/src/components/forms/Field/index.tsx
@@ -1,4 +1,4 @@
-import * as React from 'react'
+import React from 'react'
import { Field } from 'react-final-form'
// $FlowFixMe
diff --git a/src/logic/contracts/generateBatchRequests.ts b/src/logic/contracts/generateBatchRequests.ts
index 5c2a4128..a0807afb 100644
--- a/src/logic/contracts/generateBatchRequests.ts
+++ b/src/logic/contracts/generateBatchRequests.ts
@@ -46,7 +46,7 @@ const generateBatchRequests =
({
return new Promise((resolve) => {
const resolver = (error, result) => {
if (error) {
- resolve()
+ resolve(undefined)
} else {
resolve(result)
}
@@ -58,7 +58,7 @@ const generateBatchRequests = ({
request = web3[type][method].request(...args, resolver)
} else {
if (address === null) {
- resolve()
+ resolve(undefined)
return
}
request = contractInstance.methods[method](...args).call.request(resolver)
@@ -68,7 +68,7 @@ const generateBatchRequests = ({
batch ? batch.add(request) : localBatch.add(request)
} catch (e) {
console.warn('There was an error trying to batch request from web3.', e)
- resolve()
+ resolve(undefined)
}
})
})
diff --git a/src/logic/contracts/safeContracts.ts b/src/logic/contracts/safeContracts.ts
index 25550958..384fcc8e 100644
--- a/src/logic/contracts/safeContracts.ts
+++ b/src/logic/contracts/safeContracts.ts
@@ -130,7 +130,11 @@ export const estimateGasForDeployingSafe = async (
const proxyFactoryData = proxyFactoryMaster.methods
.createProxyWithNonce(safeMaster.options.address, gnosisSafeData, safeCreationSalt)
.encodeABI()
- const gas = await calculateGasOf(proxyFactoryData, userAccount, proxyFactoryMaster.options.address)
+ const gas = await calculateGasOf({
+ data: proxyFactoryData,
+ from: userAccount,
+ to: proxyFactoryMaster.options.address,
+ })
const gasPrice = await calculateGasPrice()
return gas * parseInt(gasPrice, 10)
diff --git a/src/logic/hooks/useEstimateTransactionGas.tsx b/src/logic/hooks/useEstimateTransactionGas.tsx
new file mode 100644
index 00000000..f3c33747
--- /dev/null
+++ b/src/logic/hooks/useEstimateTransactionGas.tsx
@@ -0,0 +1,257 @@
+import { useEffect, useState } from 'react'
+import {
+ estimateGasForTransactionApproval,
+ estimateGasForTransactionCreation,
+ estimateGasForTransactionExecution,
+} from 'src/logic/safe/transactions/gas'
+import { fromTokenUnit } from 'src/logic/tokens/utils/humanReadableValue'
+import { formatAmount } from 'src/logic/tokens/utils/formatAmount'
+import { calculateGasPrice } from 'src/logic/wallets/ethTransactions'
+import { getNetworkInfo } from 'src/config'
+import { useSelector } from 'react-redux'
+import {
+ safeCurrentVersionSelector,
+ safeParamAddressFromStateSelector,
+ safeThresholdSelector,
+} from 'src/logic/safe/store/selectors'
+import { CALL } from 'src/logic/safe/transactions'
+import { providerSelector } from '../wallets/store/selectors'
+
+import { List } from 'immutable'
+import { Confirmation } from 'src/logic/safe/store/models/types/confirmation'
+import { checkIfOffChainSignatureIsPossible } from 'src/logic/safe/safeTxSigner'
+import { ZERO_ADDRESS } from 'src/logic/wallets/ethAddresses'
+import { sameString } from 'src/utils/strings'
+import { WALLETS } from 'src/config/networks/network.d'
+
+export enum EstimationStatus {
+ LOADING = 'LOADING',
+ FAILURE = 'FAILURE',
+ SUCCESS = 'SUCCESS',
+}
+
+const checkIfTxIsExecution = (
+ threshold: number,
+ preApprovingOwner?: string,
+ txConfirmations?: number,
+ txType?: string,
+): boolean =>
+ txConfirmations === threshold || !!preApprovingOwner || threshold === 1 || sameString(txType, 'spendingLimit')
+
+const checkIfTxIsApproveAndExecution = (threshold: number, txConfirmations: number, txType?: string): boolean =>
+ txConfirmations + 1 === threshold || sameString(txType, 'spendingLimit')
+
+const checkIfTxIsCreation = (txConfirmations: number, txType?: string): boolean =>
+ txConfirmations === 0 && !sameString(txType, 'spendingLimit')
+
+type TransactionEstimationProps = {
+ txData: string
+ safeAddress: string
+ txRecipient: string
+ txConfirmations?: List
+ txAmount?: string
+ operation?: number
+ gasPrice?: string
+ gasToken?: string
+ refundReceiver?: string // Address of receiver of gas payment (or 0 if tx.origin).
+ safeTxGas?: number
+ from?: string
+ isExecution: boolean
+ isCreation: boolean
+ isOffChainSignature?: boolean
+ approvalAndExecution?: boolean
+}
+
+const estimateTransactionGas = async ({
+ txData,
+ safeAddress,
+ txRecipient,
+ txConfirmations,
+ txAmount,
+ operation,
+ gasPrice,
+ gasToken,
+ refundReceiver,
+ safeTxGas,
+ from,
+ isExecution,
+ isCreation,
+ isOffChainSignature = false,
+ approvalAndExecution,
+}: TransactionEstimationProps): Promise => {
+ if (isCreation) {
+ return estimateGasForTransactionCreation(safeAddress, txData, txRecipient, txAmount || '0', operation || CALL)
+ }
+
+ if (!from) {
+ throw new Error('No from provided for approving or execute transaction')
+ }
+
+ if (isExecution) {
+ return estimateGasForTransactionExecution({
+ safeAddress,
+ txRecipient,
+ txConfirmations,
+ txAmount: txAmount || '0',
+ txData,
+ operation: operation || CALL,
+ from,
+ gasPrice: gasPrice || '0',
+ gasToken: gasToken || ZERO_ADDRESS,
+ refundReceiver: refundReceiver || ZERO_ADDRESS,
+ safeTxGas: safeTxGas || 0,
+ approvalAndExecution,
+ })
+ }
+
+ return estimateGasForTransactionApproval({
+ safeAddress,
+ operation: operation || CALL,
+ txData,
+ txAmount: txAmount || '0',
+ txRecipient,
+ from,
+ isOffChainSignature,
+ })
+}
+
+type UseEstimateTransactionGasProps = {
+ txData: string
+ txRecipient: string
+ txConfirmations?: List
+ txAmount?: string
+ preApprovingOwner?: string
+ operation?: number
+ safeTxGas?: number
+ txType?: string
+}
+
+type TransactionGasEstimationResult = {
+ txEstimationExecutionStatus: EstimationStatus
+ gasEstimation: number // Amount of gas needed for execute or approve the transaction
+ gasCost: string // Cost of gas in raw format (estimatedGas * gasPrice)
+ gasCostFormatted: string // Cost of gas in format '< | > 100'
+ gasPrice: string // Current price of gas unit
+ isExecution: boolean // Returns true if the user will execute the tx or false if it just signs it
+ isCreation: boolean // Returns true if the transaction is a creation transaction
+ isOffChainSignature: boolean // Returns true if offChainSignature is available
+}
+
+export const useEstimateTransactionGas = ({
+ txRecipient,
+ txData,
+ txConfirmations,
+ txAmount,
+ preApprovingOwner,
+ operation,
+ safeTxGas,
+ txType,
+}: UseEstimateTransactionGasProps): TransactionGasEstimationResult => {
+ const [gasEstimation, setGasEstimation] = useState({
+ txEstimationExecutionStatus: EstimationStatus.LOADING,
+ gasEstimation: 0,
+ gasCost: '0',
+ gasCostFormatted: '< 0.001',
+ gasPrice: '0',
+ isExecution: false,
+ isCreation: false,
+ isOffChainSignature: false,
+ })
+ const { nativeCoin } = getNetworkInfo()
+ const safeAddress = useSelector(safeParamAddressFromStateSelector)
+ const threshold = useSelector(safeThresholdSelector)
+ const safeVersion = useSelector(safeCurrentVersionSelector)
+ const { account: from, smartContractWallet, name: providerName } = useSelector(providerSelector)
+
+ useEffect(() => {
+ const estimateGas = async () => {
+ if (!txData.length) {
+ return
+ }
+ // FIXME this should be removed when estimating with WalletConnect correctly
+ if (!providerName || sameString(providerName, WALLETS.WALLET_CONNECT)) {
+ return null
+ }
+
+ const isExecution = checkIfTxIsExecution(Number(threshold), preApprovingOwner, txConfirmations?.size, txType)
+ const isCreation = checkIfTxIsCreation(txConfirmations?.size || 0, txType)
+ const approvalAndExecution = checkIfTxIsApproveAndExecution(Number(threshold), txConfirmations?.size || 0, txType)
+
+ try {
+ const isOffChainSignature = checkIfOffChainSignatureIsPossible(isExecution, smartContractWallet, safeVersion)
+
+ const gasEstimation = await estimateTransactionGas({
+ safeAddress,
+ txRecipient,
+ txData,
+ txAmount,
+ txConfirmations,
+ isExecution,
+ isCreation,
+ isOffChainSignature,
+ operation,
+ from,
+ safeTxGas,
+ approvalAndExecution,
+ })
+ const gasPrice = await calculateGasPrice()
+ const estimatedGasCosts = gasEstimation * parseInt(gasPrice, 10)
+ const gasCost = fromTokenUnit(estimatedGasCosts, nativeCoin.decimals)
+ const gasCostFormatted = formatAmount(gasCost)
+
+ let txEstimationExecutionStatus = EstimationStatus.SUCCESS
+
+ if (gasEstimation <= 0) {
+ txEstimationExecutionStatus = isOffChainSignature ? EstimationStatus.SUCCESS : EstimationStatus.FAILURE
+ }
+
+ setGasEstimation({
+ txEstimationExecutionStatus,
+ gasEstimation,
+ gasCost,
+ gasCostFormatted,
+ gasPrice,
+ isExecution,
+ isCreation,
+ isOffChainSignature,
+ })
+ } catch (error) {
+ console.warn(error.message)
+ // We put a fixed the amount of gas to let the user try to execute the tx, but it's not accurate so it will probably fail
+ const gasEstimation = 10000
+ const gasCost = fromTokenUnit(gasEstimation, nativeCoin.decimals)
+ const gasCostFormatted = formatAmount(gasCost)
+ setGasEstimation({
+ txEstimationExecutionStatus: EstimationStatus.FAILURE,
+ gasEstimation,
+ gasCost,
+ gasCostFormatted,
+ gasPrice: '1',
+ isExecution,
+ isCreation,
+ isOffChainSignature: false,
+ })
+ }
+ }
+
+ estimateGas()
+ }, [
+ txData,
+ safeAddress,
+ txRecipient,
+ txConfirmations,
+ txAmount,
+ preApprovingOwner,
+ nativeCoin.decimals,
+ threshold,
+ from,
+ operation,
+ safeVersion,
+ smartContractWallet,
+ safeTxGas,
+ txType,
+ providerName,
+ ])
+
+ return gasEstimation
+}
diff --git a/src/logic/notifications/store/reducer/notifications.ts b/src/logic/notifications/store/reducer/notifications.ts
index 802ab9bd..bb05f747 100644
--- a/src/logic/notifications/store/reducer/notifications.ts
+++ b/src/logic/notifications/store/reducer/notifications.ts
@@ -20,7 +20,7 @@ export default handleActions(
const { dismissAll, key } = action.payload
if (key) {
- return state.update(key, (prev) => prev.set('dismissed', true))
+ return state.update(key, (prev) => prev?.set('dismissed', true))
}
if (dismissAll) {
return state.withMutations((map) => {
diff --git a/src/logic/safe/safeTxSigner.ts b/src/logic/safe/safeTxSigner.ts
index 52de1a3b..4fce148d 100644
--- a/src/logic/safe/safeTxSigner.ts
+++ b/src/logic/safe/safeTxSigner.ts
@@ -1,31 +1,61 @@
-// https://docs.gnosis.io/safe/docs/docs5/#pre-validated-signatures
-// https://github.com/gnosis/safe-contracts/blob/master/test/gnosisSafeTeamEdition.js#L26
-export const generateSignaturesFromTxConfirmations = (confirmations, preApprovingOwner) => {
- // The constant parts need to be sorted so that the recovered signers are sorted ascending
- // (natural order) by address (not checksummed).
- const confirmationsMap = confirmations.reduce((map, obj) => {
- map[obj.owner.toLowerCase()] = obj // eslint-disable-line no-param-reassign
- return map
- }, {})
+import { List } from 'immutable'
+import { Confirmation } from 'src/logic/safe/store/models/types/confirmation'
+import { EMPTY_DATA } from 'src/logic/wallets/ethTransactions'
+import semverSatisfies from 'semver/functions/satisfies'
+import { SAFE_VERSION_FOR_OFFCHAIN_SIGNATURES } from './transactions/offchainSigner'
+
+// Here we're checking that safe contract version is greater or equal 1.1.1, but
+// theoretically EIP712 should also work for 1.0.0 contracts
+// Also, offchain signatures are not working for ledger/trezor wallet because of a bug in their library:
+// https://github.com/LedgerHQ/ledgerjs/issues/378
+// Couldn't find an issue for trezor but the error is almost the same
+export const checkIfOffChainSignatureIsPossible = (
+ isExecution: boolean,
+ isSmartContractWallet: boolean,
+ safeVersion?: string,
+): boolean =>
+ !isExecution &&
+ !isSmartContractWallet &&
+ !!safeVersion &&
+ semverSatisfies(safeVersion, SAFE_VERSION_FOR_OFFCHAIN_SIGNATURES)
+
+// https://docs.gnosis.io/safe/docs/contracts_signatures/#pre-validated-signatures
+export const getPreValidatedSignatures = (from: string, initialString: string = EMPTY_DATA): string => {
+ return `${initialString}000000000000000000000000${from.replace(
+ EMPTY_DATA,
+ '',
+ )}000000000000000000000000000000000000000000000000000000000000000001`
+}
+
+export const generateSignaturesFromTxConfirmations = (
+ confirmations?: List,
+ preApprovingOwner?: string,
+): string => {
+ let confirmationsMap =
+ confirmations?.map((value) => {
+ return {
+ signature: value.signature,
+ owner: value.owner.toLowerCase(),
+ }
+ }) || List([])
if (preApprovingOwner) {
- confirmationsMap[preApprovingOwner.toLowerCase()] = { owner: preApprovingOwner }
+ confirmationsMap = confirmationsMap.push({ owner: preApprovingOwner, signature: null })
}
+ // The constant parts need to be sorted so that the recovered signers are sorted ascending
+ // (natural order) by address (not checksummed).
+ confirmationsMap = confirmationsMap.sort((ownerA, ownerB) => ownerA.owner.localeCompare(ownerB.owner))
+
let sigs = '0x'
- Object.keys(confirmationsMap)
- .sort()
- .forEach((addr) => {
- const conf = confirmationsMap[addr]
- if (conf.signature) {
- sigs += conf.signature.slice(2)
- } else {
- // https://docs.gnosis.io/safe/docs/docs5/#pre-validated-signatures
- sigs += `000000000000000000000000${addr.replace(
- '0x',
- '',
- )}000000000000000000000000000000000000000000000000000000000000000001`
- }
- })
+ confirmationsMap.forEach(({ signature, owner }) => {
+ if (signature) {
+ sigs += signature.slice(2)
+ } else {
+ // https://docs.gnosis.io/safe/docs/contracts_signatures/#pre-validated-signatures
+ sigs += getPreValidatedSignatures(owner, '')
+ }
+ })
+
return sigs
}
diff --git a/src/logic/safe/store/actions/__tests__/utils.test.ts b/src/logic/safe/store/actions/__tests__/utils.test.ts
index db063f9a..b11ebcb3 100644
--- a/src/logic/safe/store/actions/__tests__/utils.test.ts
+++ b/src/logic/safe/store/actions/__tests__/utils.test.ts
@@ -3,22 +3,8 @@ import { GnosisSafe } from 'src/types/contracts/GnosisSafe.d'
import { TxServiceModel } from 'src/logic/safe/store/actions/transactions/fetchTransactions/loadOutgoingTransactions'
describe('Store actions utils > getNewTxNonce', () => {
- it(`Should return passed predicted transaction nonce if it's a valid value`, async () => {
- // Given
- const txNonce = '45'
- const lastTx = { nonce: 44 } as TxServiceModel
- const safeInstance = {}
-
- // When
- const nonce = await getNewTxNonce(txNonce, lastTx, safeInstance as GnosisSafe)
-
- // Then
- expect(nonce).toBe('45')
- })
-
it(`Should return nonce of a last transaction + 1 if passed nonce is less than last transaction or invalid`, async () => {
// Given
- const txNonce = ''
const lastTx = { nonce: 44 } as TxServiceModel
const safeInstance = {
methods: {
@@ -29,7 +15,7 @@ describe('Store actions utils > getNewTxNonce', () => {
}
// When
- const nonce = await getNewTxNonce(txNonce, lastTx, safeInstance as GnosisSafe)
+ const nonce = await getNewTxNonce(lastTx, safeInstance as GnosisSafe)
// Then
expect(nonce).toBe('45')
@@ -37,7 +23,6 @@ describe('Store actions utils > getNewTxNonce', () => {
it(`Should retrieve contract's instance nonce value as a fallback, if txNonce and lastTx are not valid`, async () => {
// Given
- const txNonce = ''
const lastTx = null
const safeInstance = {
methods: {
@@ -48,7 +33,7 @@ describe('Store actions utils > getNewTxNonce', () => {
}
// When
- const nonce = await getNewTxNonce(txNonce, lastTx, safeInstance as GnosisSafe)
+ const nonce = await getNewTxNonce(lastTx, safeInstance as GnosisSafe)
// Then
expect(nonce).toBe('45')
diff --git a/src/logic/safe/store/actions/createTransaction.ts b/src/logic/safe/store/actions/createTransaction.ts
index 0106e56f..0e318e33 100644
--- a/src/logic/safe/store/actions/createTransaction.ts
+++ b/src/logic/safe/store/actions/createTransaction.ts
@@ -1,5 +1,4 @@
import { push } from 'connected-react-router'
-import semverSatisfies from 'semver/functions/satisfies'
import { ThunkAction } from 'redux-thunk'
import { onboardUser } from 'src/components/ConnectButton'
@@ -10,11 +9,10 @@ import {
CALL,
getApprovalTransaction,
getExecutionTransaction,
- SAFE_VERSION_FOR_OFFCHAIN_SIGNATURES,
saveTxToHistory,
tryOffchainSigning,
} from 'src/logic/safe/transactions'
-import { estimateSafeTxGas } from 'src/logic/safe/transactions/gas'
+import { estimateGasForTransactionCreation } from 'src/logic/safe/transactions/gas'
import { getCurrentSafeVersion } from 'src/logic/safe/utils/safeVersion'
import { ZERO_ADDRESS } from 'src/logic/wallets/ethAddresses'
import { EMPTY_DATA } from 'src/logic/wallets/ethTransactions'
@@ -40,6 +38,7 @@ import { AnyAction } from 'redux'
import { PayableTx } from 'src/types/contracts/types.d'
import { AppReduxState } from 'src/store'
import { Dispatch, DispatchReturn } from './types'
+import { checkIfOffChainSignatureIsPossible, getPreValidatedSignatures } from 'src/logic/safe/safeTxSigner'
export interface CreateTransactionArgs {
navigateToTransactionsTab?: boolean
@@ -87,18 +86,18 @@ const createTransaction = (
const { account: from, hardwareWallet, smartContractWallet } = providerSelector(state)
const safeInstance = await getGnosisSafeInstanceAt(safeAddress)
const lastTx = await getLastTx(safeAddress)
- const nonce = await getNewTxNonce(txNonce?.toString(), lastTx, safeInstance)
+ const nonce = txNonce ? txNonce.toString() : await getNewTxNonce(lastTx, safeInstance)
const isExecution = await shouldExecuteTransaction(safeInstance, nonce, lastTx)
const safeVersion = await getCurrentSafeVersion(safeInstance)
- const safeTxGas =
- safeTxGasArg || (await estimateSafeTxGas(safeInstance, safeAddress, txData, to, valueInWei, operation))
-
- // https://docs.gnosis.io/safe/docs/docs5/#pre-validated-signatures
- const sigs = `0x000000000000000000000000${from.replace(
- '0x',
- '',
- )}000000000000000000000000000000000000000000000000000000000000000001`
+ let safeTxGas
+ try {
+ safeTxGas =
+ safeTxGasArg || (await estimateGasForTransactionCreation(safeAddress, txData, to, valueInWei, operation))
+ } catch (error) {
+ safeTxGas = safeTxGasArg || 0
+ }
+ const sigs = getPreValidatedSignatures(from)
const notificationsQueue = getNotificationsFromTxType(notifiedTransaction, origin)
const beforeExecutionKey = dispatch(enqueueSnackbar(notificationsQueue.beforeExecution))
@@ -123,11 +122,7 @@ const createTransaction = (
const safeTxHash = generateSafeTxHash(safeAddress, txArgs)
try {
- // Here we're checking that safe contract version is greater or equal 1.1.1, but
- // theoretically EIP712 should also work for 1.0.0 contracts
- const canTryOffchainSigning =
- !isExecution && !smartContractWallet && semverSatisfies(safeVersion, SAFE_VERSION_FOR_OFFCHAIN_SIGNATURES)
- if (canTryOffchainSigning) {
+ if (checkIfOffChainSignatureIsPossible(isExecution, smartContractWallet, safeVersion)) {
const signature = await tryOffchainSigning(safeTxHash, { ...txArgs, safeAddress }, hardwareWallet)
if (signature) {
@@ -141,9 +136,7 @@ const createTransaction = (
}
}
- const tx = isExecution
- ? await getExecutionTransaction(txArgs)
- : await getApprovalTransaction(safeInstance, safeTxHash)
+ const tx = isExecution ? getExecutionTransaction(txArgs) : getApprovalTransaction(safeInstance, safeTxHash)
const sendParams: PayableTx = { from, value: 0 }
// if not set owner management tests will fail on ganache
diff --git a/src/logic/safe/store/actions/processTransaction.ts b/src/logic/safe/store/actions/processTransaction.ts
index eced5a75..a8a352bf 100644
--- a/src/logic/safe/store/actions/processTransaction.ts
+++ b/src/logic/safe/store/actions/processTransaction.ts
@@ -1,12 +1,15 @@
import { AnyAction } from 'redux'
import { ThunkAction } from 'redux-thunk'
-import semverSatisfies from 'semver/functions/satisfies'
import { getGnosisSafeInstanceAt } from 'src/logic/contracts/safeContracts'
import { getNotificationsFromTxType } from 'src/logic/notifications'
-import { generateSignaturesFromTxConfirmations } from 'src/logic/safe/safeTxSigner'
+import {
+ checkIfOffChainSignatureIsPossible,
+ generateSignaturesFromTxConfirmations,
+ getPreValidatedSignatures,
+} from 'src/logic/safe/safeTxSigner'
import { getApprovalTransaction, getExecutionTransaction, saveTxToHistory } from 'src/logic/safe/transactions'
-import { SAFE_VERSION_FOR_OFFCHAIN_SIGNATURES, tryOffchainSigning } from 'src/logic/safe/transactions/offchainSigner'
+import { tryOffchainSigning } from 'src/logic/safe/transactions/offchainSigner'
import { getCurrentSafeVersion } from 'src/logic/safe/utils/safeVersion'
import { EMPTY_DATA } from 'src/logic/wallets/ethTransactions'
import { providerSelector } from 'src/logic/wallets/store/selectors'
@@ -29,16 +32,18 @@ interface ProcessTransactionArgs {
safeAddress: string
tx: Transaction
userAddress: string
+ thresholdReached: boolean
}
type ProcessTransactionAction = ThunkAction, AppReduxState, DispatchReturn, AnyAction>
-const processTransaction = ({
+export const processTransaction = ({
approveAndExecute,
notifiedTransaction,
safeAddress,
tx,
userAddress,
+ thresholdReached,
}: ProcessTransactionArgs): ProcessTransactionAction => async (
dispatch: Dispatch,
getState: () => AppReduxState,
@@ -49,17 +54,15 @@ const processTransaction = ({
const safeInstance = await getGnosisSafeInstanceAt(safeAddress)
const lastTx = await getLastTx(safeAddress)
- const nonce = await getNewTxNonce(undefined, lastTx, safeInstance)
+ const nonce = await getNewTxNonce(lastTx, safeInstance)
const isExecution = approveAndExecute || (await shouldExecuteTransaction(safeInstance, nonce, lastTx))
const safeVersion = await getCurrentSafeVersion(safeInstance)
- let sigs = generateSignaturesFromTxConfirmations(tx.confirmations, approveAndExecute && userAddress)
- // https://docs.gnosis.io/safe/docs/docs5/#pre-validated-signatures
+ const preApprovingOwner = approveAndExecute && !thresholdReached ? userAddress : undefined
+ let sigs = generateSignaturesFromTxConfirmations(tx.confirmations, preApprovingOwner)
+
if (!sigs) {
- sigs = `0x000000000000000000000000${from.replace(
- '0x',
- '',
- )}000000000000000000000000000000000000000000000000000000000000000001`
+ sigs = getPreValidatedSignatures(from)
}
const notificationsQueue = getNotificationsFromTxType(notifiedTransaction, tx.origin)
@@ -86,14 +89,7 @@ const processTransaction = ({
}
try {
- // Here we're checking that safe contract version is greater or equal 1.1.1, but
- // theoretically EIP712 should also work for 1.0.0 contracts
- // Also, offchain signatures are not working for ledger/trezor wallet because of a bug in their library:
- // https://github.com/LedgerHQ/ledgerjs/issues/378
- // Couldn't find an issue for trezor but the error is almost the same
- const canTryOffchainSigning =
- !isExecution && !smartContractWallet && semverSatisfies(safeVersion, SAFE_VERSION_FOR_OFFCHAIN_SIGNATURES)
- if (canTryOffchainSigning) {
+ if (checkIfOffChainSignatureIsPossible(isExecution, smartContractWallet, safeVersion)) {
const signature = await tryOffchainSigning(tx.safeTxHash, { ...txArgs, safeAddress }, hardwareWallet)
if (signature) {
@@ -109,9 +105,7 @@ const processTransaction = ({
}
}
- transaction = isExecution
- ? await getExecutionTransaction(txArgs)
- : await getApprovalTransaction(safeInstance, tx.safeTxHash)
+ transaction = isExecution ? getExecutionTransaction(txArgs) : getApprovalTransaction(safeInstance, tx.safeTxHash)
const sendParams: any = { from, value: 0 }
@@ -196,5 +190,3 @@ const processTransaction = ({
return txHash
}
-
-export default processTransaction
diff --git a/src/logic/safe/store/actions/removeLocalSafe.ts b/src/logic/safe/store/actions/removeLocalSafe.ts
new file mode 100644
index 00000000..64bd4284
--- /dev/null
+++ b/src/logic/safe/store/actions/removeLocalSafe.ts
@@ -0,0 +1,11 @@
+import { Action, Dispatch } from 'redux'
+import { loadStoredSafes } from 'src/logic/safe/utils'
+import removeSafe from 'src/logic/safe/store/actions/removeSafe'
+
+export const removeLocalSafe = (safeAddress: string) => async (dispatch: Dispatch): Promise => {
+ const storedSafes = await loadStoredSafes()
+ if (storedSafes) {
+ delete storedSafes[safeAddress]
+ }
+ dispatch(removeSafe(safeAddress))
+}
diff --git a/src/logic/safe/store/actions/transactions/utils/transactionHelpers.ts b/src/logic/safe/store/actions/transactions/utils/transactionHelpers.ts
index b776b71c..fcc32275 100644
--- a/src/logic/safe/store/actions/transactions/utils/transactionHelpers.ts
+++ b/src/logic/safe/store/actions/transactions/utils/transactionHelpers.ts
@@ -173,12 +173,12 @@ export const calculateTransactionStatus = (
if (tx.isExecuted && tx.isSuccessful) {
txStatus = TransactionStatus.SUCCESS
+ } else if (tx.creationTx) {
+ txStatus = TransactionStatus.SUCCESS
} else if (tx.cancelled || nonce > tx.nonce) {
txStatus = TransactionStatus.CANCELLED
} else if (tx.confirmations.size === threshold) {
txStatus = TransactionStatus.AWAITING_EXECUTION
- } else if (tx.creationTx) {
- txStatus = TransactionStatus.SUCCESS
} else if (!!tx.isPending) {
txStatus = TransactionStatus.PENDING
} else {
diff --git a/src/logic/safe/store/actions/utils.ts b/src/logic/safe/store/actions/utils.ts
index 74b59b0d..828c6e92 100644
--- a/src/logic/safe/store/actions/utils.ts
+++ b/src/logic/safe/store/actions/utils.ts
@@ -16,15 +16,7 @@ export const getLastTx = async (safeAddress: string): Promise => {
- if (txNonce) {
- return txNonce
- }
-
+export const getNewTxNonce = async (lastTx: TxServiceModel | null, safeInstance: GnosisSafe): Promise => {
// use current's safe nonce as fallback
return lastTx ? `${lastTx.nonce + 1}` : (await safeInstance.methods.nonce().call()).toString()
}
diff --git a/src/logic/safe/store/reducer/safe.ts b/src/logic/safe/store/reducer/safe.ts
index 0d651704..b5997f68 100644
--- a/src/logic/safe/store/reducer/safe.ts
+++ b/src/logic/safe/store/reducer/safe.ts
@@ -107,17 +107,18 @@ export default handleActions(
[ADD_OR_UPDATE_SAFE]: (state: SafeReducerMap, action) => {
const { safe } = action.payload
+ const safeAddress = safe.address
- if (!state.hasIn(['safes', safe.address])) {
- return state.setIn(['safes', safe.address], makeSafe(safe))
+ if (!state.hasIn(['safes', safeAddress])) {
+ return state.setIn(['safes', safeAddress], makeSafe(safe))
}
- const shouldUpdate = shouldSafeStoreBeUpdated(safe, state.getIn(['safes', safe.safeAddress]))
+ const shouldUpdate = shouldSafeStoreBeUpdated(safe, state.getIn(['safes', safeAddress]))
return shouldUpdate
? state.updateIn(
- ['safes', safe.address],
- makeSafe({ name: safe?.name || 'LOADED SAFE', address: safe.address }),
+ ['safes', safeAddress],
+ makeSafe({ name: safe?.name || 'LOADED SAFE', address: safeAddress }),
(prevSafe) => updateSafeProps(prevSafe, safe),
)
: state
@@ -125,7 +126,14 @@ export default handleActions(
[REMOVE_SAFE]: (state: SafeReducerMap, action) => {
const safeAddress = action.payload
- return state.deleteIn(['safes', safeAddress])
+ const currentDefaultSafe = state.get('defaultSafe')
+
+ let newState = state.deleteIn(['safes', safeAddress])
+ if (sameAddress(safeAddress, currentDefaultSafe)) {
+ newState = newState.set('defaultSafe', DEFAULT_SAFE_INITIAL_STATE)
+ }
+
+ return newState
},
[ADD_SAFE_OWNER]: (state: SafeReducerMap, action) => {
const { ownerAddress, ownerName, safeAddress } = action.payload
diff --git a/src/logic/safe/transactions/__tests__/gas.test.ts b/src/logic/safe/transactions/__tests__/gas.test.ts
index 4c698240..028796ad 100644
Binary files a/src/logic/safe/transactions/__tests__/gas.test.ts and b/src/logic/safe/transactions/__tests__/gas.test.ts differ
diff --git a/src/logic/safe/transactions/gas.ts b/src/logic/safe/transactions/gas.ts
index 92982f12..37f12655 100644
--- a/src/logic/safe/transactions/gas.ts
+++ b/src/logic/safe/transactions/gas.ts
@@ -1,19 +1,15 @@
-import GnosisSafeSol from '@gnosis.pm/safe-contracts/build/contracts/GnosisSafe.json'
import { BigNumber } from 'bignumber.js'
-import { AbiItem } from 'web3-utils'
-
-import { CALL } from '.'
-
import { getGnosisSafeInstanceAt } from 'src/logic/contracts/safeContracts'
-import { generateSignaturesFromTxConfirmations } from 'src/logic/safe/safeTxSigner'
-import { Transaction } from 'src/logic/safe/store/models/types/transaction'
-import { ZERO_ADDRESS } from 'src/logic/wallets/ethAddresses'
-import { EMPTY_DATA, calculateGasOf, calculateGasPrice } from 'src/logic/wallets/ethTransactions'
-import { getAccountFrom, getWeb3 } from 'src/logic/wallets/getWeb3'
-import { GnosisSafe } from 'src/types/contracts/GnosisSafe.d'
+import { calculateGasOf, EMPTY_DATA } from 'src/logic/wallets/ethTransactions'
+import { getWeb3 } from 'src/logic/wallets/getWeb3'
import { sameString } from 'src/utils/strings'
+import { ZERO_ADDRESS } from 'src/logic/wallets/ethAddresses'
+import { generateSignaturesFromTxConfirmations } from 'src/logic/safe/safeTxSigner'
+import { List } from 'immutable'
+import { Confirmation } from 'src/logic/safe/store/models/types/confirmation'
-const estimateDataGasCosts = (data: string): number => {
+// Receives the response data of the safe method requiredTxGas() and parses it to get the gas amount
+const parseRequiredTxGasResponse = (data: string): number => {
const reducer = (accumulator, currentValue) => {
if (currentValue === EMPTY_DATA) {
return accumulator + 0
@@ -29,76 +25,38 @@ const estimateDataGasCosts = (data: string): number => {
return data.match(/.{2}/g)?.reduce(reducer, 0)
}
-export const estimateTxGasCosts = async (
- safeAddress: string,
- to: string,
- data: string,
- tx?: Transaction,
- preApprovingOwner?: string,
-): Promise => {
+interface ErrorDataJson extends JSON {
+ originalError?: {
+ data?: string
+ }
+ data?: string
+}
+
+const getJSONOrNullFromString = (stringInput: string): ErrorDataJson | null => {
try {
- const web3 = getWeb3()
- const from = await getAccountFrom(web3)
-
- if (!from) {
- return 0
- }
-
- const safeInstance = (new web3.eth.Contract(GnosisSafeSol.abi as AbiItem[], safeAddress) as unknown) as GnosisSafe
- const nonce = await safeInstance.methods.nonce().call()
- const threshold = await safeInstance.methods.getThreshold().call()
- const isExecution = tx?.confirmations.size === Number(threshold) || !!preApprovingOwner || threshold === '1'
-
- let txData
- if (isExecution) {
- // https://docs.gnosis.io/safe/docs/docs5/#pre-validated-signatures
- const signatures = tx?.confirmations
- ? generateSignaturesFromTxConfirmations(tx.confirmations, preApprovingOwner)
- : `0x000000000000000000000000${from.replace(
- EMPTY_DATA,
- '',
- )}000000000000000000000000000000000000000000000000000000000000000001`
- txData = await safeInstance.methods
- .execTransaction(
- to,
- tx?.value || 0,
- data,
- CALL,
- tx?.safeTxGas || 0,
- 0,
- 0,
- ZERO_ADDRESS,
- ZERO_ADDRESS,
- signatures,
- )
- .encodeABI()
- } else {
- const txHash = await safeInstance.methods
- .getTransactionHash(to, tx?.value || 0, data, CALL, 0, 0, 0, ZERO_ADDRESS, ZERO_ADDRESS, nonce)
- .call({
- from,
- })
- txData = await safeInstance.methods.approveHash(txHash).encodeABI()
- }
-
- const gas = await calculateGasOf(txData, from, safeAddress)
- const gasPrice = await calculateGasPrice()
-
- return gas * parseInt(gasPrice, 10)
- } catch (err) {
- console.error('Error while estimating transaction execution gas costs:')
- console.error(err)
-
- return 10000
+ return JSON.parse(stringInput)
+ } catch (error) {
+ return null
}
}
// Parses the result from the error message (GETH, OpenEthereum/Parity and Nethermind) and returns the data value
export const getDataFromNodeErrorMessage = (errorMessage: string): string | undefined => {
+ // Replace illegal characters that often comes within the error string (like � for example)
+ // https://stackoverflow.com/questions/12754256/removing-invalid-characters-in-javascript
+ const normalizedErrorString = errorMessage.replace(/\uFFFD/g, '')
+
// Extracts JSON object from the error message
- const [, ...error] = errorMessage.split('\n')
+ const [, ...error] = normalizedErrorString.split('\n')
+
try {
- const errorAsJSON = JSON.parse(error.join(''))
+ const errorAsString = error.join('')
+ const errorAsJSON = getJSONOrNullFromString(errorAsString)
+
+ // Trezor wallet returns the error not as an JSON object but directly as string
+ if (!errorAsJSON) {
+ return errorAsString.length ? errorAsString : undefined
+ }
// For new GETH nodes they will return the data as error in the format:
// {
@@ -130,7 +88,7 @@ export const getDataFromNodeErrorMessage = (errorMessage: string): string | unde
}
}
-const getGasEstimationTxResponse = async (txConfig: {
+export const getGasEstimationTxResponse = async (txConfig: {
to: string
from: string
data: string
@@ -190,8 +148,7 @@ const calculateMinimumGasForTransaction = async (
return 0
}
-export const estimateSafeTxGas = async (
- safe: GnosisSafe | undefined,
+export const estimateGasForTransactionCreation = async (
safeAddress: string,
data: string,
to: string,
@@ -199,10 +156,7 @@ export const estimateSafeTxGas = async (
operation: number,
): Promise => {
try {
- let safeInstance = safe
- if (!safeInstance) {
- safeInstance = await getGnosisSafeInstanceAt(safeAddress)
- }
+ const safeInstance = await getGnosisSafeInstanceAt(safeAddress)
const estimateData = safeInstance.methods.requiredTxGas(to, valueInWei, data, operation).encodeABI()
const gasEstimationResponse = await getGasEstimationTxResponse({
@@ -214,7 +168,7 @@ export const estimateSafeTxGas = async (
const txGasEstimation = gasEstimationResponse + 10000
// 21000 - additional gas costs (e.g. base tx costs, transfer costs)
- const dataGasEstimation = estimateDataGasCosts(estimateData) + 21000
+ const dataGasEstimation = parseRequiredTxGasResponse(estimateData) + 21000
const additionalGasBatches = [0, 10000, 20000, 40000, 80000, 160000, 320000, 640000, 1280000, 2560000, 5120000]
return await calculateMinimumGasForTransaction(
@@ -225,7 +179,102 @@ export const estimateSafeTxGas = async (
dataGasEstimation,
)
} catch (error) {
- console.error('Error calculating tx gas estimation', error)
- return 0
+ console.info('Error calculating tx gas estimation', error.message)
+ throw error
}
}
+
+type TransactionExecutionEstimationProps = {
+ txData: string
+ safeAddress: string
+ txRecipient: string
+ txConfirmations?: List
+ txAmount: string
+ operation: number
+ gasPrice: string
+ gasToken: string
+ refundReceiver: string // Address of receiver of gas payment (or 0 if tx.origin).
+ safeTxGas: number
+ from: string
+ approvalAndExecution?: boolean
+}
+
+export const estimateGasForTransactionExecution = async ({
+ safeAddress,
+ txRecipient,
+ txConfirmations,
+ txAmount,
+ txData,
+ operation,
+ gasPrice,
+ gasToken,
+ refundReceiver,
+ safeTxGas,
+ approvalAndExecution,
+}: TransactionExecutionEstimationProps): Promise => {
+ const safeInstance = await getGnosisSafeInstanceAt(safeAddress)
+ try {
+ if (approvalAndExecution) {
+ console.info(`Estimating transaction success for execution & approval...`)
+ // @todo (agustin) once we solve the problem with the preApprovingOwner, we need to use the method bellow (execTransaction) with sigs = generateSignaturesFromTxConfirmations(txConfirmations,from)
+ const gasEstimation = await estimateGasForTransactionCreation(
+ safeAddress,
+ txData,
+ txRecipient,
+ txAmount,
+ operation,
+ )
+ console.info(`Gas estimation successfully finished with gas amount: ${gasEstimation}`)
+ return gasEstimation
+ }
+ const sigs = generateSignaturesFromTxConfirmations(txConfirmations)
+ console.info(`Estimating transaction success for with gas amount: ${safeTxGas}...`)
+ await safeInstance.methods
+ .execTransaction(txRecipient, txAmount, txData, operation, safeTxGas, 0, gasPrice, gasToken, refundReceiver, sigs)
+ .call()
+
+ console.info(`Gas estimation successfully finished with gas amount: ${safeTxGas}`)
+ return safeTxGas
+ } catch (error) {
+ throw new Error(`Gas estimation failed with gas amount: ${safeTxGas}`)
+ }
+}
+
+type TransactionApprovalEstimationProps = {
+ txData: string
+ safeAddress: string
+ txRecipient: string
+ txAmount: string
+ operation: number
+ from: string
+ isOffChainSignature: boolean
+}
+
+export const estimateGasForTransactionApproval = async ({
+ safeAddress,
+ txRecipient,
+ txAmount,
+ txData,
+ operation,
+ from,
+ isOffChainSignature,
+}: TransactionApprovalEstimationProps): Promise => {
+ if (isOffChainSignature) {
+ return 0
+ }
+
+ const safeInstance = await getGnosisSafeInstanceAt(safeAddress)
+
+ const nonce = await safeInstance.methods.nonce().call()
+ const txHash = await safeInstance.methods
+ .getTransactionHash(txRecipient, txAmount, txData, operation, 0, 0, 0, ZERO_ADDRESS, ZERO_ADDRESS, nonce)
+ .call({
+ from,
+ })
+ const approveTransactionTxData = await safeInstance.methods.approveHash(txHash).encodeABI()
+ return calculateGasOf({
+ data: approveTransactionTxData,
+ from,
+ to: safeAddress,
+ })
+}
diff --git a/src/logic/safe/transactions/send.ts b/src/logic/safe/transactions/send.ts
index 67bbab2f..289c8fe3 100644
--- a/src/logic/safe/transactions/send.ts
+++ b/src/logic/safe/transactions/send.ts
@@ -30,10 +30,7 @@ export const getTransactionHash = async ({
return txHash
}
-export const getApprovalTransaction = async (
- safeInstance: GnosisSafe,
- txHash: string,
-): Promise> => {
+export const getApprovalTransaction = (safeInstance: GnosisSafe, txHash: string): NonPayableTransactionObject => {
try {
return safeInstance.methods.approveHash(txHash)
} catch (err) {
diff --git a/src/logic/safe/utils/upgradeSafe.ts b/src/logic/safe/utils/upgradeSafe.ts
index 4f3dea18..53caa747 100644
--- a/src/logic/safe/utils/upgradeSafe.ts
+++ b/src/logic/safe/utils/upgradeSafe.ts
@@ -6,7 +6,6 @@ import {
SAFE_MASTER_COPY_ADDRESS,
getGnosisSafeInstanceAt,
} from 'src/logic/contracts/safeContracts'
-import { DELEGATE_CALL } from 'src/logic/safe/transactions'
import { getWeb3 } from 'src/logic/wallets/getWeb3'
import { MultiSend } from 'src/types/contracts/MultiSend.d'
@@ -49,7 +48,7 @@ export const getEncodedMultiSendCallData = (txs: MultiSendTx[], web3: Web3): str
return encodedMultiSendCallData
}
-export const upgradeSafeToLatestVersion = async (safeAddress: string, createTransaction): Promise => {
+export const getUpgradeSafeTransactionHash = async (safeAddress: string): Promise => {
const safeInstance = await getGnosisSafeInstanceAt(safeAddress)
const fallbackHandlerTxData = safeInstance.methods.setFallbackHandler(DEFAULT_FALLBACK_HANDLER_ADDRESS).encodeABI()
const updateSafeTxData = safeInstance.methods.changeMasterCopy(SAFE_MASTER_COPY_ADDRESS).encodeABI()
@@ -69,17 +68,5 @@ export const upgradeSafeToLatestVersion = async (safeAddress: string, createTran
]
const web3 = getWeb3()
- const encodeMultiSendCallData = getEncodedMultiSendCallData(txs, web3)
- createTransaction({
- safeAddress,
- to: MULTI_SEND_ADDRESS,
- valueInWei: 0,
- txData: encodeMultiSendCallData,
- notifiedTransaction: 'STANDARD_TX',
- enqueueSnackbar: () => {},
- closeSnackbar: () => {},
- operation: DELEGATE_CALL,
- })
-
- return
+ return getEncodedMultiSendCallData(txs, web3)
}
diff --git a/src/logic/wallets/ethTransactions.ts b/src/logic/wallets/ethTransactions.ts
index 3067de09..87a702f2 100644
--- a/src/logic/wallets/ethTransactions.ts
+++ b/src/logic/wallets/ethTransactions.ts
@@ -50,10 +50,16 @@ export const calculateGasPrice = async (): Promise => {
}
}
-export const calculateGasOf = async (data: string, from: string, to: string): Promise => {
+export const calculateGasOf = async (txConfig: {
+ to: string
+ from: string
+ data: string
+ gasPrice?: number
+ gas?: number
+}): Promise => {
const web3 = getWeb3()
try {
- const gas = await web3.eth.estimateGas({ data, from, to })
+ const gas = await web3.eth.estimateGas(txConfig)
return gas * 2
} catch (err) {
diff --git a/src/routes/open/components/Layout.tsx b/src/routes/open/components/Layout.tsx
index 45385f05..2bce3846 100644
--- a/src/routes/open/components/Layout.tsx
+++ b/src/routes/open/components/Layout.tsx
@@ -17,7 +17,7 @@ import {
getOwnerAddressBy,
getOwnerNameBy,
} from 'src/routes/open/components/fields'
-import Welcome from 'src/routes/welcome/components/Layout'
+import { WelcomeLayout } from 'src/routes/welcome/components/index'
import { history } from 'src/store'
import { secondary, sm } from 'src/theme/variables'
import { networkSelector, providerNameSelector, userAccountSelector } from 'src/logic/wallets/store/selectors'
@@ -138,7 +138,7 @@ export const Layout = (props: LayoutProps): React.ReactElement => {
) : (
-
+
)}
>
)
diff --git a/src/routes/safe/components/Apps/components/AppFrame.tsx b/src/routes/safe/components/Apps/components/AppFrame.tsx
index be761418..28c47ff0 100644
--- a/src/routes/safe/components/Apps/components/AppFrame.tsx
+++ b/src/routes/safe/components/Apps/components/AppFrame.tsx
@@ -32,7 +32,7 @@ import { LoadingContainer } from 'src/components/LoaderContainer/index'
import { TIMEOUT } from 'src/utils/constants'
import { web3ReadOnly } from 'src/logic/wallets/getWeb3'
-import ConfirmTransactionModal from '../components/ConfirmTransactionModal'
+import { ConfirmTransactionModal } from '../components/ConfirmTransactionModal'
import { useIframeMessageHandler } from '../hooks/useIframeMessageHandler'
import { useLegalConsent } from '../hooks/useLegalConsent'
import LegalDisclaimer from './LegalDisclaimer'
diff --git a/src/routes/safe/components/Apps/components/ConfirmTransactionModal.tsx b/src/routes/safe/components/Apps/components/ConfirmTransactionModal.tsx
index 80eb88de..fd199a37 100644
--- a/src/routes/safe/components/Apps/components/ConfirmTransactionModal.tsx
+++ b/src/routes/safe/components/Apps/components/ConfirmTransactionModal.tsx
@@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react'
-import { Icon, Text, Title, GenericModal, ModalFooterConfirmation } from '@gnosis.pm/safe-react-components'
+import { GenericModal, Icon, ModalFooterConfirmation, Text, Title } from '@gnosis.pm/safe-react-components'
import { Transaction } from '@gnosis.pm/safe-apps-sdk-v1'
import styled from 'styled-components'
import { useDispatch } from 'react-redux'
@@ -20,11 +20,13 @@ import createTransaction from 'src/logic/safe/store/actions/createTransaction'
import { MULTI_SEND_ADDRESS } from 'src/logic/contracts/safeContracts'
import { DELEGATE_CALL, TX_NOTIFICATION_TYPES } from 'src/logic/safe/transactions'
import { encodeMultiSendCall } from 'src/logic/safe/transactions/multisend'
-import { estimateSafeTxGas } from 'src/logic/safe/transactions/gas'
import GasEstimationInfo from './GasEstimationInfo'
import { getNetworkInfo } from 'src/config'
import { TransactionParams } from './AppFrame'
+import { EstimationStatus, useEstimateTransactionGas } from 'src/logic/hooks/useEstimateTransactionGas'
+import Row from 'src/components/layout/Row'
+import { TransactionFees } from 'src/components/TransactionsFees'
const isTxValid = (t: Transaction): boolean => {
if (!['string', 'number'].includes(typeof t.value)) {
@@ -67,6 +69,10 @@ const StyledTextBox = styled(TextBox)`
max-width: 444px;
`
+const Container = styled.div`
+ max-width: 480px;
+`
+
type OwnProps = {
isOpen: boolean
app: SafeApp
@@ -82,7 +88,7 @@ type OwnProps = {
const { nativeCoin } = getNetworkInfo()
-const ConfirmTransactionModal = ({
+export const ConfirmTransactionModal = ({
isOpen,
app,
txs,
@@ -95,32 +101,25 @@ const ConfirmTransactionModal = ({
onTxReject,
}: OwnProps): React.ReactElement | null => {
const [estimatedSafeTxGas, setEstimatedSafeTxGas] = useState(0)
- const [estimatingGas, setEstimatingGas] = useState(false)
+
+ const {
+ gasEstimation,
+ isOffChainSignature,
+ isCreation,
+ isExecution,
+ gasCostFormatted,
+ txEstimationExecutionStatus,
+ } = useEstimateTransactionGas({
+ txData: encodeMultiSendCall(txs),
+ txRecipient: MULTI_SEND_ADDRESS,
+ operation: DELEGATE_CALL,
+ })
useEffect(() => {
- const estimateGas = async () => {
- try {
- setEstimatingGas(true)
- const safeTxGas = await estimateSafeTxGas(
- undefined,
- safeAddress,
- encodeMultiSendCall(txs),
- MULTI_SEND_ADDRESS,
- '0',
- DELEGATE_CALL,
- )
-
- setEstimatedSafeTxGas(safeTxGas)
- } catch (err) {
- console.error(err)
- } finally {
- setEstimatingGas(false)
- }
- }
if (params?.safeTxGas) {
- estimateGas()
+ setEstimatedSafeTxGas(gasEstimation)
}
- }, [params, safeAddress, txs])
+ }, [params, gasEstimation])
const dispatch = useDispatch()
if (!isOpen) {
@@ -173,7 +172,7 @@ const ConfirmTransactionModal = ({
>
) : (
- <>
+
{txs.map((tx, index) => (
@@ -205,11 +204,20 @@ const ConfirmTransactionModal = ({
)}
- >
+