From 250cc09773958295d8b21a5940971300d9bfbb2d Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Wed, 4 Mar 2020 17:35:59 -0300 Subject: [PATCH 01/21] box --- src/assets/IconANT.svg | 56 ++++++++++++++ src/components/Dashboard/CourtStats.js | 86 +++++++++++++++++++--- src/components/Dashboard/Dashboard.js | 7 +- src/components/Dashboard/DashboardStats.js | 9 --- 4 files changed, 137 insertions(+), 21 deletions(-) create mode 100755 src/assets/IconANT.svg delete mode 100644 src/components/Dashboard/DashboardStats.js diff --git a/src/assets/IconANT.svg b/src/assets/IconANT.svg new file mode 100755 index 00000000..639f7298 --- /dev/null +++ b/src/assets/IconANT.svg @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/components/Dashboard/CourtStats.js b/src/components/Dashboard/CourtStats.js index 2600e0d9..448c005a 100644 --- a/src/components/Dashboard/CourtStats.js +++ b/src/components/Dashboard/CourtStats.js @@ -1,18 +1,82 @@ import React from 'react' -import { Box, Distribution } from '@aragon/ui' +import { Box, GU, textStyle, useTheme } from '@aragon/ui' +import IconANJ from '../../assets/IconANJ.svg' +// import { formatUnits, bigNum } from '../../lib/math-utils' +// import LatestActivity from './LatestActivity' +// import CourtStats from './CourtStats' + +// const splitAmount = amount => { +// const [integer, fractional] = amount.split('.') +// return ( +// +// {integer} +// {fractional && ( +// +// .{fractional} +// +// )} +// +// ) +// } const CourtStats = () => { + const theme = useTheme() + const stats = { + title: 'Total Active ANJ', + token: { + symbol: 'ANJ', + value: 101490826, + decimals: 18, + icon: IconANJ, + usdValue: 82501892, + }, + } + return ( - - + + + {stats.title} + +
+ + {stats.token.value} + + ANJ + + {stats.token.symbol} + +
) } diff --git a/src/components/Dashboard/Dashboard.js b/src/components/Dashboard/Dashboard.js index 3776a340..6ce9f9dd 100644 --- a/src/components/Dashboard/Dashboard.js +++ b/src/components/Dashboard/Dashboard.js @@ -11,6 +11,7 @@ import ActivateANJ from './panels/ActivateANJ' import WithdrawANJ from './panels/WithdrawANJ' import DeactivateANJ from './panels/DeactivateANJ' import AppealColateralModule from './AppealColateralModule' +import CourtStats from './CourtStats' import { useWallet } from '../../providers/Wallet' import { DashboardStateProvider } from './DashboardStateProvider' @@ -66,7 +67,11 @@ function Dashboard() { )} {!wallet.account ? ( - + } + secondary={} + invert="horizontal" + /> ) : ( } diff --git a/src/components/Dashboard/DashboardStats.js b/src/components/Dashboard/DashboardStats.js deleted file mode 100644 index bcb55206..00000000 --- a/src/components/Dashboard/DashboardStats.js +++ /dev/null @@ -1,9 +0,0 @@ -import React from 'react' -// import LatestActivity from './LatestActivity' -// import CourtStats from './CourtStats' - -const DashboardStats = () => { - return <>{/* */} -} - -export default DashboardStats From 8e56d711ae9c20a86087bf6eded123a0b2405611 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Thu, 5 Mar 2020 17:51:16 -0300 Subject: [PATCH 02/21] change polling --- src/components/Dashboard/AccountBanner.js | 6 +-- src/components/Dashboard/CourtStats.js | 49 ++++++++++++++++++----- src/hooks/useCourtContracts.js | 6 +-- src/hooks/useCourtStats.js | 2 + 4 files changed, 46 insertions(+), 17 deletions(-) create mode 100644 src/hooks/useCourtStats.js diff --git a/src/components/Dashboard/AccountBanner.js b/src/components/Dashboard/AccountBanner.js index 00e8a754..356a8c31 100644 --- a/src/components/Dashboard/AccountBanner.js +++ b/src/components/Dashboard/AccountBanner.js @@ -6,7 +6,6 @@ import AccountBannerInfo from './AccountBannerInfo' import { useCourtConfig } from '../../providers/CourtConfig' import { useTotalActiveBalancePolling } from '../../hooks/useCourtContracts' import { useJurorFirstTimeANJActivation } from '../../hooks/useANJ' -import { useCourtClock } from '../../providers/CourtClock' import { ACCOUNT_STATUS_JUROR_ACTIVE } from '../../types/account-status-types' import { formatUnits, getPercentageBN, bigNum } from '../../lib/math-utils' @@ -155,7 +154,6 @@ const Wrapper = ({ mainIcon, information }) => { const BannerWithProbability = ({ activeBalance }) => { const theme = useTheme() - const { currentTermId } = useCourtClock() // Calculate juror's active balance and total active balance for current term const { @@ -163,9 +161,7 @@ const BannerWithProbability = ({ activeBalance }) => { amountNotEffective: activeAmountNotEffective, } = activeBalance const activeBalanceCurrentTerm = activeAmount.sub(activeAmountNotEffective) - const totalActiveBalanceCurrentTerm = useTotalActiveBalancePolling( - currentTermId - ) + const totalActiveBalanceCurrentTerm = useTotalActiveBalancePolling() const fetchingTotalBalance = totalActiveBalanceCurrentTerm.eq(bigNum(-1)) const totalPercentage = getPercentageBN( diff --git a/src/components/Dashboard/CourtStats.js b/src/components/Dashboard/CourtStats.js index 448c005a..920ff967 100644 --- a/src/components/Dashboard/CourtStats.js +++ b/src/components/Dashboard/CourtStats.js @@ -42,24 +42,47 @@ const CourtStats = () => { return ( - + + {stats.title} + + + + + + ) +} + +function TokenStats({ token, theme }) { + const { value, icon, symbol, usdValue } = token + return ( + <> +
- {stats.title} - -
- {stats.token.value} + {value} { `} height="20" width="18" - src={stats.token.icon} + src={icon} alt="ANJ" /> - {stats.token.symbol} + {symbol}
- + + ${usdValue} + + ) } diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index 1bf32956..70422887 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -351,7 +351,7 @@ export function useAppealFeeAllowance(owner) { return allowance } -export function useTotalActiveBalancePolling(termId) { +export function useTotalActiveBalancePolling() { const jurorRegistryContract = useCourtContract( CourtModuleType.JurorsRegistry, jurorRegistryAbi @@ -363,7 +363,7 @@ export function useTotalActiveBalancePolling(termId) { const fetchTotalActiveBalance = useCallback(() => { timeoutId.current = setTimeout(() => { return jurorRegistryContract - .totalActiveBalanceAt(termId) + .totalActiveBalance() .then(balance => { setTotalActiveBalance(balance) clearTimeout(timeoutId.current) @@ -374,7 +374,7 @@ export function useTotalActiveBalancePolling(termId) { fetchTotalActiveBalance() }) }, 1000) - }, [jurorRegistryContract, termId]) + }, [jurorRegistryContract]) useEffect(() => { fetchTotalActiveBalance() diff --git a/src/hooks/useCourtStats.js b/src/hooks/useCourtStats.js new file mode 100644 index 00000000..d4a2ef57 --- /dev/null +++ b/src/hooks/useCourtStats.js @@ -0,0 +1,2 @@ +const COURT_METRICS = [{}] +function useCourtStats() {} From 8ad37ac76eb9f09bc6c06ea7e1488eeb4dc15fd4 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Tue, 10 Mar 2020 11:19:55 -0300 Subject: [PATCH 03/21] stats --- src/abi/JurorRegistry.json | 5 +- src/components/Dashboard/AccountBanner.js | 9 ++- src/components/Dashboard/CourtStats.js | 9 ++- src/endpoints.js | 4 ++ src/hooks/useCourtContracts.js | 70 +++++++++++++++++++++-- src/hooks/useCourtStats.js | 57 +++++++++++++++++- src/lib/web3-utils.js | 10 +++- src/networks.js | 17 ++++++ src/types/court-module-types.js | 2 +- src/utils/known-tokens.js | 16 ++++++ src/web3-contracts.js | 6 ++ 11 files changed, 191 insertions(+), 14 deletions(-) diff --git a/src/abi/JurorRegistry.json b/src/abi/JurorRegistry.json index 10276289..8f713a4f 100644 --- a/src/abi/JurorRegistry.json +++ b/src/abi/JurorRegistry.json @@ -2,5 +2,8 @@ "function activate(uint256 _amount) external", "function deactivate(uint256 _amount) external", "function unstake(uint256 _amount, bytes _data) external", - "function totalActiveBalanceAt(uint64 _termId) external view returns (uint256)" + "function totalActiveBalance() external view returns (uint256)", + "function totalActiveBalanceAt(uint64 _termId) external view returns (uint256)", + "function totalStaked() external view returns (uint256)" + ] diff --git a/src/components/Dashboard/AccountBanner.js b/src/components/Dashboard/AccountBanner.js index 356a8c31..58991c96 100644 --- a/src/components/Dashboard/AccountBanner.js +++ b/src/components/Dashboard/AccountBanner.js @@ -2,7 +2,7 @@ import React from 'react' import { CircleGraph, GU, Help, LoadingRing, useTheme } from '@aragon/ui' import AccountBannerInfo from './AccountBannerInfo' - +import { useCourtClock } from '../../providers/CourtClock' import { useCourtConfig } from '../../providers/CourtConfig' import { useTotalActiveBalancePolling } from '../../hooks/useCourtContracts' import { useJurorFirstTimeANJActivation } from '../../hooks/useANJ' @@ -154,14 +154,17 @@ const Wrapper = ({ mainIcon, information }) => { const BannerWithProbability = ({ activeBalance }) => { const theme = useTheme() - + const { currentTermId } = useCourtClock() // Calculate juror's active balance and total active balance for current term const { amount: activeAmount, amountNotEffective: activeAmountNotEffective, } = activeBalance const activeBalanceCurrentTerm = activeAmount.sub(activeAmountNotEffective) - const totalActiveBalanceCurrentTerm = useTotalActiveBalancePolling() + const totalActiveBalanceCurrentTerm = useTotalActiveBalancePolling( + currentTermId + ) + console.log('activeeee ', totalActiveBalanceCurrentTerm) const fetchingTotalBalance = totalActiveBalanceCurrentTerm.eq(bigNum(-1)) const totalPercentage = getPercentageBN( diff --git a/src/components/Dashboard/CourtStats.js b/src/components/Dashboard/CourtStats.js index 920ff967..f7d4d7a3 100644 --- a/src/components/Dashboard/CourtStats.js +++ b/src/components/Dashboard/CourtStats.js @@ -1,6 +1,7 @@ import React from 'react' import { Box, GU, textStyle, useTheme } from '@aragon/ui' import IconANJ from '../../assets/IconANJ.svg' +import useCourtStats from '../../hooks/useCourtStats' // import { formatUnits, bigNum } from '../../lib/math-utils' // import LatestActivity from './LatestActivity' // import CourtStats from './CourtStats' @@ -27,7 +28,7 @@ import IconANJ from '../../assets/IconANJ.svg' // ) // } -const CourtStats = () => { +const CourtStats = React.memo(function CourtStats() { const theme = useTheme() const stats = { title: 'Total Active ANJ', @@ -40,6 +41,10 @@ const CourtStats = () => { }, } + const cstats = useCourtStats() + + console.log('court stats ', cstats) + return (
{
) -} +}) function TokenStats({ token, theme }) { const { value, icon, symbol, usdValue } = token diff --git a/src/endpoints.js b/src/endpoints.js index 21443ede..fb050b57 100644 --- a/src/endpoints.js +++ b/src/endpoints.js @@ -1,4 +1,5 @@ import environment from './environment' +// import { networkConfigs } from './networks' import { isLocalOrUnknownNetwork, getNetworkName } from './lib/web3-utils' @@ -18,6 +19,9 @@ export const IPFS_ENDPOINT = isLocalOrUnknownNetwork(CHAIN_ID) const GRAPH_API_PATH = '/subgraphs/name/aragon/aragon-court' +// export const ETH_NODE = +// networkConfigs[getNetworkName(environment('CHAIN_ID'))].nodes.defaultEth + function getAPIBase() { return isLocalOrUnknownNetwork(CHAIN_ID) ? [GRAPH_API_BASE_HTTP_LOCAL, GRAPH_API_BASE_WS_LOCAL] diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index 70422887..ff0a6a64 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -1,6 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react' -import { useContract } from '../web3-contracts' +import { useContract, useContractReadOnly } from '../web3-contracts' import { useCourtConfig } from '../providers/CourtConfig' import { CourtModuleType } from '../types/court-module-types' @@ -59,6 +59,14 @@ function useCourtContract(moduleType, abi) { return useContract(contractAddress, abi) } +function useCourtContractReadOnly(moduleType, abi) { + const { modules } = useCourtConfig() + + const contractAddress = getModuleAddress(modules, moduleType) + + return useContractReadOnly(contractAddress, abi) +} + /** * All ANJ interactions * @returns {Object} all available functions around ANJ balances @@ -351,7 +359,7 @@ export function useAppealFeeAllowance(owner) { return allowance } -export function useTotalActiveBalancePolling() { +export function useTotalActiveBalancePolling(termId) { const jurorRegistryContract = useCourtContract( CourtModuleType.JurorsRegistry, jurorRegistryAbi @@ -363,7 +371,7 @@ export function useTotalActiveBalancePolling() { const fetchTotalActiveBalance = useCallback(() => { timeoutId.current = setTimeout(() => { return jurorRegistryContract - .totalActiveBalance() + .totalActiveBalanceAt(termId) .then(balance => { setTotalActiveBalance(balance) clearTimeout(timeoutId.current) @@ -374,7 +382,7 @@ export function useTotalActiveBalancePolling() { fetchTotalActiveBalance() }) }, 1000) - }, [jurorRegistryContract]) + }, [jurorRegistryContract, termId]) useEffect(() => { fetchTotalActiveBalance() @@ -384,3 +392,57 @@ export function useTotalActiveBalancePolling() { return totalActiveBalance } +export function useTotalANTStaked() { + const [totalANTStaked, setTotalANTStaked] = useState(bigNum(-1)) + + const jurorRegistryContract = useCourtContractReadOnly( + CourtModuleType.JurorsRegistry, + jurorRegistryAbi + ) + useEffect(() => { + if (!jurorRegistryContract) { + return + } + const getTotalANTStaked = async () => { + retryMax(() => jurorRegistryContract.totalStaked()) + .then(totalStaked => { + setTotalANTStaked(totalStaked) + }) + .catch(err => { + console.error(`Error fetching ANT staked: ${err}`) + }) + } + + getTotalANTStaked() + }, [jurorRegistryContract]) + + return totalANTStaked +} + +export function useTotalActiveBalance() { + const jurorRegistryContract = useCourtContract( + CourtModuleType.JurorsRegistry, + jurorRegistryAbi + ) + + const [totalActiveBalance, setTotalActiveBalance] = useState(bigNum(-1)) + + useEffect(() => { + if (!jurorRegistryContract) { + return + } + const getTotalActiveBalance = async () => { + retryMax(() => jurorRegistryContract.totalActiveBalance()) + .then(totalActive => { + setTotalActiveBalance(totalActive) + }) + .catch(err => { + console.error(`Error fetching ANT staked: ${err}`) + }) + } + + getTotalActiveBalance() + }, [jurorRegistryContract]) + + return totalActiveBalance +} diff --git a/src/hooks/useCourtStats.js b/src/hooks/useCourtStats.js index d4a2ef57..676f54b5 100644 --- a/src/hooks/useCourtStats.js +++ b/src/hooks/useCourtStats.js @@ -1,2 +1,55 @@ -const COURT_METRICS = [{}] -function useCourtStats() {} +import { useMemo, useEffect, useState } from 'react' +import { useTotalActiveBalance, useTotalANTStaked } from './useCourtContracts' +import { getKnownToken } from '../utils/known-tokens' +import { bigNum } from '../lib/math-utils' + +const COURT_STATS = [ + { + label: 'Total Active ANJ', + token: getKnownToken('ANJ'), + }, + { + label: 'Total Staked ANT', + token: getKnownToken('ANT'), + }, + // { label: 'Total Active Jurors' }, +] + +function useCourtStats() { + const [fetching, setFetching] = useState(true) + + const ANJActiveBalance = useTotalActiveBalance() + + const ANTTotalStake = useTotalANTStaked() + + const ANJActiveBalanceKey = ANJActiveBalance.toString() + const ANTTotalStakeKey = ANTTotalStake.toString() + + useEffect(() => { + console.log('useEffect') + if (!ANJActiveBalance.eq(bigNum(-1)) && !ANTTotalStake.eq(bigNum(-1))) { + setFetching(false) + } + console.log('fetching') + }, [ANJActiveBalanceKey, ANTTotalStakeKey]) // eslint-disable-line react-hooks/exhaustive-deps + + return useMemo(() => { + console.log('return ') + if (fetching) { + return [null, true] + } + + const statsData = [ANJActiveBalance, ANTTotalStake] + return [ + ...COURT_STATS.map((stat, index) => { + return { + ...stat, + value: statsData[index], + } + }), + false, + ] + }, [ANJActiveBalanceKey, ANTTotalStakeKey, fetching]) // eslint-disable-line react-hooks/exhaustive-deps +} + +export default useCourtStats diff --git a/src/lib/web3-utils.js b/src/lib/web3-utils.js index 0dd2f988..d59a4009 100644 --- a/src/lib/web3-utils.js +++ b/src/lib/web3-utils.js @@ -1,11 +1,19 @@ import env from '../environment' +import { ethers } from 'ethers' import { solidityKeccak256, id as keccak256 } from 'ethers/utils' - +// import { ETH_NODE } from '../endpoints' +import { networkConfigs } from '../networks' export const soliditySha3 = solidityKeccak256 export const hash256 = keccak256 export const DEFAULT_LOCAL_CHAIN = 'rpc' export const ETH_FAKE_ADDRESS = `0x${''.padEnd(40, '0')}` +export function getWeb3Provider() { + const ethEndpoint = + networkConfigs[getNetworkName(env('CHAIN_ID'))].nodes.defaultEth + return new ethers.providers.JsonRpcProvider(ethEndpoint) +} + export function getFunctionSignature(func) { return keccak256(func).slice(0, 10) } diff --git a/src/networks.js b/src/networks.js index aa1bff23..4e081dd8 100644 --- a/src/networks.js +++ b/src/networks.js @@ -16,3 +16,20 @@ export const networks = { }, mainnet: { court: '0xee4650cBe7a2B23701D416f58b41D8B76b617797' }, } + +export const networkConfigs = { + rpc: { + nodes: { + defaultEth: 'http://localhost:8545', + }, + }, + mainnet: { + nodes: { + defaultEth: 'wss://mainnet.eth.aragon.network/ws', + }, + }, +} + +export function getNetworkConfig(chainId) { + return networkConfigs[chainId] +} diff --git a/src/types/court-module-types.js b/src/types/court-module-types.js index 937214e4..66d25915 100644 --- a/src/types/court-module-types.js +++ b/src/types/court-module-types.js @@ -1,7 +1,7 @@ export const CourtModuleType = { AragonCourt: Symbol('COURT_MAIN_MODULE'), DisputeManager: Symbol('COURT_MODULE_DISPUTE_MANAGER'), - JurorsRegistry: Symbol('COURT_MDOULE_JURORS_REGISTRY'), + JurorsRegistry: Symbol('COURT_MODULE_JURORS_REGISTRY'), Voting: Symbol('COURT_MODULE_VOTING'), Treasury: Symbol('COURT_MODULE_TREASURY'), Subscriptions: Symbol('COURT_MODULE_SUBSCRIPTIONS'), diff --git a/src/utils/known-tokens.js b/src/utils/known-tokens.js index 5d2e3955..84f94c68 100644 --- a/src/utils/known-tokens.js +++ b/src/utils/known-tokens.js @@ -2,11 +2,27 @@ import env from '../environment' import { getNetworkName } from '../lib/web3-utils' export const KNOWN_TOKEN_BY_ENV = { + ANJ: { + mainnet: { + address: '0xcD62b1C403fa761BAadFC74C525ce2B51780b184', + decimals: 18, + }, + }, + ANT: { + mainnet: { + address: '0x960b236A07cf122663c4303350609A66A7B288C0', + decimals: 18, + }, + }, DAI: { mainnet: { address: '0x6b175474e89094c44da98b954eedeac495271d0f', decimals: 18, }, + rpc: { + address: '0x6b175474e89094c44da98b954eedeac495271d0f', + decimals: 18, + }, }, } diff --git a/src/web3-contracts.js b/src/web3-contracts.js index 50100bbd..bdecd18d 100644 --- a/src/web3-contracts.js +++ b/src/web3-contracts.js @@ -1,6 +1,7 @@ import { useMemo } from 'react' import { Contract as EthersContract } from 'ethers' import { useWallet } from './providers/Wallet' +import { getWeb3Provider } from './lib/web3-utils' export function useContract(address, abi, signer = true) { const { account, ethers } = useWallet() @@ -19,3 +20,8 @@ export function useContract(address, abi, signer = true) { ) }, [abi, account, address, ethers, signer]) } + +export function useContractReadOnly(address, abi) { + const ethers = getWeb3Provider() + return new EthersContract(address, abi, ethers) +} From 53effac6b68674ed0d168575d20374b1693ed733 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Tue, 10 Mar 2020 12:54:25 -0300 Subject: [PATCH 04/21] stats --- src/hooks/useCourtContracts.js | 11 +++++++---- src/hooks/useCourtStats.js | 26 +++++++++----------------- 2 files changed, 16 insertions(+), 21 deletions(-) diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index ff0a6a64..48014be6 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -360,16 +360,19 @@ export function useAppealFeeAllowance(owner) { } export function useTotalActiveBalancePolling(termId) { - const jurorRegistryContract = useCourtContract( + const jurorRegistryContract = useCourtContractReadOnly( CourtModuleType.JurorsRegistry, jurorRegistryAbi ) + console.log('jurorRegistryContract ', jurorRegistryContract) const [totalActiveBalance, setTotalActiveBalance] = useState(bigNum(-1)) const timeoutId = useRef(null) const fetchTotalActiveBalance = useCallback(() => { + if (!jurorRegistryContract) return timeoutId.current = setTimeout(() => { + console.log('jurorRegistryContract ', jurorRegistryContract) return jurorRegistryContract .totalActiveBalanceAt(termId) .then(balance => { @@ -392,6 +395,7 @@ export function useTotalActiveBalancePolling(termId) { return totalActiveBalance } + export function useTotalANTStaked() { const [totalANTStaked, setTotalANTStaked] = useState(bigNum(-1)) @@ -420,13 +424,12 @@ export function useTotalANTStaked() { } export function useTotalActiveBalance() { - const jurorRegistryContract = useCourtContract( + const [totalActiveBalance, setTotalActiveBalance] = useState(bigNum(-1)) + const jurorRegistryContract = useCourtContractReadOnly( CourtModuleType.JurorsRegistry, jurorRegistryAbi ) - const [totalActiveBalance, setTotalActiveBalance] = useState(bigNum(-1)) - useEffect(() => { if (!jurorRegistryContract) { return diff --git a/src/hooks/useCourtStats.js b/src/hooks/useCourtStats.js index 676f54b5..b3d85284 100644 --- a/src/hooks/useCourtStats.js +++ b/src/hooks/useCourtStats.js @@ -1,5 +1,6 @@ -import { useMemo, useEffect, useState } from 'react' +import { useMemo } from 'react' import { useTotalActiveBalance, useTotalANTStaked } from './useCourtContracts' +// import { useCourtClock } from '../providers/CourtClock' import { getKnownToken } from '../utils/known-tokens' import { bigNum } from '../lib/math-utils' @@ -16,32 +17,23 @@ const COURT_STATS = [ ] function useCourtStats() { - const [fetching, setFetching] = useState(true) + // const [fetching, setFetching] = useState(true) + // const { currentTermId } = useCourtClock() const ANJActiveBalance = useTotalActiveBalance() + console.log('ANJActiveBalance ', ANJActiveBalance) const ANTTotalStake = useTotalANTStaked() - - const ANJActiveBalanceKey = ANJActiveBalance.toString() - const ANTTotalStakeKey = ANTTotalStake.toString() - - useEffect(() => { - console.log('useEffect') - if (!ANJActiveBalance.eq(bigNum(-1)) && !ANTTotalStake.eq(bigNum(-1))) { - setFetching(false) - } - console.log('fetching') - }, [ANJActiveBalanceKey, ANTTotalStakeKey]) // eslint-disable-line react-hooks/exhaustive-deps + console.log('ANTTotalStake ', ANTTotalStake) return useMemo(() => { - console.log('return ') - if (fetching) { + if (!ANJActiveBalance.eq(bigNum(-1)) && !ANTTotalStake.eq(bigNum(-1))) { return [null, true] } const statsData = [ANJActiveBalance, ANTTotalStake] return [ - ...COURT_STATS.map((stat, index) => { + COURT_STATS.map((stat, index) => { return { ...stat, value: statsData[index], @@ -49,7 +41,7 @@ function useCourtStats() { }), false, ] - }, [ANJActiveBalanceKey, ANTTotalStakeKey, fetching]) // eslint-disable-line react-hooks/exhaustive-deps + }, [ANTTotalStake.toString(), ANJActiveBalance.toString()]) // eslint-disable-line react-hooks/exhaustive-deps } export default useCourtStats From 3b01bffe5069f329ebb66ac8036347bb8f61c988 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Tue, 10 Mar 2020 17:48:57 -0300 Subject: [PATCH 05/21] eth node and active jurors --- src/components/Dashboard/AccountBanner.js | 1 - src/components/Dashboard/Balance.js | 2 +- src/components/Dashboard/CourtStats.js | 188 +++++++++++++--------- src/hooks/query-hooks.js | 12 +- src/hooks/useCourtContracts.js | 2 - src/hooks/useCourtStats.js | 27 ++-- src/hooks/useTokenBalanceToUsd.js | 2 +- src/lib/web3-utils.js | 1 - src/queries/balances.js | 7 + src/utils/known-tokens.js | 14 ++ src/web3-contracts.js | 15 +- 11 files changed, 169 insertions(+), 102 deletions(-) diff --git a/src/components/Dashboard/AccountBanner.js b/src/components/Dashboard/AccountBanner.js index 58991c96..6341fe95 100644 --- a/src/components/Dashboard/AccountBanner.js +++ b/src/components/Dashboard/AccountBanner.js @@ -164,7 +164,6 @@ const BannerWithProbability = ({ activeBalance }) => { const totalActiveBalanceCurrentTerm = useTotalActiveBalancePolling( currentTermId ) - console.log('activeeee ', totalActiveBalanceCurrentTerm) const fetchingTotalBalance = totalActiveBalanceCurrentTerm.eq(bigNum(-1)) const totalPercentage = getPercentageBN( diff --git a/src/components/Dashboard/Balance.js b/src/components/Dashboard/Balance.js index 7326215a..8cdf8993 100644 --- a/src/components/Dashboard/Balance.js +++ b/src/components/Dashboard/Balance.js @@ -68,7 +68,7 @@ const Balance = React.memo(function Balance({ `} > {loading ? ( - + ) : ( { -// const [integer, fractional] = amount.split('.') -// return ( -// -// {integer} -// {fractional && ( -// -// .{fractional} -// -// )} -// -// ) -// } - -const CourtStats = React.memo(function CourtStats() { - const theme = useTheme() - const stats = { - title: 'Total Active ANJ', - token: { - symbol: 'ANJ', - value: 101490826, - decimals: 18, - icon: IconANJ, - usdValue: 82501892, - }, - } - - const cstats = useCourtStats() - - console.log('court stats ', cstats) +import { formatUnits } from '../../lib/math-utils' +import { + useANJBalanceToUsd, + useTokenBalanceToUsd, +} from '../../hooks/useTokenBalanceToUsd' +import Loading from './Loading' +const splitAmount = amount => { + const [integer, fractional] = amount.split('.') return ( - -
+ + {integer} + {fractional && ( - {stats.title} + .{fractional} + )} + + ) +} - -
+function CourtStats() { + const theme = useTheme() + const [stats, fetching] = useCourtStats() + + return ( + + {(() => { + if (fetching) { + return + } + return stats.map((stat, index) => { + return ( +
+ + {stat.label} + + {stat.token ? ( + + ) : ( + + )} +
+ ) + }) + })()}
) -}) +} + +function Stat({ value }) { + return ( + + {value} + + ) +} -function TokenStats({ token, theme }) { - const { value, icon, symbol, usdValue } = token +function TokenStats({ stat, theme }) { + const { value, token } = stat + const { decimals, icon, symbol } = token return ( <>
- {value} + {splitAmount(formatUnits(value, { digits: decimals }))} - ANJ - - {symbol} - + + + {symbol} + +
- ${usdValue} + ${symbol === 'ANJ' ? AnjUsdValue(value) : TokenUsdValue(token, value)} ) } +function AnjUsdValue(amount) { + const usdValue = useANJBalanceToUsd(amount) + return usdValue +} + +function TokenUsdValue(token, amount) { + const { decimals, symbol } = token + const usdValue = useTokenBalanceToUsd(symbol, decimals, amount) + return usdValue +} + export default CourtStats diff --git a/src/hooks/query-hooks.js b/src/hooks/query-hooks.js index 44fd2226..61cb4b08 100644 --- a/src/hooks/query-hooks.js +++ b/src/hooks/query-hooks.js @@ -1,7 +1,7 @@ import { useQuery } from 'urql' import { JurorDrafts, JurorDraftRewarded } from '../queries/jurorDrafts' -import { FirstANJActivationMovement } from '../queries/balances' +import { FirstANJActivationMovement, ActiveJurors } from '../queries/balances' export function useJurorDraftQuery(jurorId) { const [result] = useQuery({ @@ -49,3 +49,13 @@ export function useFirstANJActivationQuery(jurorId, { pause = false }) { return juror ? juror.movements[0] : null } + +export function useActiveJurorsNumber() { + const [result] = useQuery({ + query: ActiveJurors, + }) + + const { jurors } = result.data || {} + + return jurors ? jurors.length : null +} diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index 48014be6..3da6ad55 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -364,7 +364,6 @@ export function useTotalActiveBalancePolling(termId) { CourtModuleType.JurorsRegistry, jurorRegistryAbi ) - console.log('jurorRegistryContract ', jurorRegistryContract) const [totalActiveBalance, setTotalActiveBalance] = useState(bigNum(-1)) const timeoutId = useRef(null) @@ -372,7 +371,6 @@ export function useTotalActiveBalancePolling(termId) { const fetchTotalActiveBalance = useCallback(() => { if (!jurorRegistryContract) return timeoutId.current = setTimeout(() => { - console.log('jurorRegistryContract ', jurorRegistryContract) return jurorRegistryContract .totalActiveBalanceAt(termId) .then(balance => { diff --git a/src/hooks/useCourtStats.js b/src/hooks/useCourtStats.js index b3d85284..e3afc479 100644 --- a/src/hooks/useCourtStats.js +++ b/src/hooks/useCourtStats.js @@ -1,37 +1,38 @@ import { useMemo } from 'react' import { useTotalActiveBalance, useTotalANTStaked } from './useCourtContracts' -// import { useCourtClock } from '../providers/CourtClock' +import { useActiveJurorsNumber } from '../hooks/query-hooks' import { getKnownToken } from '../utils/known-tokens' import { bigNum } from '../lib/math-utils' +import IconANJ from '../assets/IconANJ.svg' +import IconANT from '../assets/IconANT.svg' const COURT_STATS = [ { label: 'Total Active ANJ', - token: getKnownToken('ANJ'), + token: { ...getKnownToken('ANJ'), icon: IconANJ }, }, { label: 'Total Staked ANT', - token: getKnownToken('ANT'), + token: { ...getKnownToken('ANT'), icon: IconANT }, }, - // { label: 'Total Active Jurors' }, + { label: 'Total Active Jurors' }, ] function useCourtStats() { - // const [fetching, setFetching] = useState(true) - // const { currentTermId } = useCourtClock() - const ANJActiveBalance = useTotalActiveBalance() - console.log('ANJActiveBalance ', ANJActiveBalance) - const ANTTotalStake = useTotalANTStaked() - console.log('ANTTotalStake ', ANTTotalStake) + const activeJurors = useActiveJurorsNumber() return useMemo(() => { - if (!ANJActiveBalance.eq(bigNum(-1)) && !ANTTotalStake.eq(bigNum(-1))) { + if ( + ANJActiveBalance.eq(bigNum(-1)) || + ANTTotalStake.eq(bigNum(-1)) || + activeJurors === null + ) { return [null, true] } - const statsData = [ANJActiveBalance, ANTTotalStake] + const statsData = [ANJActiveBalance, ANTTotalStake, activeJurors] return [ COURT_STATS.map((stat, index) => { return { @@ -41,7 +42,7 @@ function useCourtStats() { }), false, ] - }, [ANTTotalStake.toString(), ANJActiveBalance.toString()]) // eslint-disable-line react-hooks/exhaustive-deps + }, [ANTTotalStake.toString(), ANJActiveBalance.toString(), activeJurors]) // eslint-disable-line react-hooks/exhaustive-deps } export default useCourtStats diff --git a/src/hooks/useTokenBalanceToUsd.js b/src/hooks/useTokenBalanceToUsd.js index c9ab7519..bcc6538f 100644 --- a/src/hooks/useTokenBalanceToUsd.js +++ b/src/hooks/useTokenBalanceToUsd.js @@ -102,7 +102,7 @@ export function useANJBalanceToUsd(amount) { * @param {BigNumber} balance The balance to convert into USD. * @returns { Number } The balance value in USD */ -export default function useTokenBalanceToUsd(symbol, decimals, balance) { +export function useTokenBalanceToUsd(symbol, decimals, balance) { const [usd, setUsd] = useState('-') useEffect(() => { let cancelled = false diff --git a/src/lib/web3-utils.js b/src/lib/web3-utils.js index d59a4009..57a81920 100644 --- a/src/lib/web3-utils.js +++ b/src/lib/web3-utils.js @@ -1,7 +1,6 @@ import env from '../environment' import { ethers } from 'ethers' import { solidityKeccak256, id as keccak256 } from 'ethers/utils' -// import { ETH_NODE } from '../endpoints' import { networkConfigs } from '../networks' export const soliditySha3 = solidityKeccak256 export const hash256 = keccak256 diff --git a/src/queries/balances.js b/src/queries/balances.js index 481e1f2d..eb24547e 100644 --- a/src/queries/balances.js +++ b/src/queries/balances.js @@ -56,3 +56,10 @@ export const FirstANJActivationMovement = gql` } } ` +export const ActiveJurors = gql` + query Jurors { + jurors(where: { activeBalance_gt: 0 }) { + id + } + } +` diff --git a/src/utils/known-tokens.js b/src/utils/known-tokens.js index 84f94c68..25bff957 100644 --- a/src/utils/known-tokens.js +++ b/src/utils/known-tokens.js @@ -6,22 +6,36 @@ export const KNOWN_TOKEN_BY_ENV = { mainnet: { address: '0xcD62b1C403fa761BAadFC74C525ce2B51780b184', decimals: 18, + symbol: 'ANJ', + }, + rpc: { + address: '0xcD62b1C403fa761BAadFC74C525ce2B51780b184', + decimals: 18, + symbol: 'ANJ', }, }, ANT: { mainnet: { address: '0x960b236A07cf122663c4303350609A66A7B288C0', decimals: 18, + symbol: 'ANT', + }, + rpc: { + address: '0x960b236A07cf122663c4303350609A66A7B288C0', + decimals: 18, + symbol: 'ANT', }, }, DAI: { mainnet: { address: '0x6b175474e89094c44da98b954eedeac495271d0f', decimals: 18, + symbol: 'DAI', }, rpc: { address: '0x6b175474e89094c44da98b954eedeac495271d0f', decimals: 18, + symbol: 'DAI', }, }, } diff --git a/src/web3-contracts.js b/src/web3-contracts.js index bdecd18d..0a1d1e92 100644 --- a/src/web3-contracts.js +++ b/src/web3-contracts.js @@ -1,7 +1,9 @@ import { useMemo } from 'react' -import { Contract as EthersContract } from 'ethers' +import { Contract as EthersContract, providers as Providers } from 'ethers' import { useWallet } from './providers/Wallet' -import { getWeb3Provider } from './lib/web3-utils' +import { getNetworkName } from './lib/web3-utils' +import { networkConfigs } from './networks' +import env from './environment' export function useContract(address, abi, signer = true) { const { account, ethers } = useWallet() @@ -22,6 +24,11 @@ export function useContract(address, abi, signer = true) { } export function useContractReadOnly(address, abi) { - const ethers = getWeb3Provider() - return new EthersContract(address, abi, ethers) + const ethEndpoint = + networkConfigs[getNetworkName(env('CHAIN_ID'))].nodes.defaultEth + + return useMemo(() => { + const provider = new Providers.JsonRpcProvider(ethEndpoint) + return new EthersContract(address, abi, provider) + }, [abi, address, ethEndpoint]) } From 2c13348c0b0d456cec3902d8be1ab9e43d917452 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Tue, 10 Mar 2020 18:05:57 -0300 Subject: [PATCH 06/21] svg optimization --- src/assets/IconANJSpring.svg | 2 +- src/assets/IconANT.svg | 57 +------------------ src/assets/backgroundError.svg | 2 +- src/assets/globalError.svg | 2 +- src/assets/noData.svg | 2 +- .../Activity/assets/activity-icon-anj.svg | 2 +- .../assets/activity-icon-appeal-ruling.svg | 2 +- .../assets/activity-icon-claim-rewards.svg | 2 +- .../assets/activity-icon-draft-jury.svg | 2 +- .../assets/activity-icon-execute-ruling.svg | 2 +- src/endpoints.js | 4 -- 11 files changed, 10 insertions(+), 69 deletions(-) diff --git a/src/assets/IconANJSpring.svg b/src/assets/IconANJSpring.svg index 1e90743d..514c3d8f 100644 --- a/src/assets/IconANJSpring.svg +++ b/src/assets/IconANJSpring.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/assets/IconANT.svg b/src/assets/IconANT.svg index 639f7298..8ba97700 100755 --- a/src/assets/IconANT.svg +++ b/src/assets/IconANT.svg @@ -1,56 +1 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + \ No newline at end of file diff --git a/src/assets/backgroundError.svg b/src/assets/backgroundError.svg index 14f29a02..be9bc0f9 100644 --- a/src/assets/backgroundError.svg +++ b/src/assets/backgroundError.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/assets/globalError.svg b/src/assets/globalError.svg index cc707b1b..800ed7f8 100644 --- a/src/assets/globalError.svg +++ b/src/assets/globalError.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/assets/noData.svg b/src/assets/noData.svg index beb402d8..37f79ef6 100644 --- a/src/assets/noData.svg +++ b/src/assets/noData.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/components/Activity/assets/activity-icon-anj.svg b/src/components/Activity/assets/activity-icon-anj.svg index d78cbf50..7c700b2d 100644 --- a/src/components/Activity/assets/activity-icon-anj.svg +++ b/src/components/Activity/assets/activity-icon-anj.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/components/Activity/assets/activity-icon-appeal-ruling.svg b/src/components/Activity/assets/activity-icon-appeal-ruling.svg index 0614dece..89349425 100644 --- a/src/components/Activity/assets/activity-icon-appeal-ruling.svg +++ b/src/components/Activity/assets/activity-icon-appeal-ruling.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/components/Activity/assets/activity-icon-claim-rewards.svg b/src/components/Activity/assets/activity-icon-claim-rewards.svg index 46a1a7e4..e19650a0 100644 --- a/src/components/Activity/assets/activity-icon-claim-rewards.svg +++ b/src/components/Activity/assets/activity-icon-claim-rewards.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/components/Activity/assets/activity-icon-draft-jury.svg b/src/components/Activity/assets/activity-icon-draft-jury.svg index e497a4b6..88100261 100644 --- a/src/components/Activity/assets/activity-icon-draft-jury.svg +++ b/src/components/Activity/assets/activity-icon-draft-jury.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/components/Activity/assets/activity-icon-execute-ruling.svg b/src/components/Activity/assets/activity-icon-execute-ruling.svg index 56d13eaa..2e104505 100644 --- a/src/components/Activity/assets/activity-icon-execute-ruling.svg +++ b/src/components/Activity/assets/activity-icon-execute-ruling.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/src/endpoints.js b/src/endpoints.js index f75c5ab4..7009cd51 100644 --- a/src/endpoints.js +++ b/src/endpoints.js @@ -1,5 +1,4 @@ import environment from './environment' -// import { networkConfigs } from './networks' import { isLocalOrUnknownNetwork, getNetworkType } from './lib/web3-utils' @@ -19,9 +18,6 @@ export const IPFS_ENDPOINT = isLocalOrUnknownNetwork(CHAIN_ID) const GRAPH_API_PATH = '/subgraphs/name/aragon/aragon-court' -// export const ETH_NODE = -// networkConfigs[getNetworkName(environment('CHAIN_ID'))].nodes.defaultEth - function getAPIBase() { return isLocalOrUnknownNetwork(CHAIN_ID) ? [GRAPH_API_BASE_HTTP_LOCAL, GRAPH_API_BASE_WS_LOCAL] From 8c46338753c545029b88e1dd79d071817e03998b Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Tue, 10 Mar 2020 19:14:52 -0300 Subject: [PATCH 07/21] add first 1000 for jurors query --- src/networks.js | 2 +- src/queries/balances.js | 2 +- src/web3-contracts.js | 6 +----- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/src/networks.js b/src/networks.js index c01637eb..58b44908 100644 --- a/src/networks.js +++ b/src/networks.js @@ -23,7 +23,7 @@ export const networkConfigs = { defaultEth: 'http://localhost:8545', }, }, - mainnet: { + main: { nodes: { defaultEth: 'wss://mainnet.eth.aragon.network/ws', }, diff --git a/src/queries/balances.js b/src/queries/balances.js index eb24547e..ab971b5e 100644 --- a/src/queries/balances.js +++ b/src/queries/balances.js @@ -58,7 +58,7 @@ export const FirstANJActivationMovement = gql` ` export const ActiveJurors = gql` query Jurors { - jurors(where: { activeBalance_gt: 0 }) { + jurors(first: 1000, where: { activeBalance_gt: 0 }) { id } } diff --git a/src/web3-contracts.js b/src/web3-contracts.js index 2fa14926..c7132317 100644 --- a/src/web3-contracts.js +++ b/src/web3-contracts.js @@ -3,7 +3,6 @@ import { Contract as EthersContract, providers as Providers } from 'ethers' import { useWallet } from './providers/Wallet' import { getNetworkType } from './lib/web3-utils' import { networkConfigs } from './networks' -import env from './environment' export function useContract(address, abi, signer = true) { const { account, ethers } = useWallet() @@ -24,10 +23,7 @@ export function useContract(address, abi, signer = true) { } export function useContractReadOnly(address, abi) { - console.log('networkConfigs ', networkConfigs) - console.log('network name ', env('CHAIN_ID')) - const ethEndpoint = - networkConfigs[getNetworkType(env('CHAIN_ID'))].nodes.defaultEth + const ethEndpoint = networkConfigs[getNetworkType()].nodes.defaultEth return useMemo(() => { const provider = new Providers.JsonRpcProvider(ethEndpoint) From 18cc0028d1bd23436fef7a834569264db398c404 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Thu, 19 Mar 2020 21:55:58 -0300 Subject: [PATCH 08/21] pr comments --- src/components/Dashboard/Balance.js | 27 ++---------- src/components/Dashboard/CourtStats.js | 57 ++++++-------------------- src/components/SplitAmount.js | 25 +++++++++++ src/endpoints.js | 3 +- src/hooks/query-hooks.js | 4 +- src/hooks/useCourtContracts.js | 42 ++++++++++++++----- src/hooks/useCourtStats.js | 5 ++- src/hooks/useTokenBalanceToUsd.js | 46 ++++++++++++--------- src/lib/web3-utils.js | 3 +- src/networks.js | 11 +++-- src/utils/known-tokens.js | 10 ++--- src/voided-disputes.js | 2 +- src/web3-contracts.js | 10 +++-- 13 files changed, 131 insertions(+), 114 deletions(-) create mode 100644 src/components/SplitAmount.js diff --git a/src/components/Dashboard/Balance.js b/src/components/Dashboard/Balance.js index 8cdf8993..dce88044 100644 --- a/src/components/Dashboard/Balance.js +++ b/src/components/Dashboard/Balance.js @@ -4,6 +4,7 @@ import { useSpring, animated } from 'react-spring' import Loading from './Loading' import ANJLockedDistribution from './ANJLockedDistribution' +import SplitAmount from '../SplitAmount' import { useCourtConfig } from '../../providers/CourtConfig' import { useANJBalanceToUsd } from '../../hooks/useTokenBalanceToUsd' @@ -15,28 +16,6 @@ import { movementDirection, convertToString } from '../../types/anj-types' import ANJIcon from '../../assets/IconANJ.svg' import lockIcon from '../../assets/IconLock.svg' -const splitAmount = amount => { - const [integer, fractional] = amount.split('.') - return ( - - {integer} - {fractional && ( - - .{fractional} - - )} - - ) -} - const Balance = React.memo(function Balance({ label, amount, @@ -113,7 +92,9 @@ const Balance = React.memo(function Balance({ align-items: center; `} > - {splitAmount(formatUnits(amount, { digits: decimals }))} + ANJ { - const [integer, fractional] = amount.split('.') - return ( - - {integer} - {fractional && ( - - .{fractional} - - )} - - ) -} +import SplitAmount from '../SplitAmount' function CourtStats() { const theme = useTheme() @@ -64,7 +43,14 @@ function CourtStats() { {stat.token ? ( ) : ( - + + {stat.value} + )} ) @@ -74,22 +60,10 @@ function CourtStats() { ) } -function Stat({ value }) { - return ( - - {value} - - ) -} - function TokenStats({ stat, theme }) { const { value, token } = stat const { decimals, icon, symbol } = token + return ( <>
- {splitAmount(formatUnits(value, { digits: decimals }))} +
- - {symbol} -
+ {integer} + {fractional && ( + + .{fractional} + + )} + + ) +} diff --git a/src/endpoints.js b/src/endpoints.js index 7009cd51..8b093682 100644 --- a/src/endpoints.js +++ b/src/endpoints.js @@ -26,7 +26,8 @@ function getAPIBase() { export default function endpoints() { const [API_BASE_HTTP, API_BASE_WS] = getAPIBase() - const networkType = getNetworkType(CHAIN_ID) + const networkType = + getNetworkType(CHAIN_ID) === 'local' ? 'rpc' : getNetworkType(CHAIN_ID) const API_PATH = networkType === 'main' diff --git a/src/hooks/query-hooks.js b/src/hooks/query-hooks.js index 61cb4b08..c39fdbec 100644 --- a/src/hooks/query-hooks.js +++ b/src/hooks/query-hooks.js @@ -1,7 +1,7 @@ import { useQuery } from 'urql' import { JurorDrafts, JurorDraftRewarded } from '../queries/jurorDrafts' -import { FirstANJActivationMovement, ActiveJurors } from '../queries/balances' +import { ActiveJurors, FirstANJActivationMovement } from '../queries/balances' export function useJurorDraftQuery(jurorId) { const [result] = useQuery({ @@ -57,5 +57,5 @@ export function useActiveJurorsNumber() { const { jurors } = result.data || {} - return jurors ? jurors.length : null + return jurors?.length } diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index ed19e68e..fa15df49 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -479,7 +479,7 @@ export function useTotalANTStaked() { return totalANTStaked } -export function useTotalActiveBalance() { +export function useTotalActiveBalance(timeout = 1000) { const [totalActiveBalance, setTotalActiveBalance] = useState(bigNum(-1)) const jurorRegistryContract = useCourtContractReadOnly( CourtModuleType.JurorsRegistry, @@ -487,21 +487,41 @@ export function useTotalActiveBalance() { ) useEffect(() => { + let cancelled = false + let timeoutId + if (!jurorRegistryContract) { return } - const getTotalActiveBalance = async () => { - retryMax(() => jurorRegistryContract.totalActiveBalance()) - .then(totalActive => { - setTotalActiveBalance(totalActive) - }) - .catch(err => { - console.error(`Error fetching ANT staked: ${err}`) - }) + + const fetchTotalActiveBalance = () => { + timeoutId = setTimeout(() => { + return jurorRegistryContract + .totalActiveBalance() + .then(balance => { + if (!cancelled) { + setTotalActiveBalance(balance) + } + }) + .catch(err => { + console.error(`Error fetching balance: ${err} retrying...`) + }) + .finally(() => { + if (!cancelled) { + clearTimeout(timeoutId) + fetchTotalActiveBalance() + } + }) + }, timeout) } - getTotalActiveBalance() - }, [jurorRegistryContract]) + fetchTotalActiveBalance() + + return () => { + cancelled = true + clearTimeout(timeoutId) + } + }, [jurorRegistryContract, timeout]) return totalActiveBalance } diff --git a/src/hooks/useCourtStats.js b/src/hooks/useCourtStats.js index e3afc479..9c0ace20 100644 --- a/src/hooks/useCourtStats.js +++ b/src/hooks/useCourtStats.js @@ -17,7 +17,10 @@ const COURT_STATS = [ }, { label: 'Total Active Jurors' }, ] - +/** + * Hook to get the dashboard stats ANJ active balance, ANT total stake and the active jurors number + * @returns {Array} First item an array with the stats and the second one a loading state + */ function useCourtStats() { const ANJActiveBalance = useTotalActiveBalance() const ANTTotalStake = useTotalANTStaked() diff --git a/src/hooks/useTokenBalanceToUsd.js b/src/hooks/useTokenBalanceToUsd.js index 0a30d6fe..1150df2c 100644 --- a/src/hooks/useTokenBalanceToUsd.js +++ b/src/hooks/useTokenBalanceToUsd.js @@ -4,7 +4,11 @@ import env from '../environment' import { useCourtConfig } from '../providers/CourtConfig' import { getKnownToken } from '../utils/known-tokens' import { formatUnits, bigNum } from '../lib/math-utils' -import { addressesEqual, ETH_FAKE_ADDRESS } from '../lib/web3-utils' +import { + addressesEqual, + ETH_FAKE_ADDRESS, + getNetworkType, +} from '../lib/web3-utils' const UNISWAP_PRECISION = 18 const UNISWAP_MARKET_RETRY_EVERY = 1000 @@ -43,7 +47,7 @@ export function useANJBalanceToUsd(amount) { const dai = getKnownToken('DAI') const { address: daiAddress } = dai || {} - const [convertedAmount, setConvertedAmount] = useState('0') + const [convertedAmount, setConvertedAmount] = useState('-') useEffect(() => { let cancelled = false @@ -107,23 +111,27 @@ export function useTokenBalanceToUsd(symbol, decimals, balance) { useEffect(() => { let cancelled = false - fetch(`${API_BASE}/price?fsym=${symbol}&tsyms=USD`) - .then(res => res.json()) - .then(price => { - if (cancelled || !balance || !(parseFloat(price.USD) > 0)) { - return - } - - const usdDigits = 2 - const precision = 6 - - const usdBalance = balance - .mul(bigNum(parseInt(price.USD * 10 ** (precision + usdDigits), 10))) - .div(10 ** precision) - .div(bigNum(10).pow(decimals)) - - setUsd(formatUnits(usdBalance, { digits: usdDigits })) - }) + if (getNetworkType() === 'main') { + fetch(`${API_BASE}/price?fsym=${symbol}&tsyms=USD`) + .then(res => res.json()) + .then(price => { + if (cancelled || !balance || !(parseFloat(price.USD) > 0)) { + return + } + + const usdDigits = 2 + const precision = 6 + + const usdBalance = balance + .mul( + bigNum(parseInt(price.USD * 10 ** (precision + usdDigits), 10)) + ) + .div(10 ** precision) + .div(bigNum(10).pow(decimals)) + + setUsd(formatUnits(usdBalance, { digits: usdDigits })) + }) + } return () => { cancelled = true diff --git a/src/lib/web3-utils.js b/src/lib/web3-utils.js index bc693357..35250456 100644 --- a/src/lib/web3-utils.js +++ b/src/lib/web3-utils.js @@ -1,8 +1,9 @@ import env from '../environment' import { solidityKeccak256, id as keccak256 } from 'ethers/utils' + export const soliditySha3 = solidityKeccak256 export const hash256 = keccak256 -export const DEFAULT_LOCAL_CHAIN = 'rpc' +export const DEFAULT_LOCAL_CHAIN = 'local' export const ETH_FAKE_ADDRESS = `0x${''.padEnd(40, '0')}` const ETH_ADDRESS_SPLIT_REGEX = /(0x[a-fA-F0-9]{40}(?:\b|\.|,|\?|!|;))/g diff --git a/src/networks.js b/src/networks.js index 58b44908..3f3ed833 100644 --- a/src/networks.js +++ b/src/networks.js @@ -7,7 +7,7 @@ export const RINKEBY_USABILITY_COURT = '0x44f788370206696b20B94BC77c4f73Ca264aa05E' export const networks = { - rpc: { court: '0xC89Ce4735882C9F0f0FE26686c53074E09B0D550' }, + local: { court: '0xC89Ce4735882C9F0f0FE26686c53074E09B0D550' }, ropsten: { court: '0x3b26bc496aebaed5b3E0E81cDE6B582CDe71396e' }, rinkeby: { // Use the 'usability' Court address if declared @@ -18,14 +18,19 @@ export const networks = { } export const networkConfigs = { - rpc: { + local: { nodes: { defaultEth: 'http://localhost:8545', }, }, main: { nodes: { - defaultEth: 'wss://mainnet.eth.aragon.network/ws', + defaultEth: 'https://mainnet.eth.aragon.network/', + }, + }, + rinkeby: { + nodes: { + defaultEth: 'https://rinkeby.eth.aragon.network/', }, }, } diff --git a/src/utils/known-tokens.js b/src/utils/known-tokens.js index e64bba8b..590695ac 100644 --- a/src/utils/known-tokens.js +++ b/src/utils/known-tokens.js @@ -3,24 +3,24 @@ import { getNetworkType } from '../lib/web3-utils' export const KNOWN_TOKEN_BY_ENV = { ANJ: { - mainnet: { + main: { address: '0xcD62b1C403fa761BAadFC74C525ce2B51780b184', decimals: 18, symbol: 'ANJ', }, - rpc: { + local: { address: '0xcD62b1C403fa761BAadFC74C525ce2B51780b184', decimals: 18, symbol: 'ANJ', }, }, ANT: { - mainnet: { + main: { address: '0x960b236A07cf122663c4303350609A66A7B288C0', decimals: 18, symbol: 'ANT', }, - rpc: { + local: { address: '0x960b236A07cf122663c4303350609A66A7B288C0', decimals: 18, symbol: 'ANT', @@ -32,7 +32,7 @@ export const KNOWN_TOKEN_BY_ENV = { decimals: 18, symbol: 'DAI', }, - rpc: { + local: { address: '0x6b175474e89094c44da98b954eedeac495271d0f', decimals: 18, symbol: 'DAI', diff --git a/src/voided-disputes.js b/src/voided-disputes.js index d49e15a1..4cee15ad 100644 --- a/src/voided-disputes.js +++ b/src/voided-disputes.js @@ -10,7 +10,7 @@ const DEFAULT_VOID_DESCRIPTION = 'Dispute #0 is void and all related content has been removed from the Dashboard. Aragon One has made the decision to void the dispute and consider it non-existent when considering precedence for future Aragon Court cases.' const VOIDED_DISPUTES = { - rpc: new Map([[networks.rpc.court, new Map([])]]), + local: new Map([[networks.local.court, new Map([])]]), ropsten: new Map([[networks.ropsten.court, new Map([])]]), rinkeby: new Map([ [RINKEBY_COURT, new Map([])], diff --git a/src/web3-contracts.js b/src/web3-contracts.js index c7132317..d3dc2672 100644 --- a/src/web3-contracts.js +++ b/src/web3-contracts.js @@ -25,8 +25,12 @@ export function useContract(address, abi, signer = true) { export function useContractReadOnly(address, abi) { const ethEndpoint = networkConfigs[getNetworkType()].nodes.defaultEth + const ethProvider = useMemo( + () => (ethEndpoint ? new Providers.JsonRpcProvider(ethEndpoint) : null), + [ethEndpoint] + ) + return useMemo(() => { - const provider = new Providers.JsonRpcProvider(ethEndpoint) - return new EthersContract(address, abi, provider) - }, [abi, address, ethEndpoint]) + return new EthersContract(address, abi, ethProvider) + }, [abi, address, ethProvider]) } From 8b3ef0716bb062d66d1960ee16d94a1bff6edb31 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Fri, 20 Mar 2020 20:59:22 -0300 Subject: [PATCH 09/21] price fix --- src/components/Dashboard/CourtStats.js | 43 +++++++++++------- src/hooks/useCourtContracts.js | 61 +++++++++++++++++++------- src/hooks/useCourtStats.js | 11 +++-- src/networks.js | 13 +++++- src/utils/known-tokens.js | 30 +++++++++++++ 5 files changed, 121 insertions(+), 37 deletions(-) diff --git a/src/components/Dashboard/CourtStats.js b/src/components/Dashboard/CourtStats.js index b902b80e..ce8ae8be 100644 --- a/src/components/Dashboard/CourtStats.js +++ b/src/components/Dashboard/CourtStats.js @@ -1,7 +1,7 @@ import React from 'react' import { Box, GU, textStyle, useTheme } from '@aragon/ui' import { formatUnits } from '../../lib/math-utils' -import useCourtStats from '../../hooks/useCourtStats' +import useCourtStats, { STAT_NOT_AVAILABLE } from '../../hooks/useCourtStats' import { useANJBalanceToUsd, useTokenBalanceToUsd, @@ -63,7 +63,7 @@ function CourtStats() { function TokenStats({ stat, theme }) { const { value, token } = stat const { decimals, icon, symbol } = token - + const statAvailable = !value.eq(STAT_NOT_AVAILABLE) return ( <>
- + {statAvailable ? ( + + ) : ( + '-' + )} -
- -
+ > + +
+ )} - ${symbol === 'ANJ' ? AnjUsdValue(value) : TokenUsdValue(token, value)} + $ + {statAvailable + ? symbol === 'ANJ' + ? AnjUsdValue(value) + : TokenUsdValue(token, value) + : '-'} ) diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index fa15df49..ca3c56f4 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { useContract, useContractReadOnly } from '../web3-contracts' import { CourtModuleType } from '../types/court-module-types' import { useCourtConfig } from '../providers/CourtConfig' -import { getFunctionSignature } from '../lib/web3-utils' +import { getFunctionSignature, getNetworkType } from '../lib/web3-utils' import { bigNum, formatUnits } from '../lib/math-utils' import { hashVote, @@ -13,6 +13,9 @@ import { import { getModuleAddress } from '../utils/court-utils' import { retryMax } from '../utils/retry-max' import { useActivity } from '../components/Activity/ActivityProvider' +import { networkAgentAddress, networkReserveAddress } from '../networks' +import { getKnownToken } from '../utils/known-tokens' +import { STAT_NOT_AVAILABLE } from '../hooks/useCourtStats' import aragonCourtAbi from '../abi/AragonCourt.json' import courtTreasuryAbi from '../abi/CourtTreasury.json' @@ -452,29 +455,53 @@ export function useTotalActiveBalancePolling(termId) { return totalActiveBalance } -export function useTotalANTStaked() { +export function useTotalANTStakedPolling(timeout = 1000) { const [totalANTStaked, setTotalANTStaked] = useState(bigNum(-1)) + const { address: antAddress } = getKnownToken('ANT') + const antContract = useContractReadOnly(antAddress, tokenAbi) - const jurorRegistryContract = useCourtContractReadOnly( - CourtModuleType.JurorsRegistry, - jurorRegistryAbi - ) useEffect(() => { - if (!jurorRegistryContract) { + let cancelled = false + let timeoutId + + // Ask facu if he wants to mantain the ropsten network for the dashboard and remove ropsten from the networks if not + if (getNetworkType() === 'local' || getNetworkType() === 'ropsten') { + setTotalANTStaked(STAT_NOT_AVAILABLE) return } - const getTotalANTStaked = async () => { - retryMax(() => jurorRegistryContract.totalStaked()) - .then(totalStaked => { - setTotalANTStaked(totalStaked) - }) - .catch(err => { - console.error(`Error fetching ANT staked: ${err}`) - }) + if (!antContract) { + return + } + + const fetchTotalANTBalance = () => { + timeoutId = setTimeout(() => { + const agentBalancePromise = antContract.balanceOf(networkAgentAddress) + const vaultBalancePromise = antContract.balanceOf(networkReserveAddress) + return Promise.all([agentBalancePromise, vaultBalancePromise]) + .then(([antInAgent, antInVault]) => { + if (!cancelled) { + setTotalANTStaked(antInAgent.add(antInVault)) + } + }) + .catch(err => { + console.error(`Error fetching balance: ${err} retrying...`) + }) + .finally(() => { + if (!cancelled) { + clearTimeout(timeoutId) + fetchTotalANTBalance() + } + }) + }, timeout) } - getTotalANTStaked() - }, [jurorRegistryContract]) + fetchTotalANTBalance() + + return () => { + cancelled = true + clearTimeout(timeoutId) + } + }, [antContract, timeout]) return totalANTStaked } diff --git a/src/hooks/useCourtStats.js b/src/hooks/useCourtStats.js index 9c0ace20..112827ed 100644 --- a/src/hooks/useCourtStats.js +++ b/src/hooks/useCourtStats.js @@ -1,5 +1,8 @@ import { useMemo } from 'react' -import { useTotalActiveBalance, useTotalANTStaked } from './useCourtContracts' +import { + useTotalActiveBalance, + useTotalANTStakedPolling, +} from './useCourtContracts' import { useActiveJurorsNumber } from '../hooks/query-hooks' import { getKnownToken } from '../utils/known-tokens' import { bigNum } from '../lib/math-utils' @@ -17,13 +20,15 @@ const COURT_STATS = [ }, { label: 'Total Active Jurors' }, ] +export const STAT_NOT_AVAILABLE = bigNum(-2) /** * Hook to get the dashboard stats ANJ active balance, ANT total stake and the active jurors number * @returns {Array} First item an array with the stats and the second one a loading state */ function useCourtStats() { - const ANJActiveBalance = useTotalActiveBalance() - const ANTTotalStake = useTotalANTStaked() + const timeout = 5000 + const ANJActiveBalance = useTotalActiveBalance(timeout) + const ANTTotalStake = useTotalANTStakedPolling(timeout) const activeJurors = useActiveJurorsNumber() return useMemo(() => { diff --git a/src/networks.js b/src/networks.js index 3f3ed833..d39fc24d 100644 --- a/src/networks.js +++ b/src/networks.js @@ -1,4 +1,5 @@ import environment from './environment' +import { getNetworkType } from './lib/web3-utils' const SUBGRAPH_NAME = environment('SUBGRAPH_NAME') @@ -14,7 +15,11 @@ export const networks = { court: SUBGRAPH_NAME === 'usability' ? RINKEBY_USABILITY_COURT : RINKEBY_COURT, }, - main: { court: '0xee4650cBe7a2B23701D416f58b41D8B76b617797' }, + main: { + court: '0xee4650cBe7a2B23701D416f58b41D8B76b617797', + network_agent: '0x5e8c17a6065c35b172b10e80493d2266e2947df4', + network_reserve: '0xec0dd1579551964703246becfbf199c27cb84485', + }, } export const networkConfigs = { @@ -38,3 +43,9 @@ export const networkConfigs = { export function getNetworkConfig(chainId) { return networkConfigs[chainId] } + +export const networkAgentAddress = + networks[getNetworkType(environment('CHAIN_ID'))].network_agent + +export const networkReserveAddress = + networks[getNetworkType(environment('CHAIN_ID'))].network_reserve diff --git a/src/utils/known-tokens.js b/src/utils/known-tokens.js index 590695ac..c2826632 100644 --- a/src/utils/known-tokens.js +++ b/src/utils/known-tokens.js @@ -8,6 +8,16 @@ export const KNOWN_TOKEN_BY_ENV = { decimals: 18, symbol: 'ANJ', }, + rinkeby: { + address: '0x929F3B27a22a7A56FC8d89617033D22e53840aC9', + decimals: 18, + symbol: 'ANJ', + }, + ropsten: { + address: '0xc863E1CcC047befF17022F4229DBE6321A6BCe65', + decimals: 18, + symbol: 'ANJ', + }, local: { address: '0xcD62b1C403fa761BAadFC74C525ce2B51780b184', decimals: 18, @@ -20,6 +30,16 @@ export const KNOWN_TOKEN_BY_ENV = { decimals: 18, symbol: 'ANT', }, + rinkeby: { + address: '0xbf932fdf8d600398d64614ef9a10401ff046f449', + decimals: 18, + symbol: 'ANT', + }, + ropsten: { + address: '0x0cb95D9537c8Fb0C947eD48FDafc66A7b72EfC86', + decimals: 18, + symbol: 'ANT', + }, local: { address: '0x960b236A07cf122663c4303350609A66A7B288C0', decimals: 18, @@ -32,6 +52,16 @@ export const KNOWN_TOKEN_BY_ENV = { decimals: 18, symbol: 'DAI', }, + rinkeby: { + address: '0xe9A083D88Eed757B1d633321Ce0519F432c6284d', + decimals: 18, + symbol: 'DAI', + }, + ropsten: { + address: '0x4E1F48Db14D7E1ada090c42ffE15FF3024EEc8Bf', + decimals: 18, + symbol: 'DAI', + }, local: { address: '0x6b175474e89094c44da98b954eedeac495271d0f', decimals: 18, From d33083e9226fc1dce4793826a48140ee04833e89 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Mon, 23 Mar 2020 12:57:15 -0300 Subject: [PATCH 10/21] remove ant local --- src/utils/known-tokens.js | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/utils/known-tokens.js b/src/utils/known-tokens.js index c2826632..9287d4e6 100644 --- a/src/utils/known-tokens.js +++ b/src/utils/known-tokens.js @@ -40,11 +40,6 @@ export const KNOWN_TOKEN_BY_ENV = { decimals: 18, symbol: 'ANT', }, - local: { - address: '0x960b236A07cf122663c4303350609A66A7B288C0', - decimals: 18, - symbol: 'ANT', - }, }, DAI: { main: { From 6005c7941a5b18f22a89cbe38a391c101b3c5866 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Tue, 24 Mar 2020 19:44:30 -0300 Subject: [PATCH 11/21] remove commented code --- src/hooks/useCourtContracts.js | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index 43879e75..f7ab5c7e 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -64,14 +64,6 @@ function useCourtContract(moduleType, abi) { return useContract(contractAddress, abi) } -// function useCourtContractReadOnly(moduleType, abi) { -// const { modules } = useCourtConfig() - -// const contractAddress = getModuleAddress(modules, moduleType) - -// return useContractReadOnly(contractAddress, abi) -// } - /** * All ANJ interactions * @returns {Object} all available functions around ANJ balances From 651a694704c5bee7091c8e73425b2329faa7b8a0 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Wed, 25 Mar 2020 13:28:36 -0300 Subject: [PATCH 12/21] total rewards stat --- src/assets/IconDAI.svg | 7 +++ src/components/Dashboard/AccountBanner.js | 2 +- src/hooks/subscription-hooks.js | 16 +++++- src/hooks/useCourtContracts.js | 12 ---- src/hooks/useCourtStats.js | 69 +++++++++++++++++++---- src/queries/court.js | 11 ++++ 6 files changed, 93 insertions(+), 24 deletions(-) create mode 100755 src/assets/IconDAI.svg diff --git a/src/assets/IconDAI.svg b/src/assets/IconDAI.svg new file mode 100755 index 00000000..e79a7e41 --- /dev/null +++ b/src/assets/IconDAI.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/src/components/Dashboard/AccountBanner.js b/src/components/Dashboard/AccountBanner.js index 2ca218aa..e2e66ba0 100644 --- a/src/components/Dashboard/AccountBanner.js +++ b/src/components/Dashboard/AccountBanner.js @@ -4,7 +4,7 @@ import { GU, Help, LoadingRing, useTheme } from '@aragon/ui' import AccountBannerInfo from './AccountBannerInfo' import CircleGraph from '../CircleGraph' import { useCourtConfig } from '../../providers/CourtConfig' -import { useTotalActiveBalance } from '../../hooks/useCourtContracts' +import { useTotalActiveBalance } from '../../hooks/useCourtStats' import { useJurorFirstTimeANJActivation } from '../../hooks/useANJ' import { ACCOUNT_STATUS_JUROR_ACTIVE } from '../../types/account-status-types' diff --git a/src/hooks/subscription-hooks.js b/src/hooks/subscription-hooks.js index c6849fa1..3ca27cc9 100644 --- a/src/hooks/subscription-hooks.js +++ b/src/hooks/subscription-hooks.js @@ -4,7 +4,11 @@ import { dayjs } from '../utils/date-utils' import { CourtModuleType } from '../types/court-module-types' import { useCourtConfig } from '../providers/CourtConfig' import { ANJBalance, Juror } from '../queries/balances' -import { CourtConfig, JurorsRegistryModule } from '../queries/court' +import { + CourtConfig, + JurorsRegistryModule, + FeeMovements, +} from '../queries/court' import { AppealsByMaker, AppealsByTaker } from '../queries/appeals' import { JurorDraftsNotRewarded, @@ -303,3 +307,13 @@ export function useJurorRegistrySubscription() { return { data: juroRegistryStats, error } } + +export function useTotalRewardsSubscription() { + const [{ data, error }] = useSubscription({ + query: FeeMovements, + }) + + const rewards = data?.feeMovements || null + + return { data: rewards, error } +} diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index f7ab5c7e..da06ffec 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -17,7 +17,6 @@ import { useActivity } from '../components/Activity/ActivityProvider' import { networkAgentAddress, networkReserveAddress } from '../networks' import { getKnownToken } from '../utils/known-tokens' import { STAT_NOT_AVAILABLE } from '../hooks/useCourtStats' -import { useJurorRegistrySubscription } from '../hooks/subscription-hooks' import aragonCourtAbi from '../abi/AragonCourt.json' import courtSubscriptionsAbi from '../abi/CourtSubscriptions.json' @@ -633,14 +632,3 @@ export function useTotalANTStakedPolling(timeout = 1000) { return totalANTStaked } - -export function useTotalActiveBalance() { - const { data: jurorRegistryStats } = useJurorRegistrySubscription() - - return useMemo(() => { - if (!jurorRegistryStats) { - return bigNum(-1) - } - return bigNum(jurorRegistryStats?.totalActive) || null - }, [jurorRegistryStats]) -} diff --git a/src/hooks/useCourtStats.js b/src/hooks/useCourtStats.js index f7186edd..69cb0cbe 100644 --- a/src/hooks/useCourtStats.js +++ b/src/hooks/useCourtStats.js @@ -1,13 +1,15 @@ import { useMemo } from 'react' -import { - useTotalActiveBalance, - useTotalANTStakedPolling, -} from './useCourtContracts' +import { useTotalANTStakedPolling } from './useCourtContracts' import { useActiveJurorsNumber } from '../hooks/query-hooks' +import { + useJurorRegistrySubscription, + useTotalRewardsSubscription, +} from '../hooks/subscription-hooks' import { getKnownToken } from '../utils/known-tokens' import { bigNum } from '../lib/math-utils' import IconANJ from '../assets/IconANJ.svg' import IconANT from '../assets/IconANT.svg' +import IconDAI from '../assets/IconDAI.svg' const COURT_STATS = [ { @@ -19,28 +21,75 @@ const COURT_STATS = [ token: { ...getKnownToken('ANT'), icon: IconANT }, }, { label: 'Total Active Jurors' }, + { + label: 'Total Rewards DAI', + token: { ...getKnownToken('DAI'), icon: IconDAI }, + }, ] export const STAT_NOT_AVAILABLE = bigNum(-2) + +export function useTotalActiveBalance() { + const { data: jurorRegistryStats, error } = useJurorRegistrySubscription() + + return useMemo(() => { + if (error) { + return [null, error] + } + if (!jurorRegistryStats) { + return [bigNum(-1), error] + } + return [bigNum(jurorRegistryStats?.totalActive) || null, error] + }, [error, jurorRegistryStats]) +} + +function useTotalRewards() { + const { data: rewards, error } = useTotalRewardsSubscription() + + return useMemo(() => { + if (error) { + return [null, error] + } + if (!rewards) { + return [bigNum(-1), error] + } + return [ + rewards.reduce( + (totalAcumulator, reward) => totalAcumulator.add(reward.amount), + bigNum(0) + ), + error, + ] + }, [error, rewards]) +} /** * Hook to get the dashboard stats ANJ active balance, ANT total stake and the active jurors number * @returns {Array} First item an array with the stats and the second one a loading state */ function useCourtStats() { const timeout = 5000 - const ANJActiveBalance = useTotalActiveBalance() - const ANTTotalStake = useTotalANTStakedPolling(timeout) + const [anjActiveBalance, activeBalanceError] = useTotalActiveBalance() + const antTotalStake = useTotalANTStakedPolling(timeout) const activeJurors = useActiveJurorsNumber() + const [totalRewards, totalRewardsError] = useTotalRewards() + console.log('totalREwards ', totalRewards) + console.log('totalRewardsError ', totalRewardsError) + console.log('totalRewardsError ', activeBalanceError) return useMemo(() => { if ( - ANJActiveBalance.eq(bigNum(-1)) || - ANTTotalStake.eq(bigNum(-1)) || + anjActiveBalance.eq(bigNum(-1)) || + antTotalStake.eq(bigNum(-1)) || activeJurors === null ) { return [null, true] } - const statsData = [ANJActiveBalance, ANTTotalStake, activeJurors] + const statsData = [ + anjActiveBalance, + antTotalStake, + activeJurors, + totalRewards, + ] return [ COURT_STATS.map((stat, index) => { return { @@ -50,7 +99,7 @@ function useCourtStats() { }), false, ] - }, [ANTTotalStake.toString(), ANJActiveBalance.toString(), activeJurors]) // eslint-disable-line react-hooks/exhaustive-deps + }, [antTotalStake.toString(), anjActiveBalance.toString(), activeJurors]) // eslint-disable-line react-hooks/exhaustive-deps } export default useCourtStats diff --git a/src/queries/court.js b/src/queries/court.js index 86f69209..ec294596 100644 --- a/src/queries/court.js +++ b/src/queries/court.js @@ -59,3 +59,14 @@ export const JurorsRegistryModule = gql` } } ` + +export const FeeMovements = gql` + subscription FeeMovements { + feeMovements(where: { type_not: Withdraw }) { + id + type + amount + createdAt + } + } +` From 1c5e00b77e91ff02e1df965a8c3105f5d64b8687 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Wed, 25 Mar 2020 15:56:48 -0300 Subject: [PATCH 13/21] error handler --- src/components/Dashboard/CourtStats.js | 13 ++++---- src/hooks/query-hooks.js | 6 ++-- src/hooks/useCourtContracts.js | 7 ++-- src/hooks/useCourtStats.js | 44 +++++++++++++++----------- 4 files changed, 38 insertions(+), 32 deletions(-) diff --git a/src/components/Dashboard/CourtStats.js b/src/components/Dashboard/CourtStats.js index ce8ae8be..b7f7c3aa 100644 --- a/src/components/Dashboard/CourtStats.js +++ b/src/components/Dashboard/CourtStats.js @@ -1,7 +1,7 @@ import React from 'react' import { Box, GU, textStyle, useTheme } from '@aragon/ui' import { formatUnits } from '../../lib/math-utils' -import useCourtStats, { STAT_NOT_AVAILABLE } from '../../hooks/useCourtStats' +import useCourtStats from '../../hooks/useCourtStats' import { useANJBalanceToUsd, useTokenBalanceToUsd, @@ -49,7 +49,7 @@ function CourtStats() { font-weight: 300; `} > - {stat.value} + {!stat.error ? stat.value : '-'}
)} @@ -61,9 +61,8 @@ function CourtStats() { } function TokenStats({ stat, theme }) { - const { value, token } = stat + const { value, token, error } = stat const { decimals, icon, symbol } = token - const statAvailable = !value.eq(STAT_NOT_AVAILABLE) return ( <>
- {statAvailable ? ( + {!error ? ( ) : ( '-' )} - {statAvailable && ( + {!error && (
$ - {statAvailable + {!error ? symbol === 'ANJ' ? AnjUsdValue(value) : TokenUsdValue(token, value) diff --git a/src/hooks/query-hooks.js b/src/hooks/query-hooks.js index 35b8adb4..a7abacd7 100644 --- a/src/hooks/query-hooks.js +++ b/src/hooks/query-hooks.js @@ -57,11 +57,11 @@ export function useFirstANJActivationQuery(jurorId, { pause = false }) { } export function useActiveJurorsNumber() { - const [result] = useQuery({ + const [{ data, error }] = useQuery({ query: ActiveJurors, }) - const { jurors } = result.data || {} + const { jurors } = data || {} - return jurors?.length + return [jurors?.length, error] } diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index da06ffec..4c6a860c 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -16,7 +16,6 @@ import { retryMax } from '../utils/retry-max' import { useActivity } from '../components/Activity/ActivityProvider' import { networkAgentAddress, networkReserveAddress } from '../networks' import { getKnownToken } from '../utils/known-tokens' -import { STAT_NOT_AVAILABLE } from '../hooks/useCourtStats' import aragonCourtAbi from '../abi/AragonCourt.json' import courtSubscriptionsAbi from '../abi/CourtSubscriptions.json' @@ -583,6 +582,7 @@ export function useActiveBalanceOfAt(juror, termId) { export function useTotalANTStakedPolling(timeout = 1000) { const [totalANTStaked, setTotalANTStaked] = useState(bigNum(-1)) + const [error, setError] = useState(false) const [controlledTimeout, setControlledTimeout] = useState(0) const { address: antAddress } = getKnownToken('ANT') || {} const antContract = useContractReadOnly(antAddress, tokenAbi) @@ -592,7 +592,7 @@ export function useTotalANTStakedPolling(timeout = 1000) { let timeoutId if (getNetworkType() === 'local') { - setTotalANTStaked(STAT_NOT_AVAILABLE) + setError(true) return } if (!antContract) { @@ -611,6 +611,7 @@ export function useTotalANTStakedPolling(timeout = 1000) { }) .catch(err => { console.error(`Error fetching balance: ${err} retrying...`) + setError(true) }) .finally(() => { if (!cancelled) { @@ -630,5 +631,5 @@ export function useTotalANTStakedPolling(timeout = 1000) { } }, [antContract, controlledTimeout, timeout]) - return totalANTStaked + return [totalANTStaked, error] } diff --git a/src/hooks/useCourtStats.js b/src/hooks/useCourtStats.js index 69cb0cbe..dc10a5b9 100644 --- a/src/hooks/useCourtStats.js +++ b/src/hooks/useCourtStats.js @@ -11,6 +11,8 @@ import IconANJ from '../assets/IconANJ.svg' import IconANT from '../assets/IconANT.svg' import IconDAI from '../assets/IconDAI.svg' +export const STAT_NOT_AVAILABLE = bigNum(-2) + const COURT_STATS = [ { label: 'Total Active ANJ', @@ -26,19 +28,15 @@ const COURT_STATS = [ token: { ...getKnownToken('DAI'), icon: IconDAI }, }, ] -export const STAT_NOT_AVAILABLE = bigNum(-2) export function useTotalActiveBalance() { const { data: jurorRegistryStats, error } = useJurorRegistrySubscription() return useMemo(() => { - if (error) { - return [null, error] - } - if (!jurorRegistryStats) { + if (!jurorRegistryStats || error) { return [bigNum(-1), error] } - return [bigNum(jurorRegistryStats?.totalActive) || null, error] + return [bigNum(jurorRegistryStats?.totalActive) || bigNum(-1), error] }, [error, jurorRegistryStats]) } @@ -46,10 +44,7 @@ function useTotalRewards() { const { data: rewards, error } = useTotalRewardsSubscription() return useMemo(() => { - if (error) { - return [null, error] - } - if (!rewards) { + if (!rewards || error) { return [bigNum(-1), error] } return [ @@ -67,19 +62,23 @@ function useTotalRewards() { */ function useCourtStats() { const timeout = 5000 - const [anjActiveBalance, activeBalanceError] = useTotalActiveBalance() - const antTotalStake = useTotalANTStakedPolling(timeout) - const activeJurors = useActiveJurorsNumber() + const [anjActiveBalance, anjActiveBalanceError] = useTotalActiveBalance() + const [antTotalStake, antError] = useTotalANTStakedPolling(timeout) + const [activeJurors, activeJurorsError] = useActiveJurorsNumber() const [totalRewards, totalRewardsError] = useTotalRewards() - console.log('totalREwards ', totalRewards) - console.log('totalRewardsError ', totalRewardsError) - console.log('totalRewardsError ', activeBalanceError) + + // Loading states + const anjFetching = anjActiveBalance.eq(bigNum(-1)) && !anjActiveBalanceError + const antFetching = antTotalStake.eq(bigNum(-1)) && !antError + const activeJurorsFetching = activeJurors === null && !activeJurorsError + const totalRewardsFetching = totalRewards.eq(bigNum(-1)) && !totalRewardsError return useMemo(() => { if ( - anjActiveBalance.eq(bigNum(-1)) || - antTotalStake.eq(bigNum(-1)) || - activeJurors === null + anjFetching || + antFetching || + activeJurorsFetching || + totalRewardsFetching ) { return [null, true] } @@ -90,11 +89,18 @@ function useCourtStats() { activeJurors, totalRewards, ] + const statsError = [ + anjActiveBalanceError, + antError, + activeJurorsError, + totalRewardsError, + ] return [ COURT_STATS.map((stat, index) => { return { ...stat, value: statsData[index], + error: statsError[index], } }), false, From a8a514956286993bd1f159426f45665c420dc644 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Wed, 25 Mar 2020 16:03:28 -0300 Subject: [PATCH 14/21] svg optimization --- src/assets/IconDAI.svg | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/assets/IconDAI.svg b/src/assets/IconDAI.svg index e79a7e41..8a595495 100755 --- a/src/assets/IconDAI.svg +++ b/src/assets/IconDAI.svg @@ -1,7 +1 @@ - - - - - - - + \ No newline at end of file From c8fad43dc9d2ddac135458c0cc75af33033fbb0a Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Wed, 25 Mar 2020 16:26:05 -0300 Subject: [PATCH 15/21] change account banner to use new active balance fetch --- src/components/Dashboard/AccountBanner.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/components/Dashboard/AccountBanner.js b/src/components/Dashboard/AccountBanner.js index e2e66ba0..36afa887 100644 --- a/src/components/Dashboard/AccountBanner.js +++ b/src/components/Dashboard/AccountBanner.js @@ -154,7 +154,7 @@ const Wrapper = ({ mainIcon, information }) => { const BannerWithProbability = ({ activeBalance }) => { const theme = useTheme() - const totalActiveBalanceCurrentTerm = useTotalActiveBalance() + const [totalActiveBalanceCurrentTerm] = useTotalActiveBalance() const fetchingTotalBalance = totalActiveBalanceCurrentTerm.eq(bigNum(-1)) if (fetchingTotalBalance) { From 12bbd39bc0d8f796d428a806f037fbf9e8c79ca1 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Thu, 26 Mar 2020 18:19:46 -0300 Subject: [PATCH 16/21] pr comments --- src/abi/JurorRegistry.json | 1 - src/components/Dashboard/Balance.js | 2 +- src/components/Dashboard/CourtStats.js | 18 +++--- src/components/SplitAmount.js | 2 +- src/hooks/useCourtContracts.js | 9 +-- src/hooks/useCourtStats.js | 81 +++++++++++++++----------- src/hooks/useTokenBalanceToUsd.js | 36 ++++++------ src/networks.js | 4 +- 8 files changed, 84 insertions(+), 69 deletions(-) diff --git a/src/abi/JurorRegistry.json b/src/abi/JurorRegistry.json index 9f6eeb45..e48cbc6c 100644 --- a/src/abi/JurorRegistry.json +++ b/src/abi/JurorRegistry.json @@ -2,7 +2,6 @@ "function activate(uint256 _amount) external", "function deactivate(uint256 _amount) external", "function unstake(uint256 _amount, bytes _data) external", - "function totalActiveBalance() external view returns (uint256)", "function totalActiveBalanceAt(uint64 _termId) external view returns (uint256)", "function activeBalanceOfAt(address _juror, uint64 _termId) external view returns (uint256) " ] diff --git a/src/components/Dashboard/Balance.js b/src/components/Dashboard/Balance.js index dce88044..b713a835 100644 --- a/src/components/Dashboard/Balance.js +++ b/src/components/Dashboard/Balance.js @@ -47,7 +47,7 @@ const Balance = React.memo(function Balance({ `} > {loading ? ( - + ) : ( {stat.label} @@ -45,7 +45,7 @@ function CourtStats() { ) : ( @@ -72,7 +72,7 @@ function TokenStats({ stat, theme }) { > @@ -101,7 +101,7 @@ function TokenStats({ stat, theme }) {
diff --git a/src/components/SplitAmount.js b/src/components/SplitAmount.js index 91dc08d8..32a7a47a 100644 --- a/src/components/SplitAmount.js +++ b/src/components/SplitAmount.js @@ -9,7 +9,7 @@ export default function SplitAmount({ amount }) { margin-right: ${0.5 * GU}px; `} > - {integer} + {integer} {fractional && ( { let cancelled = false let timeoutId @@ -602,11 +603,11 @@ export function useTotalANTStakedPolling(timeout = 1000) { .finally(() => { if (!cancelled) { clearTimeout(timeoutId) - setControlledTimeout(timeout) + controlledTimeout.current = timeout fetchTotalANTBalance() } }) - }, controlledTimeout) + }, controlledTimeout.current) } fetchTotalANTBalance() diff --git a/src/hooks/useCourtStats.js b/src/hooks/useCourtStats.js index dc10a5b9..64bc5977 100644 --- a/src/hooks/useCourtStats.js +++ b/src/hooks/useCourtStats.js @@ -11,8 +11,6 @@ import IconANJ from '../assets/IconANJ.svg' import IconANT from '../assets/IconANT.svg' import IconDAI from '../assets/IconDAI.svg' -export const STAT_NOT_AVAILABLE = bigNum(-2) - const COURT_STATS = [ { label: 'Total Active ANJ', @@ -36,7 +34,7 @@ export function useTotalActiveBalance() { if (!jurorRegistryStats || error) { return [bigNum(-1), error] } - return [bigNum(jurorRegistryStats?.totalActive) || bigNum(-1), error] + return [bigNum(jurorRegistryStats.totalActive), error] }, [error, jurorRegistryStats]) } @@ -63,49 +61,66 @@ function useTotalRewards() { function useCourtStats() { const timeout = 5000 const [anjActiveBalance, anjActiveBalanceError] = useTotalActiveBalance() - const [antTotalStake, antError] = useTotalANTStakedPolling(timeout) + const [antTotalStake, antTotalStakeError] = useTotalANTStakedPolling(timeout) const [activeJurors, activeJurorsError] = useActiveJurorsNumber() const [totalRewards, totalRewardsError] = useTotalRewards() // Loading states const anjFetching = anjActiveBalance.eq(bigNum(-1)) && !anjActiveBalanceError - const antFetching = antTotalStake.eq(bigNum(-1)) && !antError + const antFetching = antTotalStake.eq(bigNum(-1)) && !antTotalStakeError const activeJurorsFetching = activeJurors === null && !activeJurorsError const totalRewardsFetching = totalRewards.eq(bigNum(-1)) && !totalRewardsError - return useMemo(() => { - if ( - anjFetching || - antFetching || - activeJurorsFetching || - totalRewardsFetching - ) { - return [null, true] - } + return useMemo( + () => { + if ( + anjFetching || + antFetching || + activeJurorsFetching || + totalRewardsFetching + ) { + return [null, true] + } - const statsData = [ - anjActiveBalance, - antTotalStake, + const statsData = [ + anjActiveBalance, + antTotalStake, + activeJurors, + totalRewards, + ] + const statsError = [ + anjActiveBalanceError, + antTotalStakeError, + activeJurorsError, + totalRewardsError, + ] + return [ + COURT_STATS.map((stat, index) => { + return { + ...stat, + value: statsData[index], + error: statsError[index], + } + }), + false, + ] + } /* eslint-disable react-hooks/exhaustive-deps */, + [ activeJurors, - totalRewards, - ] - const statsError = [ - anjActiveBalanceError, - antError, activeJurorsError, + activeJurorsFetching, + anjActiveBalance.toString(), + anjActiveBalanceError, + anjFetching, + antFetching, + antTotalStake.toString(), + antTotalStakeError, + totalRewards.toString(), totalRewardsError, + totalRewardsFetching, ] - return [ - COURT_STATS.map((stat, index) => { - return { - ...stat, - value: statsData[index], - error: statsError[index], - } - }), - false, - ] - }, [antTotalStake.toString(), anjActiveBalance.toString(), activeJurors]) // eslint-disable-line react-hooks/exhaustive-deps + /* eslint-disable-line react-hooks/exhaustive-deps */ + ) } export default useCourtStats diff --git a/src/hooks/useTokenBalanceToUsd.js b/src/hooks/useTokenBalanceToUsd.js index c9ab1350..7fb30416 100644 --- a/src/hooks/useTokenBalanceToUsd.js +++ b/src/hooks/useTokenBalanceToUsd.js @@ -115,27 +115,27 @@ export function useTokenBalanceToUsd(symbol, decimals, balance) { useEffect(() => { let cancelled = false - if (getNetworkType() === 'main') { - fetch(`${API_BASE}/price?fsym=${symbol}&tsyms=USD`) - .then(res => res.json()) - .then(price => { - if (cancelled || !balance || !(parseFloat(price.USD) > 0)) { - return - } + if (getNetworkType() !== 'main') { + return + } - const usdDigits = 2 - const precision = 6 + fetch(`${API_BASE}/price?fsym=${symbol}&tsyms=USD`) + .then(res => res.json()) + .then(price => { + if (cancelled || !balance || !(parseFloat(price.USD) > 0)) { + return + } - const usdBalance = balance - .mul( - bigNum(parseInt(price.USD * 10 ** (precision + usdDigits), 10)) - ) - .div(10 ** precision) - .div(bigNum(10).pow(decimals)) + const usdDigits = 2 + const precision = 6 - setUsd(formatUnits(usdBalance, { digits: usdDigits })) - }) - } + const usdBalance = balance + .mul(bigNum(parseInt(price.USD * 10 ** (precision + usdDigits), 10))) + .div(10 ** precision) + .div(bigNum(10).pow(decimals)) + + setUsd(formatUnits(usdBalance, { digits: usdDigits })) + }) return () => { cancelled = true diff --git a/src/networks.js b/src/networks.js index c8abeea0..f8453aad 100644 --- a/src/networks.js +++ b/src/networks.js @@ -42,8 +42,8 @@ export const networkConfigs = { }, } -export function getNetworkConfig(chainId) { - return networkConfigs[chainId] +export function getNetworkConfig(networkType) { + return networkConfigs[networkType] } export const networkAgentAddress = From 85d073bc2842957cf75611dc0e9d6c2f8f76d750 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Thu, 26 Mar 2020 21:08:47 -0300 Subject: [PATCH 17/21] network rename --- src/endpoints.js | 2 +- .../precedence-campaign-disputes.js | 16 ++++--- src/flagged-disputes/voided-disputes.js | 23 +++++---- src/hooks/useCourtContracts.js | 10 ++-- src/lib/web3-utils.js | 4 +- src/networks.js | 47 ++++++++++++------- src/providers/CourtConfig.js | 10 ++-- src/web3-contracts.js | 5 +- 8 files changed, 66 insertions(+), 51 deletions(-) diff --git a/src/endpoints.js b/src/endpoints.js index 8b093682..53a5206a 100644 --- a/src/endpoints.js +++ b/src/endpoints.js @@ -27,7 +27,7 @@ function getAPIBase() { export default function endpoints() { const [API_BASE_HTTP, API_BASE_WS] = getAPIBase() const networkType = - getNetworkType(CHAIN_ID) === 'local' ? 'rpc' : getNetworkType(CHAIN_ID) + getNetworkType(CHAIN_ID) === 'private' ? 'rpc' : getNetworkType(CHAIN_ID) const API_PATH = networkType === 'main' diff --git a/src/flagged-disputes/precedence-campaign-disputes.js b/src/flagged-disputes/precedence-campaign-disputes.js index 8eac529a..8def981f 100644 --- a/src/flagged-disputes/precedence-campaign-disputes.js +++ b/src/flagged-disputes/precedence-campaign-disputes.js @@ -1,25 +1,27 @@ import { networks, + getNetwork, + getInternalNetworkName, RINKEBY_COURT, RINKEBY_STAGING_COURT, RINKEBY_USABILITY_COURT, } from '../networks' -import { getNetworkType } from '../lib/web3-utils' const PRECEDENCE_CAMPAIGN_DISPUTES = { - rpc: new Map([[networks.rpc.court, ['0']]]), - ropsten: new Map([[networks.ropsten.court, []]]), + main: new Map([[networks.main.court, []]]), rinkeby: new Map([ [RINKEBY_COURT, []], [RINKEBY_STAGING_COURT, []], [RINKEBY_USABILITY_COURT, []], ]), - main: new Map([[networks.main.court, []]]), + ropsten: new Map([[networks.ropsten.court, []]]), + local: new Map([[networks.local.court, ['0']]]), } export function getPrecedenceCampaignDisputesByCourt() { - const networkType = getNetworkType() - const courtAddress = networks[networkType].court + const courtAddress = getNetwork().court - return PRECEDENCE_CAMPAIGN_DISPUTES[networkType].get(courtAddress) + return PRECEDENCE_CAMPAIGN_DISPUTES[getInternalNetworkName()].get( + courtAddress + ) } diff --git a/src/flagged-disputes/voided-disputes.js b/src/flagged-disputes/voided-disputes.js index 096878a1..b93fbce3 100644 --- a/src/flagged-disputes/voided-disputes.js +++ b/src/flagged-disputes/voided-disputes.js @@ -1,20 +1,14 @@ import { networks, + getInternalNetworkName, + getNetwork, RINKEBY_COURT, RINKEBY_STAGING_COURT, RINKEBY_USABILITY_COURT, } from '../networks' -import { getNetworkType } from '../lib/web3-utils' import env from '../environment' const VOIDED_DISPUTES = { - local: new Map([[networks.local.court, new Map([])]]), - ropsten: new Map([[networks.ropsten.court, new Map([])]]), - rinkeby: new Map([ - [RINKEBY_COURT, new Map([])], - [RINKEBY_USABILITY_COURT, new Map([])], - [RINKEBY_STAGING_COURT, new Map([])], - ]), main: new Map([ [ networks.main.court, @@ -32,15 +26,20 @@ const VOIDED_DISPUTES = { ), ], ]), + rinkeby: new Map([ + [RINKEBY_COURT, new Map([])], + [RINKEBY_USABILITY_COURT, new Map([])], + [RINKEBY_STAGING_COURT, new Map([])], + ]), + ropsten: new Map([[networks.ropsten.court, new Map([])]]), + local: new Map([[networks.local.court, new Map([])]]), } export function getVoidedDisputesByCourt() { if (env('SKIP_VOIDING')) { return new Map([]) } + const courtAddress = getNetwork().court - const networkType = getNetworkType() - const courtAddress = networks[networkType].court - - return VOIDED_DISPUTES[networkType].get(courtAddress) + return VOIDED_DISPUTES[getInternalNetworkName()].get(courtAddress) } diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index db348dd3..9496709d 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -3,7 +3,7 @@ import { captureException } from '@sentry/browser' import { CourtModuleType } from '../types/court-module-types' import { useContract, useContractReadOnly } from '../web3-contracts' import { useCourtConfig } from '../providers/CourtConfig' -import { getFunctionSignature, getNetworkType } from '../lib/web3-utils' +import { getFunctionSignature } from '../lib/web3-utils' import { bigNum, formatUnits } from '../lib/math-utils' import { hashVote, @@ -14,7 +14,11 @@ import { import { getModuleAddress } from '../utils/court-utils' import { retryMax } from '../utils/retry-max' import { useActivity } from '../components/Activity/ActivityProvider' -import { networkAgentAddress, networkReserveAddress } from '../networks' +import { + networkAgentAddress, + networkReserveAddress, + getInternalNetworkName, +} from '../networks' import { getKnownToken } from '../utils/known-tokens' import aragonCourtAbi from '../abi/AragonCourt.json' @@ -578,7 +582,7 @@ export function useTotalANTStakedPolling(timeout = 1000) { let cancelled = false let timeoutId - if (getNetworkType() === 'local') { + if (getInternalNetworkName() === 'local') { setError(true) return } diff --git a/src/lib/web3-utils.js b/src/lib/web3-utils.js index 35250456..01029b3a 100644 --- a/src/lib/web3-utils.js +++ b/src/lib/web3-utils.js @@ -3,7 +3,7 @@ import { solidityKeccak256, id as keccak256 } from 'ethers/utils' export const soliditySha3 = solidityKeccak256 export const hash256 = keccak256 -export const DEFAULT_LOCAL_CHAIN = 'local' +export const DEFAULT_LOCAL_CHAIN = 'private' export const ETH_FAKE_ADDRESS = `0x${''.padEnd(40, '0')}` const ETH_ADDRESS_SPLIT_REGEX = /(0x[a-fA-F0-9]{40}(?:\b|\.|,|\?|!|;))/g @@ -123,7 +123,7 @@ export function getNetworkName(chainId = env('CHAIN_ID')) { return 'unknown' } -export function isLocalOrUnknownNetwork(chainId) { +export function isLocalOrUnknownNetwork(chainId = env('CHAIN_ID')) { return getNetworkType(chainId) === DEFAULT_LOCAL_CHAIN } diff --git a/src/networks.js b/src/networks.js index f8453aad..8f27d45b 100644 --- a/src/networks.js +++ b/src/networks.js @@ -1,5 +1,5 @@ import environment from './environment' -import { getNetworkType } from './lib/web3-utils' +import { getNetworkType, isLocalOrUnknownNetwork } from './lib/web3-utils' const SUBGRAPH_NAME = environment('SUBGRAPH_NAME') @@ -11,25 +11,20 @@ export const RINKEBY_STAGING_COURT = '0x52180Af656A1923024D1ACcF1D827AB85cE48878' export const networks = { - local: { court: '0xD833215cBcc3f914bD1C9ece3EE7BF8B14f841bb' }, - ropsten: { court: '0x3b26bc496aebaed5b3E0E81cDE6B582CDe71396e' }, - rinkeby: { - // Use the 'usability' Court address if declared - court: getRinkebyCourtAddress(SUBGRAPH_NAME), - }, main: { court: '0xee4650cBe7a2B23701D416f58b41D8B76b617797', network_agent: '0x5e8c17a6065c35b172b10e80493d2266e2947df4', network_reserve: '0xec0dd1579551964703246becfbf199c27cb84485', }, + rinkeby: { + // Use the 'usability' Court address if declared + court: getRinkebyCourtAddress(SUBGRAPH_NAME), + }, + ropsten: { court: '0x3b26bc496aebaed5b3E0E81cDE6B582CDe71396e' }, + local: { court: '0xD833215cBcc3f914bD1C9ece3EE7BF8B14f841bb' }, } export const networkConfigs = { - local: { - nodes: { - defaultEth: 'http://localhost:8545', - }, - }, main: { nodes: { defaultEth: 'https://mainnet.eth.aragon.network/', @@ -40,17 +35,33 @@ export const networkConfigs = { defaultEth: 'https://rinkeby.eth.aragon.network/', }, }, + ropsten: { + nodes: { + defaultEth: 'https://ropsten.eth.aragon.network/', + }, + }, + local: { + nodes: { + defaultEth: 'http://localhost:8545', + }, + }, +} + +export function getInternalNetworkName() { + return isLocalOrUnknownNetwork() ? 'local' : getNetworkType() +} + +export function getNetwork() { + return networks[getInternalNetworkName()] } -export function getNetworkConfig(networkType) { - return networkConfigs[networkType] +export function getNetworkConfig() { + return networkConfigs[getInternalNetworkName()] } -export const networkAgentAddress = - networks[getNetworkType(environment('CHAIN_ID'))].network_agent +export const networkAgentAddress = getNetwork().network_agent -export const networkReserveAddress = - networks[getNetworkType(environment('CHAIN_ID'))].network_reserve +export const networkReserveAddress = getNetwork().network_reserve function getRinkebyCourtAddress(subGraphName) { if (subGraphName === 'usability') { diff --git a/src/providers/CourtConfig.js b/src/providers/CourtConfig.js index 434bec5d..05be8b08 100644 --- a/src/providers/CourtConfig.js +++ b/src/providers/CourtConfig.js @@ -1,15 +1,15 @@ import React, { useContext } from 'react' import PropTypes from 'prop-types' -import environment from '../environment' +// import environment from '../environment' import { useCourtConfigSubscription } from '../hooks/subscription-hooks' -import { getNetworkType } from '../lib/web3-utils' -import { networks } from '../networks' +// import { getNetworkType } from '../lib/web3-utils' +import { getNetwork } from '../networks' -const CHAIN_ID = environment('CHAIN_ID') +// const CHAIN_ID = environment('CHAIN_ID') const CourtConfigContext = React.createContext() function CourtConfigProvider({ children }) { - const courtAddress = networks[getNetworkType(CHAIN_ID)].court + const courtAddress = getNetwork().court const courtConfig = useCourtConfigSubscription(courtAddress) return ( diff --git a/src/web3-contracts.js b/src/web3-contracts.js index b81efab4..4eeae2b1 100644 --- a/src/web3-contracts.js +++ b/src/web3-contracts.js @@ -1,8 +1,7 @@ import { useMemo } from 'react' import { Contract as EthersContract, providers as Providers } from 'ethers' import { useWallet } from './providers/Wallet' -import { getNetworkType } from './lib/web3-utils' -import { networkConfigs } from './networks' +import { getNetworkConfig } from './networks' export function useContract(address, abi, signer = true) { const { account, ethers } = useWallet() @@ -24,7 +23,7 @@ export function useContract(address, abi, signer = true) { } export function useContractReadOnly(address, abi) { - const ethEndpoint = networkConfigs[getNetworkType()].nodes.defaultEth + const ethEndpoint = getNetworkConfig().nodes.defaultEth const ethProvider = useMemo( () => (ethEndpoint ? new Providers.JsonRpcProvider(ethEndpoint) : null), From e3d0123e8a997ac75db6faf035e1d3eb77223941 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Thu, 26 Mar 2020 21:45:28 -0300 Subject: [PATCH 18/21] pr comments --- src/components/Dashboard/CourtStats.js | 2 +- src/hooks/query-hooks.js | 4 +--- src/hooks/subscription-hooks.js | 4 ++-- src/hooks/useCourtContracts.js | 2 ++ src/hooks/useCourtStats.js | 7 +++++-- src/networks.js | 2 +- 6 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/components/Dashboard/CourtStats.js b/src/components/Dashboard/CourtStats.js index 938a13ea..89848e5f 100644 --- a/src/components/Dashboard/CourtStats.js +++ b/src/components/Dashboard/CourtStats.js @@ -90,7 +90,7 @@ function TokenStats({ stat, theme }) { > { let cancelled = false let timeoutId + // Since we don't have the ANT contract address on the local environment we are skipping the stat if (getInternalNetworkName() === 'local') { setError(true) return diff --git a/src/hooks/useCourtStats.js b/src/hooks/useCourtStats.js index 64bc5977..309d2f83 100644 --- a/src/hooks/useCourtStats.js +++ b/src/hooks/useCourtStats.js @@ -11,6 +11,8 @@ import IconANJ from '../assets/IconANJ.svg' import IconANT from '../assets/IconANT.svg' import IconDAI from '../assets/IconDAI.svg' +const STATS_FETCHING_TIMEOUT = 15000 + const COURT_STATS = [ { label: 'Total Active ANJ', @@ -59,9 +61,10 @@ function useTotalRewards() { * @returns {Array} First item an array with the stats and the second one a loading state */ function useCourtStats() { - const timeout = 5000 const [anjActiveBalance, anjActiveBalanceError] = useTotalActiveBalance() - const [antTotalStake, antTotalStakeError] = useTotalANTStakedPolling(timeout) + const [antTotalStake, antTotalStakeError] = useTotalANTStakedPolling( + STATS_FETCHING_TIMEOUT + ) const [activeJurors, activeJurorsError] = useActiveJurorsNumber() const [totalRewards, totalRewardsError] = useTotalRewards() diff --git a/src/networks.js b/src/networks.js index 8f27d45b..42deef80 100644 --- a/src/networks.js +++ b/src/networks.js @@ -17,7 +17,7 @@ export const networks = { network_reserve: '0xec0dd1579551964703246becfbf199c27cb84485', }, rinkeby: { - // Use the 'usability' Court address if declared + // Use the 'usability' or 'staging' Court address if declared court: getRinkebyCourtAddress(SUBGRAPH_NAME), }, ropsten: { court: '0x3b26bc496aebaed5b3E0E81cDE6B582CDe71396e' }, From f860cbd02d44b68bd28c4effc18d967f43d897f7 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Fri, 27 Mar 2020 13:15:34 -0300 Subject: [PATCH 19/21] Update src/hooks/useCourtContracts.js Co-Authored-By: Brett Sun --- src/hooks/useCourtContracts.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index 59ecb201..3a6da8fe 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -576,7 +576,7 @@ export function useTotalANTStakedPolling(timeout = 1000) { const { address: antAddress } = getKnownToken('ANT') || {} const antContract = useContractReadOnly(antAddress, tokenAbi) - // We are starting in 0 in order to inmediately make the fetch call + // We are starting in 0 in order to immediately make the fetch call const controlledTimeout = useRef(0) useEffect(() => { From c64c68a52b81301017fa3b579295c855a8f24907 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Fri, 27 Mar 2020 13:16:47 -0300 Subject: [PATCH 20/21] pr comments --- src/providers/CourtConfig.js | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/providers/CourtConfig.js b/src/providers/CourtConfig.js index 05be8b08..1da2b14a 100644 --- a/src/providers/CourtConfig.js +++ b/src/providers/CourtConfig.js @@ -1,11 +1,8 @@ import React, { useContext } from 'react' import PropTypes from 'prop-types' -// import environment from '../environment' import { useCourtConfigSubscription } from '../hooks/subscription-hooks' -// import { getNetworkType } from '../lib/web3-utils' import { getNetwork } from '../networks' -// const CHAIN_ID = environment('CHAIN_ID') const CourtConfigContext = React.createContext() function CourtConfigProvider({ children }) { From 4af9458f492b3c9ea6a50396a7e304b2179d53e5 Mon Sep 17 00:00:00 2001 From: Rodrigo Perez Date: Fri, 27 Mar 2020 13:48:00 -0300 Subject: [PATCH 21/21] pr comments --- src/endpoints.js | 5 +++-- src/hooks/useCourtContracts.js | 13 ++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/endpoints.js b/src/endpoints.js index 53a5206a..ec9f8ff9 100644 --- a/src/endpoints.js +++ b/src/endpoints.js @@ -26,8 +26,9 @@ function getAPIBase() { export default function endpoints() { const [API_BASE_HTTP, API_BASE_WS] = getAPIBase() - const networkType = - getNetworkType(CHAIN_ID) === 'private' ? 'rpc' : getNetworkType(CHAIN_ID) + const networkType = isLocalOrUnknownNetwork() + ? 'rpc' + : getNetworkType(CHAIN_ID) const API_PATH = networkType === 'main' diff --git a/src/hooks/useCourtContracts.js b/src/hooks/useCourtContracts.js index 3a6da8fe..92a8b48c 100644 --- a/src/hooks/useCourtContracts.js +++ b/src/hooks/useCourtContracts.js @@ -3,7 +3,10 @@ import { captureException } from '@sentry/browser' import { CourtModuleType } from '../types/court-module-types' import { useContract, useContractReadOnly } from '../web3-contracts' import { useCourtConfig } from '../providers/CourtConfig' -import { getFunctionSignature } from '../lib/web3-utils' +import { + getFunctionSignature, + isLocalOrUnknownNetwork, +} from '../lib/web3-utils' import { bigNum, formatUnits } from '../lib/math-utils' import { hashVote, @@ -14,11 +17,7 @@ import { import { getModuleAddress } from '../utils/court-utils' import { retryMax } from '../utils/retry-max' import { useActivity } from '../components/Activity/ActivityProvider' -import { - networkAgentAddress, - networkReserveAddress, - getInternalNetworkName, -} from '../networks' +import { networkAgentAddress, networkReserveAddress } from '../networks' import { getKnownToken } from '../utils/known-tokens' import aragonCourtAbi from '../abi/AragonCourt.json' @@ -584,7 +583,7 @@ export function useTotalANTStakedPolling(timeout = 1000) { let timeoutId // Since we don't have the ANT contract address on the local environment we are skipping the stat - if (getInternalNetworkName() === 'local') { + if (isLocalOrUnknownNetwork()) { setError(true) return }