Skip to content

Commit

Permalink
Merge pull request #275 from G7DAO/feat/update-bridge-sdk
Browse files Browse the repository at this point in the history
Feat/update bridge sdk
  • Loading branch information
elclandestin0 authored Jan 10, 2025
2 parents 1076a03 + 023682e commit bee432f
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 28 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { Bridger, BridgeTransferStatus } from 'game7-bridge-sdk'
import { useBlockchainContext } from '@/contexts/BlockchainContext'
import { useBridgeNotificationsContext } from '@/contexts/BridgeNotificationsContext'
import { getTokensForNetwork, Token } from '@/utils/tokens'
import { ZERO_ADDRESS } from '@/utils/web3utils'
import { returnSymbol, ZERO_ADDRESS } from '@/utils/web3utils'
import { MultiTokenApproval } from './MultiTokenApproval'

interface ActionButtonProps {
Expand Down Expand Up @@ -72,7 +72,7 @@ const ActionButton: React.FC<ActionButtonProps> = ({
setShowApproval(true)
return false
}

const amountBN = ethers.utils.parseUnits(amount, decimals)
if (bridgeAllowance === null) {
const gasFeesAmount = gasFees?.[1] ? ethers.utils.parseUnits(gasFees[1], 18) : amountBN
Expand Down Expand Up @@ -164,7 +164,7 @@ const ActionButton: React.FC<ActionButtonProps> = ({
lowNetworkTimestamp: Date.now() / 1000,
completionTimestamp: Date.now() / 1000,
newTransaction: true,
symbol: symbol,
symbol: returnSymbol(direction, selectedHighNetwork, selectedLowNetwork, symbol ?? ''),
status:
destinationTokenAddress === ZERO_ADDRESS
? BridgeTransferStatus.DEPOSIT_GAS_PENDING
Expand All @@ -185,7 +185,7 @@ const ActionButton: React.FC<ActionButtonProps> = ({
highNetworkHash: tx?.hash,
highNetworkTimestamp: Date.now() / 1000,
challengePeriod: selectedNetworkType === 'Testnet' ? 60 * 60 : 60 * 60 * 24 * 7,
symbol: symbol,
symbol: returnSymbol(direction, selectedHighNetwork, selectedLowNetwork, symbol ?? ''),
status:
isCCTP
? BridgeTransferStatus.CCTP_PENDING
Expand Down Expand Up @@ -241,7 +241,7 @@ const ActionButton: React.FC<ActionButtonProps> = ({
token.symbol === selectedHighNetwork.nativeCurrency?.symbol :
token.symbol === selectedLowNetwork.nativeCurrency?.symbol
)

if (bridgeAllowance === null && nativeAllowance !== null) {
return [nativeToken].filter((token): token is Token => token !== undefined)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ const BridgeView = ({
token: nativeToken
})

const { data: coinUSDRate, isFetching: isCoinFetching } = useUSDPriceOfToken(selectedBridgeToken.geckoId ?? '')
const { data: coinUSDRate, isFetching: isCoinFetching } = useUSDPriceOfToken(selectedBridgeToken?.geckoId ?? '')
const { data: ethRate } = useUSDPriceOfToken('ethereum')
const handleTokenChange = async (token: Token) => {
setSelectedBridgeToken(token)
Expand Down Expand Up @@ -213,7 +213,7 @@ const BridgeView = ({
onTokenChange={handleTokenChange}
balance={tokenInformation?.tokenBalance}
rate={
selectedBridgeToken.symbol === 'TG7T' || selectedBridgeToken.symbol === 'G7'
selectedBridgeToken?.symbol === 'TG7T' || selectedBridgeToken?.symbol === 'G7'
? 1
: isCoinFetching
? 0.0
Expand Down Expand Up @@ -259,11 +259,13 @@ const BridgeView = ({
value={Number(value)}
ethRate={ethRate?.ethereum?.usd ?? 0}
tokenRate={
selectedBridgeToken.symbol === 'TG7T' || selectedBridgeToken.symbol === 'G7'
selectedBridgeToken?.symbol === 'TG7T' || selectedBridgeToken?.symbol === 'G7'
? 1
: isCoinFetching
? 0.0
: coinUSDRate[selectedBridgeToken?.geckoId ?? ''].usd ?? 0
: coinUSDRate && selectedBridgeToken?.geckoId && coinUSDRate[selectedBridgeToken.geckoId]
? coinUSDRate[selectedBridgeToken.geckoId]?.usd ?? 0
: 0
}
tokenSymbol={tokenInformation?.symbol ?? ''}
gasNativeTokenSymbol={
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Tooltip, useClipboard } from 'summon-ui/mantine'
import { mantineBreakpoints } from '@/styles/breakpoints'
import { useMediaQuery } from '@mantine/hooks'
import { NetworkInterface } from '@/contexts/BlockchainContext'
import { returnSymbol } from '@/utils/web3utils'

const formatCurrency = (value: number) => {
const formatter = new Intl.NumberFormat('en-US', {
Expand Down Expand Up @@ -177,7 +178,7 @@ const TransactionSummary: React.FC<TransactionSummaryProps> = ({
<div className={styles.itemName}>You will receive</div>
<div className={styles.valueContainer}>
<div className={styles.value}>
{`${value} ${tokenSymbol.startsWith('USDC') ? (tokenSymbol === 'USDC.e' ? 'USDC' : 'USDC.e') : tokenSymbol}`}
{`${value} ${returnSymbol(direction, selectedHighChain, selectedLowChain, tokenSymbol)}`}
</div>
{tokenRate > 0 && <div className={styles.valueNote}>{formatCurrency(value * (tokenSymbol === 'ETH' || tokenSymbol === 'G7' || tokenSymbol === 'TG7T' ? ethRate : tokenRate))}</div>}
</div>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
// External Libraries
import React, { Fragment, useEffect, useState } from 'react'
import React, { Fragment, useEffect, useState, useRef } from 'react'
// Styles
import styles from './WithdrawTransactions.module.css'
import { ethers } from 'ethers'
Expand All @@ -15,7 +15,6 @@ interface HistoryDesktopProps { }

const mergeTransactions = (apiData: TransactionRecord[], localData: TransactionRecord[]): TransactionRecord[] => {
const combinedData = new Map<string, TransactionRecord>()

localData.forEach((localTx) => {
const hashKey = localTx.type === 'DEPOSIT' ? (localTx.lowNetworkHash ?? '') : (localTx.highNetworkHash ?? '')
combinedData.set(hashKey, localTx)
Expand All @@ -39,7 +38,6 @@ const mergeTransactions = (apiData: TransactionRecord[], localData: TransactionR
combinedData.set(hashKey, apiTx)
}
})

const combinedDataArray = Array.from(combinedData.values())
return combinedDataArray
}
Expand Down Expand Up @@ -70,15 +68,17 @@ const HistoryDesktop: React.FC<HistoryDesktopProps> = () => {
const { data: messages } = useMessages(connectedAccount, selectedNetworkType || 'Testnet')
const { useHistoryTransactions } = useBridgeAPI()
const { data: apiTransactions } = useHistoryTransactions(connectedAccount)
const [visibleTransactions, setVisibleTransactions] = useState<TransactionRecord[]>([])
const [mergedTransactions, setMergedTransactions] = useState<TransactionRecord[]>([])
const headers = ['Type', 'Submitted', 'Token', 'From', 'To', 'Transaction', 'Status', '']
const transactionsRef = useRef<HTMLDivElement | null>(null)

// Merge transations only when API data is updated with new data
useEffect(() => {
const localTransactions = messages || []
const formattedApiTransactions = apiTransactions ? apiTransactions.map(apiDataToTransactionRecord) : []
const combinedTransactions = mergeTransactions(formattedApiTransactions, localTransactions)
console.log(formattedApiTransactions)

// Check if the combined transactions are different from those in localStorage
if (
combinedTransactions.length !== localTransactions.length ||
Expand All @@ -103,36 +103,66 @@ const HistoryDesktop: React.FC<HistoryDesktopProps> = () => {
JSON.stringify([...localTransactions, ...newTransactions])
)
}
// sort first
combinedTransactions.sort((x: TransactionRecord, y: TransactionRecord) => {
const xTimestamp = x.type === 'DEPOSIT' ? x.lowNetworkTimestamp : x.highNetworkTimestamp
const yTimestamp = y.type === 'DEPOSIT' ? y.lowNetworkTimestamp : y.highNetworkTimestamp

return (yTimestamp ?? 0) - (xTimestamp ?? 0)
})
setMergedTransactions(combinedTransactions)
setVisibleTransactions(combinedTransactions.slice(0, 10))
}, [messages, apiTransactions])

const loadMoreItems = () => {
setVisibleTransactions((prev) => {
const nextItems = mergedTransactions.slice(prev.length, prev.length + 5)
return [...prev, ...nextItems]
})
}

useEffect(() => {
const handleScroll = () => {
if (transactionsRef.current) {
const { scrollTop, scrollHeight, clientHeight } = transactionsRef.current
if (scrollTop + clientHeight >= scrollHeight - 10) {
loadMoreItems()
}
}
}

const currentRef = transactionsRef.current
if (currentRef) {
currentRef.addEventListener('scroll', handleScroll)
}

return () => {
if (currentRef) {
currentRef.removeEventListener('scroll', handleScroll)
}
}
}, [visibleTransactions])

return (
<div className={styles.container}>
<div className={styles.content}>
{mergedTransactions && (
{visibleTransactions && (
<div className={styles.transactions}>
<div className={styles.withdrawsGrid}>
<div className={styles.withdrawsGrid} ref={transactionsRef}>
{headers.map((h) => (
<div className={h !== '' ? styles.transactionsHeader : styles.transactionsHeaderEmpty} key={h}>
{h}
</div>
))}
{mergedTransactions
.sort((x: TransactionRecord, y: TransactionRecord) => {
const xTimestamp = x.type === 'DEPOSIT' ? x.lowNetworkTimestamp : x.highNetworkTimestamp
const yTimestamp = y.type === 'DEPOSIT' ? y.lowNetworkTimestamp : y.highNetworkTimestamp

return (yTimestamp ?? 0) - (xTimestamp ?? 0)
})
{visibleTransactions
.map((tx: TransactionRecord, idx: number) =>
tx.type === 'WITHDRAWAL' ? (
<Withdrawal withdrawal={tx} key={idx} />
) : (
<Fragment key={idx}>{tx.lowNetworkHash && <Deposit deposit={tx} />}</Fragment>
)
)}
{mergedTransactions.filter((tx: TransactionRecord) => tx.type === 'DEPOSIT' || tx.type === 'WITHDRAWAL')
.length === 0 && <div className={styles.noTransactions}> No transactions yet</div>}
{visibleTransactions.filter((tx: TransactionRecord) => tx.type === 'DEPOSIT' || tx.type === 'WITHDRAWAL').length === 0 && <div className={styles.noTransactions}> No transactions yet</div>}
</div>
</div>
)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
box-shadow:
0 1px 3px 0 rgba(16, 24, 40, 0.1),
0 1px 2px 0 rgba(16, 24, 40, 0.06);
overflow-y: auto;
overflow-y: scroll;
flex-grow: 0;
}

Expand Down Expand Up @@ -96,7 +96,7 @@
grid-template-columns: repeat(8, auto);
width: 100%;
max-width: 1096px;
overflow-y: auto;
overflow-y: scroll;
max-height: calc(100vh - 282px);
}

Expand Down
12 changes: 11 additions & 1 deletion webapps/world-builder-dashboard/src/utils/web3utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { getHighNetworks, getLowNetworks, HIGH_NETWORKS, LOW_NETWORKS } from '../../constants'
import { ethers } from 'ethers'
import { NetworkType } from '@/contexts/BlockchainContext'
import { NetworkInterface, NetworkType } from '@/contexts/BlockchainContext'
import { providers } from 'ethers'

export const convertToBigNumber = (numberString: string, precision = 18) => {
Expand Down Expand Up @@ -92,4 +92,14 @@ export const fetchTransactionTimestamp = async (completionTxHash: string, rpcUrl
export const getCachedTransactions = (connectedAccount: string, selectedNetworkType: NetworkType) => {
const transactionsString = localStorage.getItem(`bridge-${connectedAccount}-transactions-${selectedNetworkType}`)
return transactionsString ? JSON.parse(transactionsString) : []
}

export const returnSymbol = (direction: 'DEPOSIT' | 'WITHDRAW', selectedHighChain: NetworkInterface, selectedLowChain: NetworkInterface, tokenSymbol: string) => {
if (tokenSymbol.startsWith('USDC')) {
if (direction === 'DEPOSIT' && (selectedHighChain.chainId === 13746 || selectedHighChain.chainId === 2187))
return 'USDC.e'
else if (direction === 'WITHDRAW' && (selectedLowChain.chainId === 421614 || selectedLowChain.chainId === 42161))
return 'USDC'
}
return tokenSymbol
}

0 comments on commit bee432f

Please sign in to comment.