Skip to content
This repository was archived by the owner on Nov 10, 2023. It is now read-only.
6 changes: 4 additions & 2 deletions src/components/AddressInfo/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React from 'react'

import { getNetworkInfo } from 'src/config'
import CopyBtn from 'src/components/CopyBtn'
import EtherscanBtn from 'src/components/EtherscanBtn'
import Identicon from 'src/components/Identicon'
Expand Down Expand Up @@ -42,6 +42,8 @@ interface Props {
ethBalance?: string
}

const { nativeCoin } = getNetworkInfo()

const AddressInfo = ({ ethBalance, safeAddress, safeName }: Props): React.ReactElement => {
return (
<Wrapper>
Expand All @@ -64,7 +66,7 @@ const AddressInfo = ({ ethBalance, safeAddress, safeName }: Props): React.ReactE
{ethBalance && (
<StyledBlock>
<Paragraph noMargin>
Balance: <Bold data-testid="current-eth-balance">{`${ethBalance} ETH`}</Bold>
Balance: <Bold data-testid="current-eth-balance">{`${ethBalance} ${nativeCoin.symbol}`}</Bold>
</Paragraph>
</StyledBlock>
)}
Expand Down
2 changes: 1 addition & 1 deletion src/components/AppLayout/Sidebar/SafeHeader/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {

import FlexSpacer from 'src/components/FlexSpacer'
import { getExplorerInfo, getNetworkInfo } from 'src/config'
import { NetworkSettings } from 'src/config/networks/network'
import { NetworkSettings } from 'src/config/networks/network.d'
import { border, fontColor } from 'src/theme/variables'

export const TOGGLE_SIDEBAR_BTN_TESTID = 'TOGGLE_SIDEBAR_BTN'
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import bn from 'bignumber.js'
import { List, Map } from 'immutable'

import { getNetworkInfo } from 'src/config'
import generateBatchRequests from 'src/logic/contracts/generateBatchRequests'
import { ALTERNATIVE_TOKEN_ABI } from 'src/logic/tokens/utils/alternativeAbi'
import { web3ReadOnly } from 'src/logic/wallets/getWeb3'
Expand Down Expand Up @@ -43,6 +43,7 @@ const buildIncomingTransactionFrom = ([tx, symbol, decimals, fee]: [

const batchIncomingTxsTokenDataRequest = (txs: IncomingTxServiceModel[]) => {
const batch = new web3ReadOnly.BatchRequest()
const { nativeCoin } = getNetworkInfo()
Copy link
Contributor

@Agupane Agupane Oct 13, 2020

Choose a reason for hiding this comment

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

Please check my comment about getNetworkInfo

Copy link
Collaborator

Choose a reason for hiding this comment

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

I think it's a good point. But this should be added in another PR


const whenTxsValues = txs.map((tx) => {
const methods = [
Expand All @@ -66,8 +67,8 @@ const batchIncomingTxsTokenDataRequest = (txs: IncomingTxServiceModel[]) => {
return Promise.all(whenTxsValues).then((txsValues) =>
txsValues.map(([tx, symbol, decimals, { gasPrice }, { gasUsed }]) => [
tx,
symbol === null ? 'ETH' : symbol,
decimals === null ? '18' : decimals,
symbol === null ? nativeCoin.symbol : symbol,
decimals === null ? nativeCoin.decimals : decimals,
new bn(gasPrice).times(gasUsed),
]),
)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { List, Map } from 'immutable'

import { getNetworkInfo } from 'src/config'
import { TOKEN_REDUCER_ID } from 'src/logic/tokens/store/reducer/tokens'
import {
getERC20DecimalsAndSymbol,
Expand Down Expand Up @@ -100,12 +100,13 @@ export const getRefundParams = async (
tx: TxServiceModel,
tokenInfo: (string) => Promise<{ decimals: number; symbol: string } | null>,
): Promise<RefundParams | null> => {
const { nativeCoin } = getNetworkInfo()
const txGasPrice = Number(tx.gasPrice)
let refundParams: RefundParams | null = null

if (txGasPrice > 0) {
let refundSymbol = 'ETH'
let refundDecimals = 18
let refundSymbol = nativeCoin.symbol
let refundDecimals = nativeCoin.decimals

if (tx.gasToken !== ZERO_ADDRESS) {
const gasToken = await tokenInfo(tx.gasToken)
Expand Down Expand Up @@ -243,6 +244,7 @@ export const buildTx = async ({
txCode,
}: BuildTx): Promise<Transaction> => {
const safeAddress = safe.address
const { nativeCoin } = getNetworkInfo()
const isModifySettingsTx = isModifySettingsTransaction(tx, safeAddress)
const isTxCancelled = isTransactionCancelled(tx, outgoingTxs, cancellationTxs)
const isSendERC721Tx = isSendERC721Transaction(tx, txCode, knownTokens)
Expand All @@ -255,8 +257,8 @@ export const buildTx = async ({
const decodedParams = getDecodedParams(tx)
const confirmations = getConfirmations(tx)

let tokenDecimals = 18
let tokenSymbol = 'ETH'
let tokenDecimals = nativeCoin.decimals
let tokenSymbol = nativeCoin.symbol
try {
if (isSendERC20Tx) {
const { decimals, symbol } = await getERC20DecimalsAndSymbol(tx.to)
Expand Down
28 changes: 28 additions & 0 deletions src/logic/tokens/utils/__tests__/tokenHelpers.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { makeToken } from 'src/logic/tokens/store/model/token'
import { getERC20DecimalsAndSymbol, isERC721Contract, isTokenTransfer } from 'src/logic/tokens/utils/tokenHelpers'
import { getMockedTxServiceModel } from 'src/test/utils/safeHelper'
import { fromTokenUnit, toTokenUnit } from 'src/logic/tokens/utils/humanReadableValue'

describe('isTokenTransfer', () => {
const safeAddress = '0xdfA693da0D16F5E7E78FdCBeDe8FC6eBEa44f1Cf'
Expand Down Expand Up @@ -171,4 +172,31 @@ describe('isERC721Contract', () => {
expect(result).toEqual(expectedResult)
expect(standardContractSpy).toHaveBeenCalled()
})
it('It should return the right conversion from unit to token', () => {
// given
const decimals = Number(18)

const expectedResult = '0.000000003'
const ESTIMATED_GAS_COST = 3e9 // 3 Gwei

// when
const gasCosts = fromTokenUnit(ESTIMATED_GAS_COST, decimals)

// then
expect(gasCosts).toEqual(expectedResult)
})

it('It should return the right conversion from token to unit', () => {
// given
const decimals = Number(18)

const expectedResult = '300000000000000000'
const VALUE = 0.3

// when
const txValue = toTokenUnit(VALUE, decimals)

// then
expect(txValue).toEqual(expectedResult)
})
})
14 changes: 14 additions & 0 deletions src/logic/tokens/utils/humanReadableValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,17 @@ import { BigNumber } from 'bignumber.js'
export const humanReadableValue = (value: number | string, decimals = 18): string => {
return new BigNumber(value).times(`1e-${decimals}`).toFixed()
}

export const fromTokenUnit = (amount: number | string, decimals: string | number): string =>
new BigNumber(amount).times(`1e-${decimals}`).toFixed()

export const toTokenUnit = (amount: number | string, decimals: string | number): string => {
const amountBN = new BigNumber(amount).times(`1e${decimals}`)
const [, amountDecimalPlaces] = amount.toString().split('.')

if (amountDecimalPlaces?.length >= +decimals) {
return amountBN.toFixed(+decimals, BigNumber.ROUND_DOWN)
}

return amountBN.toFixed()
}
10 changes: 3 additions & 7 deletions src/logic/tokens/utils/tokenHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import logo from 'src/assets/icons/icon_etherTokens.svg'
import { getNetworkInfo } from 'src/config'
import generateBatchRequests from 'src/logic/contracts/generateBatchRequests'
import {
getStandardTokenContract,
Expand All @@ -12,16 +12,12 @@ import { isEmptyData } from 'src/logic/safe/store/actions/transactions/utils/tra
import { TxServiceModel } from 'src/logic/safe/store/actions/transactions/fetchTransactions/loadOutgoingTransactions'
import { Map } from 'immutable'

export const ETH_ADDRESS = '0x000'
export const SAFE_TRANSFER_FROM_WITHOUT_DATA_HASH = '42842e0e'

export const getEthAsToken = (balance: string | number): Token => {
const { nativeCoin } = getNetworkInfo()
return makeToken({
address: ETH_ADDRESS,
name: 'Ether',
symbol: 'ETH',
decimals: 18,
logoUri: logo,
...nativeCoin,
balance,
})
}
Expand Down
13 changes: 6 additions & 7 deletions src/routes/open/components/ReviewInformation/index.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import TableContainer from '@material-ui/core/TableContainer'
import classNames from 'classnames'
import React, { useEffect, useState } from 'react'

import { fromTokenUnit } from 'src/logic/tokens/utils/humanReadableValue'
import { getNetworkInfo } from 'src/config'
import CopyBtn from 'src/components/CopyBtn'
import EtherscanBtn from 'src/components/EtherscanBtn'
import Identicon from 'src/components/Identicon'
Expand All @@ -13,7 +14,6 @@ import Row from 'src/components/layout/Row'
import OpenPaper from 'src/components/Stepper/OpenPaper'
import { estimateGasForDeployingSafe } from 'src/logic/contracts/safeContracts'
import { formatAmount } from 'src/logic/tokens/utils/formatAmount'
import { getWeb3 } from 'src/logic/wallets/getWeb3'
import { getAccountsFrom, getNamesFrom } from 'src/routes/open/utils/safeDataExtractor'

import { FIELD_CONFIRMATIONS, FIELD_NAME, getNumOwnersFrom } from '../fields'
Expand All @@ -37,11 +37,10 @@ const ReviewComponent = ({ userAccount, values }: ReviewComponentProps) => {
if (!addresses.length || !numOwners || !userAccount) {
return
}
const web3 = getWeb3()
const { fromWei, toBN } = web3.utils
const estimatedGasCosts = await estimateGasForDeployingSafe(addresses, numOwners, userAccount)
const gasCostsAsEth = fromWei(toBN(estimatedGasCosts), 'ether')
const formattedGasCosts = formatAmount(gasCostsAsEth)
const { nativeCoin } = getNetworkInfo()
const estimatedGasCosts = (await estimateGasForDeployingSafe(addresses, numOwners, userAccount)).toString()
const gasCosts = fromTokenUnit(estimatedGasCosts, nativeCoin.decimals)
const formattedGasCosts = formatAmount(gasCosts)
setGasCosts(formattedGasCosts)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { makeStyles } from '@material-ui/core/styles'
import { useSnackbar } from 'notistack'
import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'

import { fromTokenUnit, toTokenUnit } from 'src/logic/tokens/utils/humanReadableValue'
import { getNetworkInfo } from 'src/config'
import AddressInfo from 'src/components/AddressInfo'
import Block from 'src/components/layout/Block'
import Button from 'src/components/layout/Button'
Expand All @@ -16,7 +17,6 @@ import { TX_NOTIFICATION_TYPES } from 'src/logic/safe/transactions'
import { estimateTxGasCosts } from 'src/logic/safe/transactions/gasNew'
import { formatAmount } from 'src/logic/tokens/utils/formatAmount'
import { getEthAsToken } from 'src/logic/tokens/utils/tokenHelpers'
import { getWeb3 } from 'src/logic/wallets/getWeb3'
import { styles } from 'src/routes/safe/components/Balances/SendModal/screens/ContractInteraction/style'
import Header from 'src/routes/safe/components/Balances/SendModal/screens/ContractInteraction/Header'
import { setImageToPlaceholder } from 'src/routes/safe/components/Balances/utils'
Expand All @@ -40,23 +40,23 @@ type Props = {
tx: TransactionReviewType
}

const { nativeCoin } = getNetworkInfo()

const ContractInteractionReview = ({ onClose, onPrev, tx }: Props): React.ReactElement => {
const { enqueueSnackbar, closeSnackbar } = useSnackbar()
const classes = useStyles()
const dispatch = useDispatch()
const { address: safeAddress } = useSelector(safeSelector) || {}
const [gasCosts, setGasCosts] = useState('< 0.001')

useEffect(() => {
let isCurrent = true

const estimateGas = async (): Promise<void> => {
const { fromWei, toBN } = getWeb3().utils
const txData = tx.data ? tx.data.trim() : ''

const estimatedGasCosts = await estimateTxGasCosts(safeAddress as string, tx.contractAddress as string, txData)
const gasCostsAsEth = fromWei(toBN(estimatedGasCosts), 'ether')
const formattedGasCosts = formatAmount(gasCostsAsEth)
const gasCosts = fromTokenUnit(estimatedGasCosts, nativeCoin.decimals)
const formattedGasCosts = formatAmount(gasCosts)

if (isCurrent) {
setGasCosts(formattedGasCosts)
Expand All @@ -71,11 +71,9 @@ const ContractInteractionReview = ({ onClose, onPrev, tx }: Props): React.ReactE
}, [safeAddress, tx.contractAddress, tx.data])

const submitTx = async () => {
const web3 = getWeb3()
const txRecipient = tx.contractAddress
const txData = tx.data ? tx.data.trim() : ''
const txValue = tx.value ? web3.utils.toWei(tx.value, 'ether') : '0'

const txValue = tx.value ? toTokenUnit(tx.value, nativeCoin.decimals) : '0'
dispatch(
createTransaction({
safeAddress,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { makeStyles } from '@material-ui/core/styles'
import Close from '@material-ui/icons/Close'
import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { fromTokenUnit, toTokenUnit } from 'src/logic/tokens/utils/humanReadableValue'
import { getNetworkInfo } from 'src/config'

import CopyBtn from 'src/components/CopyBtn'
import EtherscanBtn from 'src/components/EtherscanBtn'
Expand All @@ -20,7 +22,6 @@ import { TX_NOTIFICATION_TYPES } from 'src/logic/safe/transactions'
import { estimateTxGasCosts } from 'src/logic/safe/transactions/gasNew'
import { formatAmount } from 'src/logic/tokens/utils/formatAmount'
import { getEthAsToken } from 'src/logic/tokens/utils/tokenHelpers'
import { getWeb3 } from 'src/logic/wallets/getWeb3'
import SafeInfo from 'src/routes/safe/components/Balances/SendModal/SafeInfo'
import { setImageToPlaceholder } from 'src/routes/safe/components/Balances/utils'
import { sm } from 'src/theme/variables'
Expand All @@ -37,22 +38,22 @@ type Props = {

const useStyles = makeStyles(styles)

const { nativeCoin } = getNetworkInfo()

const ReviewCustomTx = ({ onClose, onPrev, tx }: Props): React.ReactElement => {
const classes = useStyles()
const dispatch = useDispatch()
const { address: safeAddress } = useSelector(safeSelector) || {}
const [gasCosts, setGasCosts] = useState<string>('< 0.001')

useEffect(() => {
let isCurrent = true

const estimateGas = async () => {
const { fromWei, toBN } = getWeb3().utils
const txData = tx.data ? tx.data.trim() : ''

const estimatedGasCosts = await estimateTxGasCosts(safeAddress as string, tx.contractAddress as string, txData)
const gasCostsAsEth = fromWei(toBN(estimatedGasCosts), 'ether')
const formattedGasCosts = formatAmount(gasCostsAsEth)
const gasCosts = fromTokenUnit(estimatedGasCosts, nativeCoin.decimals)
const formattedGasCosts = formatAmount(gasCosts)

if (isCurrent) {
setGasCosts(formattedGasCosts)
Expand All @@ -67,10 +68,9 @@ const ReviewCustomTx = ({ onClose, onPrev, tx }: Props): React.ReactElement => {
}, [safeAddress, tx.data, tx.contractAddress])

const submitTx = async (): Promise<void> => {
const web3 = getWeb3()
const txRecipient = tx.contractAddress
const txData = tx.data ? tx.data.trim() : ''
const txValue = tx.value ? web3.utils.toWei(tx.value, 'ether') : '0'
const txValue = tx.value ? toTokenUnit(tx.value, nativeCoin.decimals) : '0'

dispatch(
createTransaction({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ import Close from '@material-ui/icons/Close'
import { withSnackbar } from 'notistack'
import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'

import { fromTokenUnit } from 'src/logic/tokens/utils/humanReadableValue'
import { getNetworkInfo } from 'src/config'
import CopyBtn from 'src/components/CopyBtn'
import EtherscanBtn from 'src/components/EtherscanBtn'
import Identicon from 'src/components/Identicon'
Expand All @@ -27,7 +28,6 @@ import {
} from 'src/logic/tokens/store/actions/fetchTokens'
import { formatAmount } from 'src/logic/tokens/utils/formatAmount'
import { SAFE_TRANSFER_FROM_WITHOUT_DATA_HASH } from 'src/logic/tokens/utils/tokenHelpers'
import { getWeb3 } from 'src/logic/wallets/getWeb3'
import SafeInfo from 'src/routes/safe/components/Balances/SendModal/SafeInfo'
import { setImageToPlaceholder } from 'src/routes/safe/components/Balances/utils'
import { sm } from 'src/theme/variables'
Expand All @@ -37,6 +37,8 @@ import ArrowDown from '../assets/arrow-down.svg'

import { styles } from './style'

const { nativeCoin } = getNetworkInfo()

const useStyles = makeStyles(styles as any)

const ReviewCollectible = ({ closeSnackbar, enqueueSnackbar, onClose, onPrev, tx }) => {
Expand All @@ -55,8 +57,6 @@ const ReviewCollectible = ({ closeSnackbar, enqueueSnackbar, onClose, onPrev, tx
let isCurrent = true

const estimateGas = async () => {
const { fromWei, toBN } = getWeb3().utils

const supportsSafeTransfer = await containsMethodByHash(tx.assetAddress, SAFE_TRANSFER_FROM_WITHOUT_DATA_HASH)
const methodToCall = supportsSafeTransfer ? `0x${SAFE_TRANSFER_FROM_WITHOUT_DATA_HASH}` : 'transfer'
const transferParams = [tx.recipientAddress, tx.nftTokenId]
Expand All @@ -67,8 +67,8 @@ const ReviewCollectible = ({ closeSnackbar, enqueueSnackbar, onClose, onPrev, tx
const txData = tokenInstance.contract.methods[methodToCall](...params).encodeABI()

const estimatedGasCosts = await estimateTxGasCosts(safeAddress as string, tx.recipientAddress, txData)
const gasCostsAsEth = fromWei(toBN(estimatedGasCosts), 'ether')
const formattedGasCosts = formatAmount(gasCostsAsEth)
const gasCosts = fromTokenUnit(estimatedGasCosts, nativeCoin.decimals)
const formattedGasCosts = formatAmount(gasCosts)

if (isCurrent) {
setGasCosts(formattedGasCosts)
Expand Down
Loading