Skip to content

Commit

Permalink
Merge pull request #204 from G7DAO/feat/network-toggle
Browse files Browse the repository at this point in the history
Feat/network toggle
  • Loading branch information
elclandestin0 authored Nov 25, 2024
2 parents 6ea7440 + 44d2f86 commit 8ada142
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import React from 'react'
import { getHighNetworks, getLowNetworks } from '../../../../constants'
import DepositMobile from './DepositMobile'
import styles from './WithdrawTransactions.module.css'
import { ethers } from 'ethers'
import { BridgeTransferStatus } from 'game7-bridge-sdk'
import { useMediaQuery } from 'summon-ui/mantine'
import IconArrowNarrowDown from '@/assets/IconArrowNarrowDown'
Expand All @@ -24,13 +25,14 @@ const Deposit: React.FC<DepositProps> = ({ deposit }) => {
from: getLowNetworks(selectedNetworkType)?.find((n) => n.chainId === deposit.lowNetworkChainId)?.displayName ?? '',
to: getHighNetworks(selectedNetworkType)?.find((n) => n.chainId === deposit.highNetworkChainId)?.displayName ?? ''
}
const tokenInformation = getTokensForNetwork(deposit?.lowNetworkChainId, connectedAccount).find(
(token) => token.address === deposit?.tokenAddress
)

const { data: status, isLoading: isLoadingStatus } = useDepositStatus(deposit, selectedNetworkType)
const { returnTransferData } = useBridgeTransfer()
const { returnTransferData, getTransactionInputs } = useBridgeTransfer()
const { data: transferStatus, isLoading } = returnTransferData({ txRecord: deposit })
const { data: transactionInputs } = getTransactionInputs({ txRecord: deposit })
const tokenInformation = getTokensForNetwork(deposit?.lowNetworkChainId, connectedAccount).find(
(token) => token.address === transactionInputs?.tokenOriginAddress
)

