Skip to content

Commit

Permalink
Merge pull request #222 from G7DAO/feat/network-toggle
Browse files Browse the repository at this point in the history
Feat/network toggle
  • Loading branch information
elclandestin0 authored Dec 4, 2024
2 parents 0c24f25 + 7a03950 commit ef888e5
Show file tree
Hide file tree
Showing 15 changed files with 147 additions and 127 deletions.
6 changes: 1 addition & 5 deletions webapps/world-builder-dashboard/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ export const L2_MAIN_NETWORK: NetworkInterface = {
symbol: 'ETH'
},
g7TokenAddress: '0xF18e4466F26B4cA55bbAb890b314a54976E45B17',
routerSpender: '0x902b3e5f8f19571859f4ab1003b960a5df693aff',
retryableCreationTimeout: 15 * 60
}

Expand All @@ -97,7 +96,6 @@ export const L3_MAIN_NETWORK: NetworkInterface = {
symbol: 'G7T'
},
g7TokenAddress: '0x0000000000000000000000000000000000000000',
routerSpender: '0x902b3e5f8f19571859f4ab1003b960a5df693aff',
retryableCreationTimeout: 15 * 60,
wrappedG7TokenAddress: '0xfa3ed70386b9255fC04aA008A8ad1B0CDa816Fac'
}
Expand Down Expand Up @@ -128,8 +126,6 @@ export const FIVE_MINUTES = 1000 * 60 * 5

export const DEFAULT_STAKE_NATIVE_POOL_ID = '1'

export const MAX_ALLOWANCE_ACCOUNT = '0x9ed191DB1829371F116Deb9748c26B49467a592A'

