Skip to content

Commit

Permalink
Merge pull request #370 from consensusnetworks/feature/dynamic-chart-…
Browse files Browse the repository at this point in the history
…colors

Feature/dynamic chart colors
  • Loading branch information
ccali11 authored Jul 12, 2023
2 parents 4a4ab39 + eb6ca9b commit f58d3b2
Show file tree
Hide file tree
Showing 19 changed files with 605 additions and 1,429 deletions.
11 changes: 11 additions & 0 deletions apps/web/public/trustwallet.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
11 changes: 10 additions & 1 deletion apps/web/src/App.vue
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
<script lang="ts" setup>
import { RouterView } from 'vue-router'
import DefaultLayout from '@/layouts/default-layout.vue'
import useTxData from '@/mockData/mock_transaction_data'
import { onMounted } from 'vue'
import useUsers from '@/composables/users'
const { mockData } = useTxData()
// Need this to fix initilizing bug between user.ts and ssv.ts
const { user } = useUsers()
onMounted(() => {
mockData()
})
</script>

<template>
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/components/charts/LineChartJS.vue
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ watch(props, ()=> {
let rgb = hexToRGB(line_chart.data.datasets[i].backgroundColor)
gradient.addColorStop(0, `rgba(${rgb?.r},${rgb?.g},${rgb?.b}, 0.28)`)
gradient.addColorStop(1, 'rgba(0, 0, 0,0)')
gradient.addColorStop(1, 'rgba(0, 0, 0, 0.0)')
line_chart.data.datasets[i].backgroundColor = gradient
}
Expand Down
62 changes: 44 additions & 18 deletions apps/web/src/composables/contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,15 +22,14 @@ const stakingRewards = ref<BreakdownAmount>({
exchange: '0 ETH'
})

const totalDeposited = ref<BreakdownAmount>({
const totalWalletBalance = ref<BreakdownAmount>({
usd: '$0.00',
exchange: '0 ETH'
})

export default function useContracts() {

const { ethereumUrl, managerAddress, viewsAddress } = useEnvironment()
const { ethersProviderList, getEthersBrowserSigner } = useEthers()
const { ethersProviderList, getEthersBalance, getEthersBrowserSigner } = useEthers()
const { getEthersLedgerSigner } = useLedger()
const { getCurrentPrice } = usePrice()
const { getEthersTrezorSigner } = useTrezor()
Expand Down Expand Up @@ -79,9 +78,11 @@ export default function useContracts() {
const totalStaked = currentStaked.reduce((accumulator, currentValue) => accumulator.add(currentValue), ethers.BigNumber.from(0))
const totalStakedUSD = parseFloat(ethers.utils.formatEther(totalStaked)) * (await getCurrentPrice({ coin: 'ETH', currency: 'USD' }))
const totalStakedETH = parseFloat(ethers.utils.formatEther(totalStaked))
const formattedTotalStakedUSD = formatNumber(totalStakedUSD)
const formattedTotalStakedETH = formatNumber(totalStakedETH)
return {
exchange: totalStakedETH.toFixed(2) + ' ETH',
usd: '$ ' + totalStakedUSD.toFixed(2)
exchange: formattedTotalStakedUSD + ' ETH',
usd: '$ ' + formattedTotalStakedETH
}
} catch (error) {
console.log('Error occurred while fetching stake:', error)
Expand All @@ -92,7 +93,6 @@ export default function useContracts() {
}
}


async function getDepositFees() {
const provider = new ethers.providers.JsonRpcProvider(ethereumUrl)
const fees = await manager.connect(provider).feePercent()
Expand Down Expand Up @@ -172,15 +172,31 @@ export default function useContracts() {
}))
}

async function getTotalDeposited() : Promise<BreakdownAmount> {
// async function getStakingRewards() : Promise<BreakdownAmount> {
// const addresses = (user.value as UserWithAccounts).accounts.map((account: Account) => account.address) as string[]
// const promises = [] as Array<Promise<ethers.BigNumber>>
// // TODO: Replace .getUserRewards with actual method that get's rewards OR figure out how to derive rewards
// addresses.forEach((address) => {promises.push(manager.connect(provider).getUserRewards(address))})
// const stakingRewards = (await Promise.all(promises)).reduce((a, b) => a.add(b))
// const stakingRewardsUSD = parseFloat(ethers.utils.formatEther(stakingRewards)) * (await getCurrentPrice({ coin: 'ETH', currency: 'USD' }))
// const stakingRewardsETH = parseFloat(ethers.utils.formatEther(stakingRewards))
// return {
// exchange: stakingRewardsETH.toFixed(2) + ' ETH',
// usd: '$ ' + stakingRewardsUSD.toFixed(2)
// }
// }

async function getTotalWalletBalance() : Promise<BreakdownAmount> {
const promises = [] as Array<Promise<any>>
const addresses = (user.value as UserWithAccounts).accounts.map((account: Account) => account.address) as string[]
addresses.forEach((address) => { promises.push(getUserContractEventsTotals(address)) })
const totalDeposited = (await Promise.all(promises)).reduce((acc, curr) => acc + curr.StakeDeposited, 0)
const totalDepositedUSD = totalDeposited * (await getCurrentPrice({ coin: 'ETH', currency: 'USD' }))
addresses.forEach((address) => { promises.push(getEthersBalance(address)) })
const totalWalletBalance = (await Promise.all(promises)).reduce((acc, curr) => acc + curr, 0)
const totalWalletBalanceUSD = totalWalletBalance * (await getCurrentPrice({ coin: 'ETH', currency: 'USD' }))
const formattedTotalWalletBalance = formatNumber(totalWalletBalance)
const formattedTotalWalletBalanceUSD = formatNumber(totalWalletBalanceUSD)
return {
exchange: totalDeposited.toFixed(2) + ' ETH',
usd: '$ ' + totalDepositedUSD.toFixed(2)
exchange: formattedTotalWalletBalance + ' ETH',
usd: '$ ' + formattedTotalWalletBalanceUSD
}
}

Expand Down Expand Up @@ -222,8 +238,8 @@ export default function useContracts() {

async function refreshBreakdown() {
setBreakdownValue({ name: 'currentStaked', ...await getCurrentStaked() })
// setBreakdownValue({ name: 'totalDeposited', ...await getTotalDeposited() })
// setBreakdownValue({ name: 'stakingRewards', ...await getStakingRewards() })
setBreakdownValue({ name: 'totalWalletBalance', ...await getTotalWalletBalance() })
// setBreakdownValue({ name: 'stakingRewardsEarned', ...await getStakingRewards() })
}

function setBreakdownValue({ name, exchange, usd }: { name: BreakdownString, exchange: string, usd: string}) {
Expand All @@ -234,13 +250,13 @@ export default function useContracts() {
usd
}
break
case 'totalDeposited':
totalDeposited.value = {
case 'totalWalletBalance':
totalWalletBalance.value = {
exchange,
usd
}
break
case 'stakingRewards':
case 'stakingRewardsEarned':
stakingRewards.value = {
exchange,
usd
Expand Down Expand Up @@ -271,7 +287,7 @@ export default function useContracts() {
currentStaked,
manager,
stakingRewards,
totalDeposited,
totalWalletBalance,
deposit,
getCurrentStaked,
getDepositFees,
Expand All @@ -280,4 +296,14 @@ export default function useContracts() {
refreshBreakdown,
withdraw
}
}

function formatNumber(number: number) {
const SI_SYMBOL = ['', 'K', 'M', 'B', 'T', 'P', 'E']
const tier = Math.log10(Math.abs(number)) / 3 | 0
if(tier === 0) return number.toFixed(2)
const suffix = SI_SYMBOL[tier]
const scale = Math.pow(10, tier * 3)
const scaled = number / scale
return scaled.toFixed(2) + suffix
}
8 changes: 4 additions & 4 deletions apps/web/src/composables/ethers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export default function useEthers() {
// const gasEstimateInEth = ethers.utils.formatEther(gasEstimate)
const fee = maxPriorityFeePerGasInWei?.mul(gasEstimate).add(maxFeePerGasInWei)
const feeInWei = ethers.utils.formatEther(fee)
const feeInEth = (parseInt(feeInWei) / 10**18).toFixed(8).toString()
const feeInEth = (parseFloat(feeInWei) / 10**18).toFixed(8).toString()
return {
gasLimit: gasEstimate.toString(),
fee: feeInEth
Expand All @@ -85,7 +85,7 @@ export default function useEthers() {
const gasEstimate = await provider.estimateGas(unsignedTransaction as ethers.utils.Deferrable<ethers.providers.TransactionRequest>)
const fee = gasPrice.mul(gasEstimate)
const feeInWei = ethers.utils.formatEther(fee)
const feeInEth = (parseInt(feeInWei) / 10**18).toFixed(8).toString()
const feeInEth = (parseFloat(feeInWei) / 10**18).toFixed(8).toString()
return {
gasLimit: gasEstimate.toString(),
fee: feeInEth
Expand Down Expand Up @@ -146,7 +146,7 @@ export default function useEthers() {

async function getMaxETHAfterFees(rpcUrl: string, unsignedTx: ethers.utils.Deferrable<ethers.providers.TransactionRequest>, totalAmount: string) {
const { fee } = await estimateEIP1559GasFee(rpcUrl, unsignedTx)
const total = parseInt(totalAmount) - parseInt(fee)
const total = parseFloat(totalAmount) - parseFloat(fee)
const maxAfterFees = ethers.utils.formatEther(total).toString()
return maxAfterFees
}
Expand Down Expand Up @@ -214,7 +214,7 @@ export default function useEthers() {
}
const ethFees = await estimateEIP1559GasFee(ethereumUrl, tx)
const { fee, gasLimit } = ethFees
const requiredBalance = parseInt(value) + parseInt(fee)
const requiredBalance = parseFloat(value) + parseFloat(fee)
const balance = await getEthersBalance(from)
if (balance < requiredBalance) {
throw new Error('Insufficient balance')
Expand Down
19 changes: 6 additions & 13 deletions apps/web/src/composables/router.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createWebHistory, createRouter } from 'vue-router'
import useUsers from '@/composables/users'
import Overview from '@/pages/overview/Overview.vue'
import Test from '@/pages/test/Test.vue'

Expand Down Expand Up @@ -28,18 +29,10 @@ const router = createRouter({
// TO DO: Add a routing beforeEach that
// dynamically fixes rerouting to auth page

// router.beforeEach(async (to, from, next) => {
// if (import.meta.env.DEV) {
// const appLaunched = sessionStorage.getItem('appLaunch')
// if (!appLaunched) {
// const { logout } = useWallet()
// await logout()
// sessionStorage.setItem('appLaunch', 'true')
// }
// }

// const { checkUserSessionExists } = useUsers()
// const loggedIn = await checkUserSessionExists()
router.beforeEach(async (to, from, next) => {
const { checkUserSessionExists } = useUsers()
await checkUserSessionExists()
next()
// if (to.fullPath === '/auth' && !loggedIn) {
// next()
// } else if (to.fullPath === '/auth' && loggedIn) {
Expand All @@ -49,6 +42,6 @@ const router = createRouter({
// } else {
// next()
// }
// })
})

export default router
Loading

0 comments on commit f58d3b2

Please sign in to comment.