return (
<>
Expand All @@ -53,7 +55,7 @@ const Deposit: React.FC<DepositProps> = ({ deposit }) => {
<div className={styles.gridItem}>{timeAgo(deposit.lowNetworkTimestamp)}</div>
<div
className={styles.gridItem}
>{`${tokenInformation?.decimals ? Number(deposit.amount) / tokenInformation?.decimals : deposit.amount} ${tokenInformation?.symbol}`}</div>
>{`${transactionInputs?.tokenSymbol === 'USDC' ? ethers.utils.formatUnits(transactionInputs?.amount, 6) : deposit.amount} ${transactionInputs?.tokenSymbol}`}</div>
<div className={styles.gridItem}>{depositInfo.from}</div>
<div className={styles.gridItem}>{depositInfo.to}</div>
<>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,6 @@ const HistoryDesktop: React.FC<HistoryDesktopProps> = () => {
const localTransactions = messages || []
const formattedApiTransactions = apiTransactions ? apiTransactions.map(mapAPIDataToTransactionRecord) : []
const combinedTransactions = mergeTransactions(formattedApiTransactions, localTransactions)
console.log(formattedApiTransactions)
console.log(combinedTransactions)
// Retrieve existing transactions from localStorage
const storedTransactionsString = localStorage.getItem(
`bridge-${connectedAccount}-transactions-${selectedNetworkType}`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useState } from 'react'
import { getHighNetworks, getLowNetworks, HIGH_NETWORKS, LOW_NETWORKS } from '../../../../constants'
import styles from './WithdrawTransactions.module.css'
import { ethers } from 'ethers'
import IconArrowNarrowUp from '@/assets/IconArrowNarrowUp'
import IconLinkExternal02 from '@/assets/IconLinkExternal02'
import IconWithdrawalNodeCompleted from '@/assets/IconWithdrawalNodeCompleted'
Expand Down Expand Up @@ -62,10 +63,11 @@ const Withdrawal: React.FC<WithdrawalProps> = ({ withdrawal }) => {
const highNetworks = getHighNetworks(selectedNetworkType) || HIGH_NETWORKS
const status = getStatus(withdrawal, lowNetworks, highNetworks)
const { data: transferStatus, isLoading } = returnTransferData({ txRecord: withdrawal })

const { data: transactionInputs } = getTransactionInputs({ txRecord: withdrawal })
const tokenInformation = getTokensForNetwork(withdrawal?.highNetworkChainId, connectedAccount).find(
(token) => token.address === withdrawal?.tokenAddress
(token) => token.address === transactionInputs?.tokenAddress
)
const { data: transactionInputs } = getTransactionInputs({ txRecord: withdrawal })

return (
<>
Expand Down Expand Up @@ -147,7 +149,7 @@ const Withdrawal: React.FC<WithdrawalProps> = ({ withdrawal }) => {
}}
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>{`${tokenInformation?.decimals ? Number(withdrawal.amount) / tokenInformation?.decimals : withdrawal.amount} ${transactionInputs?.tokenSymbol}`}</div>
>{`${transactionInputs?.tokenSymbol === 'USDC' ? ethers.utils.formatUnits(transactionInputs?.amount, 6) : withdrawal.amount} ${transactionInputs?.tokenSymbol}`}</div>
<div
className={styles.gridItem}
onClick={() => setCollapseExecuted(!collapseExecuted)}
Expand Down
59 changes: 27 additions & 32 deletions webapps/world-builder-dashboard/src/hooks/useBridgeTransfer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,7 @@ export const useBridgeTransfer = () => {
provider = new ethers.providers.Web3Provider(window.ethereum)
const currentChain = await provider.getNetwork()
if (currentChain.chainId !== targetChain.chainId) {
console.log('about to switch')
await switchChain(targetChain)
console.log('switching?')
provider = new ethers.providers.Web3Provider(window.ethereum) //refresh provider
}
} else {
Expand Down Expand Up @@ -193,7 +191,6 @@ export const useBridgeTransfer = () => {
status: BridgeTransferStatus.WITHDRAW_EXECUTED
}
}
console.log("couldn't find the transaction..")
return { ...t }
})
localStorage.setItem(
Expand All @@ -217,50 +214,47 @@ export const useBridgeTransfer = () => {
)

const getTransactionInputs = ({ txRecord }: UseTransferDataProps) => {
const isDeposit = txRecord.type === 'DEPOSIT';
const txHash = isDeposit ? txRecord.lowNetworkHash : txRecord.highNetworkHash;
const destinationChainId = isDeposit ? txRecord.highNetworkChainId : txRecord.lowNetworkChainId;
const originChainId = isDeposit ? txRecord.lowNetworkChainId : txRecord.highNetworkChainId;
const destinationRpc = getNetworks(selectedNetworkType)?.find((n) => n.chainId === destinationChainId)?.rpcs[0];
const originRpc = getNetworks(selectedNetworkType)?.find((n) => n.chainId === originChainId)?.rpcs[0];
const storageKey = `transaction-inputs-${connectedAccount}`;
const isDeposit = txRecord.type === 'DEPOSIT'
const txHash = isDeposit ? txRecord.lowNetworkHash : txRecord.highNetworkHash
const destinationChainId = isDeposit ? txRecord.highNetworkChainId : txRecord.lowNetworkChainId
const originChainId = isDeposit ? txRecord.lowNetworkChainId : txRecord.highNetworkChainId
const destinationRpc = getNetworks(selectedNetworkType)?.find((n) => n.chainId === destinationChainId)?.rpcs[0]
const originRpc = getNetworks(selectedNetworkType)?.find((n) => n.chainId === originChainId)?.rpcs[0]
const storageKey = `transaction-inputs-${connectedAccount}`

// Retrieve cached transaction inputs from localStorage
const getCachedTransactionInputs = () => {
const cachedData = localStorage.getItem(storageKey);
if (!cachedData) return null;
const cachedData = localStorage.getItem(storageKey)
if (!cachedData) return null

const cachedTransactions = JSON.parse(cachedData);
const cachedTransactions = JSON.parse(cachedData)

// Return the specific transaction input based on txHash
return cachedTransactions.find((input: any) => input.txHash === txHash) || null;
};
return cachedTransactions.find((input: any) => input.txHash === txHash) || null
}

// Save transaction inputs to localStorage as an array
const saveTransactionInputsToCache = (newInput: any) => {
const cachedData = localStorage.getItem(storageKey);
const cachedTransactions = cachedData ? JSON.parse(cachedData) : [];
const cachedData = localStorage.getItem(storageKey)
const cachedTransactions = cachedData ? JSON.parse(cachedData) : []

// Check if the transaction already exists in the array
const updatedTransactions = cachedTransactions.some((input: any) => input.txHash === newInput.txHash)
? cachedTransactions.map((input: any) =>
input.txHash === newInput.txHash ? { ...input, ...newInput } : input
)
: [...cachedTransactions, newInput]; // Add new input if not found
: [...cachedTransactions, newInput]

// Save updated transactions back to localStorage
localStorage.setItem(storageKey, JSON.stringify(updatedTransactions));
};
localStorage.setItem(storageKey, JSON.stringify(updatedTransactions))
}

// Use React Query to fetch or cache transaction inputs
return useQuery(
['transactionInputs', txHash],
async () => {
const cachedTransactionInputs = getCachedTransactionInputs();

const cachedTransactionInputs = getCachedTransactionInputs()
// If found in cache, return the cached data
if (cachedTransactionInputs) {
return cachedTransactionInputs;
return cachedTransactionInputs
}

// Otherwise, fetch transaction inputs from the bridge transfer instance
Expand All @@ -270,14 +264,15 @@ export const useBridgeTransfer = () => {
originNetworkChainId: originChainId ?? 0,
destinationSignerOrProviderOrRpc: destinationRpc,
originSignerOrProviderOrRpc: originRpc,
});

const transactionInputs = await _bridgeTransfer.getTransactionInputs();
})


const transactionInputs = isDeposit ? await _bridgeTransfer.getInfo() : await _bridgeTransfer.getTransactionInputs()

// Save the fetched transaction inputs to cache
saveTransactionInputsToCache({ txHash, ...transactionInputs });
saveTransactionInputsToCache({ txHash, ...transactionInputs })

return transactionInputs;
return transactionInputs
},
{
placeholderData: () => {
Expand All @@ -287,8 +282,8 @@ export const useBridgeTransfer = () => {
refetchOnWindowFocus: false, // Disable refetching on window focus
enabled: !!txRecord, // Ensure the query only runs when txRecord exists
}
);
};
)
}
return {
getTransactionInputs,
returnTransferData,
Expand Down

0 comments on commit 8ada142

Please sign in to comment.