export const TG7T: TokenAddressMap = {
13746: '0x0000000000000000000000000000000000000000',
421614: '0x10adbf84548f923577be12146eac104c899d1e75',
Expand All @@ -143,7 +139,7 @@ export const ETH: TokenAddressMap = {

export const USDC: TokenAddressMap = {
13746: '0xf2B58E3519C5b977a254993A4A6EaD581A8989A0',
421614: '0x119f0E6303BEc7021B295EcaB27A4a1A5b37ECf0',
421614: '0x75faf114eafb1BDbe2F0316DF893fd58CE46AA4d',
11155111: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238'
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import React from 'react'

const IconTokenNoSynbol: React.FC<React.SVGProps<SVGSVGElement>> = () => (
const IconTokenNoSymbol: React.FC<React.SVGProps<SVGSVGElement>> = () => (
<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24' fill='none'>
<path
fillRule='evenodd'
Expand All @@ -15,4 +15,4 @@ const IconTokenNoSynbol: React.FC<React.SVGProps<SVGSVGElement>> = () => (
</svg>
)

export default IconTokenNoSynbol
export default IconTokenNoSymbol
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,10 @@ const ActionButton: React.FC<ActionButtonProps> = ({
completionTimestamp: Date.now() / 1000,
newTransaction: true,
symbol: symbol,
status: BridgeTransferStatus.DEPOSIT_GAS_PENDING
status:
selectedBridgeToken.address === ZERO_ADDRESS
? BridgeTransferStatus.DEPOSIT_GAS_PENDING
: BridgeTransferStatus.DEPOSIT_ERC20_NOT_YET_CREATED
}
} else {
const tx = await bridger?.transfer({ amount: amountToSend, signer, destinationProvider })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import { useCoinGeckoAPI } from '@/hooks/useCoinGeckoAPI'
// Hooks and Constants
import { DepositDirection } from '@/pages/BridgePage/BridgePage'
import { getStakeNativeTxData } from '@/utils/bridge/stakeContractInfo'
import { Token } from '@/utils/tokens'
import { getTokensForNetwork, Token } from '@/utils/tokens'

const BridgeView = ({
direction,
Expand All @@ -56,13 +56,19 @@ const BridgeView = ({
setSelectedHighNetwork,
setSelectedBridgeToken,
selectedBridgeToken,
selectedNetworkType
selectedNetworkType,
setSelectedNativeToken,
selectedNativeToken
} = useBlockchainContext()

const { isFetching: isFetchingTokenInformation, data: tokenInformation } = useTokenInformation({
account: connectedAccount,
token: selectedBridgeToken
})
const { data: nativeTokenInformation } = useTokenInformation({
account: connectedAccount,
token: selectedNativeToken
})

const { data: coinUSDRate, isFetching: isCoinFetching } = useUSDPriceOfToken(selectedBridgeToken.geckoId ?? '')
const handleTokenChange = async (token: Token) => {
Expand Down Expand Up @@ -126,6 +132,20 @@ const BridgeView = ({
return
}
try {
if (direction === 'DEPOSIT') {
const token =
getTokensForNetwork(selectedLowNetwork.chainId, connectedAccount).find(
(token) => token.symbol === selectedLowNetwork.nativeCurrency?.symbol
) ?? null
setSelectedNativeToken(token)
} else if (direction === 'WITHDRAW') {
const token =
getTokensForNetwork(selectedLowNetwork.chainId, connectedAccount).find(
(token) => token.symbol === selectedLowNetwork.nativeCurrency?.symbol
) ?? null

setSelectedNativeToken(token)
}
const _bridger: Bridger = new Bridger(originChainId, destinationChainId, selectedBridgeToken.tokenAddressMap)
setBridger(_bridger)
} catch (e) {
Expand Down Expand Up @@ -252,8 +272,8 @@ const BridgeView = ({
)}
<TransactionSummary
direction={direction}
gasBalance={Number(tokenInformation?.tokenBalance)}
address={connectedAccount}
nativeBalance={Number(nativeTokenInformation?.tokenBalance)}
transferTime={
direction === 'DEPOSIT'
? `~${Math.floor((selectedLowNetwork.retryableCreationTimeout ?? 0) / 60)} min`
Expand All @@ -277,7 +297,7 @@ const BridgeView = ({
? 0.0
: coinUSDRate[selectedBridgeToken?.geckoId ?? ''].usd
}
gasTokenSymbol={
nativeTokenSymbol={
direction === 'DEPOSIT'
? (selectedLowNetwork?.nativeCurrency?.symbol ?? '')
: (selectedHighNetwork?.nativeCurrency?.symbol ?? '')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ const NetworkSelector = ({ networks, onChange, selectedNetwork, direction }: Net
return (
<Combobox.Option
value={String(n.chainId)}
key={n.chainId}
key={n.chainId}
className={isDisabled ? styles.optionDisabled : styles.option}
>
<Group>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,24 +20,24 @@ interface TransactionSummaryProps {
fee: number
isEstimatingFee: boolean
value: number
gasBalance: number
nativeBalance: number
ethRate: number
tokenSymbol: string
gasTokenSymbol: string
nativeTokenSymbol: string
tokenRate: number
direction: 'DEPOSIT' | 'WITHDRAW'
}
const TransactionSummary: React.FC<TransactionSummaryProps> = ({
direction,
gasBalance,
nativeBalance,
address,
transferTime,
fee,
isEstimatingFee,
ethRate,
tokenRate,
tokenSymbol,
gasTokenSymbol,
nativeTokenSymbol,
value
}) => {
const clipboard = useClipboard({ timeout: 700 })
Expand Down Expand Up @@ -87,8 +87,8 @@ const TransactionSummary: React.FC<TransactionSummaryProps> = ({
<div className={styles.valueContainer}>
<div
className={styles.value}
title={`Balance: ${String(gasBalance)}`}
>{`${fee.toFixed(18).replace(/\.?0+$/, '')} ${gasTokenSymbol}`}</div>
title={`Balance: ${String(nativeBalance)} ${nativeTokenSymbol}`}
>{`${fee.toFixed(18).replace(/\.?0+$/, '')} ${nativeTokenSymbol}`}</div>
{!!(fee * (direction === 'DEPOSIT' ? ethRate : tokenRate)) && (
<div className={styles.valueNote}>
{formatCurrency(fee * (direction === 'DEPOSIT' ? ethRate : tokenRate))}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const ValueToBridge: React.FC<ValueToBridgeProps> = ({
const [tokens, setTokens] = useState<Token[]>([])
const { connectedAccount, selectedBridgeToken, selectedHighNetwork, selectedLowNetwork } = useBlockchainContext()

const getTokens = async () => {
const getTokens = () => {
const highNetworkChainId = String(selectedHighNetwork.chainId)
const lowNetworkChainId = String(selectedLowNetwork.chainId)
const _tokens = getTokensForNetwork(selectedChainId, connectedAccount)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react'
import { getHighNetworks, getLowNetworks, getNetworks } from '../../../../constants'
import React from 'react'
import { getHighNetworks, getLowNetworks } from '../../../../constants'
import DepositMobile from './DepositMobile'
import styles from './WithdrawTransactions.module.css'
import { ethers } from 'ethers'
Expand All @@ -11,70 +11,24 @@ import { useBlockchainContext } from '@/contexts/BlockchainContext'
import { useBridgeTransfer } from '@/hooks/useBridgeTransfer'
import { TransactionRecord } from '@/utils/bridge/depositERC20ArbitrumSDK'
import { ETA, timeAgo } from '@/utils/timeFormat'
import { fetchTransactionTimestamp, getBlockExplorerUrl, getCachedTransactions } from '@/utils/web3utils'
import { getBlockExplorerUrl } from '@/utils/web3utils'

interface DepositProps {
deposit: TransactionRecord
}

const Deposit: React.FC<DepositProps> = ({ deposit }) => {
const { selectedNetworkType, connectedAccount } = useBlockchainContext()
const { selectedNetworkType } = useBlockchainContext()
const smallView = useMediaQuery('(max-width: 1199px)')
const depositInfo = {
from: getLowNetworks(selectedNetworkType)?.find((n) => n.chainId === deposit.lowNetworkChainId)?.displayName ?? '',
to: getHighNetworks(selectedNetworkType)?.find((n) => n.chainId === deposit.highNetworkChainId)?.displayName ?? ''
}

const { returnTransferData, getTransactionInputs } = useBridgeTransfer()
const { returnTransferData, getTransactionInputs, getHighNetworkTimestamp } = useBridgeTransfer()
const { data: transferStatus, isLoading } = returnTransferData({ txRecord: deposit })
const { data: transactionInputs } = getTransactionInputs({ txRecord: deposit })
const [highNetworkTimestamp, setHighNetworkTimestamp] = useState<number>(0)

useEffect(() => {
const fetchTimestamp = async () => {
if (deposit) {
const transactions = getCachedTransactions(connectedAccount ?? '', selectedNetworkType)

const cachedTransaction = transactions.find((t: any) => t.lowNetworkHash === deposit.lowNetworkHash)

if (cachedTransaction && cachedTransaction.highNetworkTimestamp) {
setHighNetworkTimestamp(cachedTransaction.highNetworkTimestamp)
return
}

const destinationRpc = getNetworks(selectedNetworkType)?.find((n) => n.chainId === deposit.highNetworkChainId)
?.rpcs[0]
if (transferStatus?.completionTxHash) {
try {
const timestamp = await fetchTransactionTimestamp(transferStatus.completionTxHash, destinationRpc ?? '')
if (timestamp) {
setHighNetworkTimestamp(timestamp)
const updatedTransactions = transactions.map((t: any) => {
const isSameHash = t.lowNetworkHash === deposit.lowNetworkHash
return isSameHash ? { ...t, highNetworkTimestamp: timestamp, lastUpdated: Date.now() } : t
})

localStorage.setItem(
`bridge-${connectedAccount}-transactions-${selectedNetworkType}`,
JSON.stringify(updatedTransactions)
)
}
} catch (error) {
console.error('Error fetching timestamp:', error)

if (cachedTransaction && cachedTransaction.highNetworkTimestamp) {
setHighNetworkTimestamp(cachedTransaction.highNetworkTimestamp)
}
}
} else {
console.log('No completion transaction hash found')
}
}
}

fetchTimestamp()
}, [transferStatus?.completionTxHash])

const { data: highNetworkTimestamp } = getHighNetworkTimestamp({ txRecord: deposit, transferStatus: transferStatus })
return (
<>
{isLoading && smallView ? (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,24 +77,20 @@ const HistoryDesktop: React.FC<HistoryDesktopProps> = () => {
const formattedApiTransactions = apiTransactions ? apiTransactions.map(mapAPIDataToTransactionRecord) : []
const combinedTransactions = mergeTransactions(formattedApiTransactions, localTransactions)
// Retrieve existing transactions from localStorage
const storedTransactionsString = localStorage.getItem(
`bridge-${connectedAccount}-transactions-${selectedNetworkType}`
)
const storedTransactions = storedTransactionsString ? JSON.parse(storedTransactionsString) : []


// Check if the combined transactions are different from those in localStorage
if (
combinedTransactions.length !== storedTransactions.length ||
combinedTransactions.length !== localTransactions.length ||
!combinedTransactions.every((tx, index) =>
tx.type === 'DEPOSIT'
? tx.lowNetworkHash === storedTransactions[index]?.lowNetworkHash
: tx.highNetworkHash === storedTransactions[index]?.highNetworkHash
? tx.lowNetworkHash === localTransactions[index]?.lowNetworkHash
: tx.highNetworkHash === localTransactions[index]?.highNetworkHash
)
) {
// Determine new transactions that aren’t in storedTransactions
const newTransactions = combinedTransactions.filter(
(newTx) =>
!storedTransactions.some((storedTx: TransactionRecord) =>
!localTransactions.some((storedTx: TransactionRecord) =>
storedTx.type === 'DEPOSIT'
? storedTx.lowNetworkHash === newTx.lowNetworkHash
: storedTx.highNetworkHash === newTx.highNetworkHash
Expand All @@ -103,7 +99,7 @@ const HistoryDesktop: React.FC<HistoryDesktopProps> = () => {

localStorage.setItem(
`bridge-${connectedAccount}-transactions-${selectedNetworkType}`,
JSON.stringify([...storedTransactions, ...newTransactions])
JSON.stringify([...localTransactions, ...newTransactions])
)
}
setMergedTransactions(combinedTransactions)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ interface NetworkToggleProps {}
const NetworkToggle: React.FC<NetworkToggleProps> = () => {
const { selectedNetworkType, setSelectedNetworkType } = useBlockchainContext()
const [isDropdownOpen, setDropdownOpen] = useState(false)
const dropdownRef = useRef<HTMLDivElement>(null)
const dropdownRef = useRef<HTMLDivElement | null>(null)
const [searchParams, setSearchParams] = useSearchParams()
const toggleDropdown = () => setDropdownOpen((prev) => !prev)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ interface BlockchainContextType {
setSelectedHighNetwork: (network: NetworkInterface) => void
selectedBridgeToken: Token
setSelectedBridgeToken: (token: Token) => void
selectedNativeToken: Token | null
setSelectedNativeToken: (token: Token | null) => void
isMetaMask: boolean
getProvider: (network: NetworkInterface) => Promise<ethers.providers.Web3Provider>
accounts: string[]
Expand Down Expand Up @@ -90,6 +92,11 @@ export const BlockchainProvider: React.FC<BlockchainProviderProps> = ({ children
const [selectedBridgeToken, setSelectedBridgeToken] = useState<Token>(
getTokensForNetwork(DEFAULT_LOW_NETWORK.chainId, connectedAccount)[0]
)
const [selectedNativeToken, setSelectedNativeToken] = useState<Token | null>(
getTokensForNetwork(DEFAULT_LOW_NETWORK.chainId, connectedAccount).find(
(token) => token.symbol === DEFAULT_LOW_NETWORK.nativeCurrency?.symbol
) ?? null
)

const tokenAddress = '0x5f88d811246222F6CB54266C42cc1310510b9feA'

Expand Down Expand Up @@ -315,7 +322,9 @@ export const BlockchainProvider: React.FC<BlockchainProviderProps> = ({ children
setSelectedBridgeToken,
selectedBridgeToken,
selectedNetworkType,
setSelectedNetworkType
setSelectedNetworkType,
setSelectedNativeToken,
selectedNativeToken
}}
>
{children}
Expand Down
4 changes: 2 additions & 2 deletions webapps/world-builder-dashboard/src/hooks/useBalance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,14 @@ import { Token } from '@/utils/tokens'

interface UseBalanceProps {
account: string | undefined
token: Token
token: Token | null
}

const useTokenInformation = ({ account, token }: UseBalanceProps) => {
return useQuery(
['balance', account, token],
async () => {
if (!account) {
if (!account || !token) {
return { tokenBalance: '0', symbol: '' }
}
const bridgeToken: BridgeToken = new BridgeToken(token.tokenAddressMap, token.chainId)
Expand Down
1 change: 0 additions & 1 deletion webapps/world-builder-dashboard/src/hooks/useBridgeAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ export const useBridgeAPI = () => {
return useQuery(
['historyTransactions', address, selectedNetworkType],
async () => {
console.log(selectedNetworkType)
const res = await fetch(`${BASE_URL}/bridge/game7${uriSnippet}/${address}/transactions?limit=50&offset=0`, {
method: 'GET'
})
Expand Down
Loading

0 comments on commit ef888e5

Please sign in to comment.