Skip to content

Commit

Permalink
Fe/sorting wip (#1770)
Browse files Browse the repository at this point in the history
* Sorting wip

* Show by latest

* Merging sorting-j

* Hides debugging related kappa and time

* debug why new type isnt recognized

* Convert transactions object to list

* Render transactions in list

* Check tx is stored before adding into _transaction

* Check tx has been confirmed before adding to _transaction store

* Sorting by descending timestamp

* Allow clear tx functionality to persist

* back to optimism mainnet rpc

* Prevent refiring tx sdk queries if already complete

* Mark tx as complete once kappa and isTxComplete avail

* Check if store marked Tx complete before firing tx status hook, render persisted tx status

* `useBridgeTxStatus` hook initialized to set isComplete to true if kappa exists, save call

* Revert prev commit, require check on tx status beyond kappa avail

* Utilize `checkStatus` as guardrail check in `useBridgeTxStatus`

* removes unused prop

* removes another unused prop

* Hide debugging meta

* Hide debugging meta

* limits to 5 txns

* align time

---------

Co-authored-by: bigboydiamonds <[email protected]>
  • Loading branch information
abtestingalpha and bigboydiamonds authored Jan 8, 2024
1 parent b1e6301 commit d0e6a01
Show file tree
Hide file tree
Showing 5 changed files with 127 additions and 110 deletions.
64 changes: 40 additions & 24 deletions packages/synapse-interface/components/_Transaction/_Transaction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ const TimeRemaining = ({
}

interface _TransactionProps {
synapseSDK: any
connectedAddress: string
originValue: number
originChain: Chain
Expand All @@ -48,15 +47,14 @@ interface _TransactionProps {
originTxHash: string
bridgeModuleName: string
estimatedTime: number // in seconds
kappa?: string
timestamp: number
currentTime: number
isComplete: boolean
kappa?: string
isStoredComplete: boolean
}

/** TODO: Update naming after refactoring existing Activity / Transaction flow */
export const _Transaction = ({
synapseSDK,
connectedAddress,
originValue,
originChain,
Expand All @@ -66,13 +64,13 @@ export const _Transaction = ({
originTxHash,
bridgeModuleName,
estimatedTime,
kappa,
timestamp,
currentTime,
isComplete,
kappa,
isStoredComplete,
}: _TransactionProps) => {
const dispatch = useAppDispatch()
const transactions = use_TransactionsState()
const { transactions } = use_TransactionsState()

const [originTxExplorerLink, originExplorerName] = getTxBlockExplorerLink(
originChain.id,
Expand Down Expand Up @@ -103,34 +101,41 @@ export const _Transaction = ({
}, [estimatedTime, currentTime, timestamp])

const [isTxComplete, _kappa] = useBridgeTxStatus({
synapseSDK,
originChainId: originChain.id,
destinationChainId: destinationChain.id,
originTxHash,
bridgeModuleName,
kappa,
checkStatus: isEstimatedTimeReached,
kappa: kappa,
checkStatus: !isStoredComplete || isEstimatedTimeReached,
currentTime: currentTime,
})

/** Check if store already marked tx as complete, otherwise check hook status */
const isTxCompleted = isStoredComplete ?? isTxComplete

/** Update tx kappa when available */
useEffect(() => {
if (_kappa && originTxHash) {
dispatch(updateTransactionKappa({ originTxHash, kappa: _kappa }))
dispatch(
updateTransactionKappa({ originTxHash, kappa: _kappa as string })
)
}
}, [_kappa, dispatch])

/** Update tx for completion */
/** Check that we have not already marked tx as complete */
useEffect(() => {
const txKappa = kappa ?? _kappa
const txKappa = _kappa

if (isTxComplete && originTxHash && txKappa) {
if (transactions[originTxHash].isComplete === false) {
dispatch(completeTransaction({ originTxHash, kappa: txKappa }))
const txn = transactions.find((tx) => tx.originTxHash === originTxHash)
if (!txn.isComplete) {
dispatch(
completeTransaction({ originTxHash, kappa: txKappa as string })
)
}
}
}, [isTxComplete, dispatch, transactions])
}, [isTxComplete, dispatch, transactions, _kappa])

const handleClearTransaction = useCallback(() => {
dispatch(removeTransaction({ originTxHash }))
Expand All @@ -155,22 +160,33 @@ export const _Transaction = ({
/>
<TransactionArrow className="bg-tint fill-surface" />
</div>
<TransactionPayloadDetail
chain={destinationChain}
token={destinationToken}
tokenAmount={null}
isOrigin={false}
/>
<div className="flex items-center">
<TransactionPayloadDetail
chain={destinationChain}
token={destinationToken}
tokenAmount={null}
isOrigin={false}
/>
<div className="mt-1 text-xs">
{new Date(timestamp * 1000).toLocaleString('en-US', {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: true,
})}
{/* <div>{typeof _kappa === 'string' && _kappa?.substring(0, 15)}</div> */}
</div>
</div>
{/* TODO: Update visual format */}
<div className="flex justify-between gap-2 pr-2 ml-auto">
{isComplete ? (
{isTxCompleted ? (
<TransactionStatus string="Complete" />
) : (
<TransactionStatus string="Pending" />
)}
<div className="flex items-center justify-end gap-2 grow">
<TimeRemaining
isComplete={isComplete}
isComplete={isTxCompleted as boolean}
remainingTime={remainingTimeInMinutes}
isDelayed={isEstimatedTimeReached}
/>
Expand All @@ -192,7 +208,7 @@ export const _Transaction = ({
text="Contact Support"
link="https://discord.gg/synapseprotocol"
/>
{isComplete && (
{isTxComplete && (
<MenuItem
text="Clear Transaction"
link={null}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
import { useState, useEffect } from 'react'
import _ from 'lodash'
import { useState, useEffect, useMemo } from 'react'
import { use_TransactionsState } from '@/slices/_transactions/hooks'
import { _TransactionDetails } from '@/slices/_transactions/reducer'
import { useSynapseContext } from '@/utils/providers/SynapseProvider'
import { _Transaction } from './_Transaction'
import { getTimeMinutesFromNow } from '@/utils/time'
import { checkTransactionsExist } from '@/utils/checkTransactionsExist'

/** TODO: Update naming once refactoring of previous Activity/Tx flow is done */
export const _Transactions = ({
connectedAddress,
}: {
connectedAddress: string
}) => {
const { synapseSDK } = useSynapseContext()
const transactions = use_TransactionsState()
const { transactions } = use_TransactionsState()

const transactionsArray: _TransactionDetails[] = Object.values(transactions)

const hasTransactions: boolean = transactionsArray.length > 0
const hasTransactions: boolean = checkTransactionsExist(transactions)

const [currentTime, setCurrentTime] = useState<number>(
getTimeMinutesFromNow(0)
Expand All @@ -35,11 +33,12 @@ export const _Transactions = ({
}, [])

if (hasTransactions) {
const sortedTransactions = _.orderBy(transactions, ['timestamp'], ['desc'])
return (
<div className="mt-3">
{transactionsArray.map((tx: _TransactionDetails) => (
<div className="flex flex-col mt-3">
{sortedTransactions.slice(0, 5).map((tx: _TransactionDetails) => (
<_Transaction
synapseSDK={synapseSDK}
key={tx.timestamp}
connectedAddress={connectedAddress}
originValue={Number(tx.originValue)}
originChain={tx.originChain}
Expand All @@ -52,7 +51,7 @@ export const _Transactions = ({
kappa={tx?.kappa}
timestamp={tx.timestamp}
currentTime={currentTime}
isComplete={tx.isComplete}
isStoredComplete={tx.isComplete}
/>
))}
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { useState, useEffect } from 'react'
import { useSynapseContext } from '@/utils/providers/SynapseProvider'

interface UseBridgeTxStatusProps {
synapseSDK: any
originChainId: number
destinationChainId: number
originTxHash: string
Expand All @@ -20,10 +19,10 @@ export const useBridgeTxStatus = ({
kappa,
checkStatus = false,
currentTime,
}: UseBridgeTxStatusProps) => {
}: UseBridgeTxStatusProps): [boolean, string] => {
const { synapseSDK } = useSynapseContext()
const [isComplete, setIsComplete] = useState<boolean>(false)
const [fetchedKappa, setFetchedKappa] = useState<string>(null)
const [fetchedKappa, setFetchedKappa] = useState<string>(kappa ?? null)

const getKappa = async (): Promise<string> => {
if (!synapseSDK) return null
Expand Down Expand Up @@ -54,6 +53,7 @@ export const useBridgeTxStatus = ({
bridgeModuleName,
kappa
)

return status
} catch (error) {
console.error('Error in getBridgeTxStatus:', error)
Expand All @@ -65,28 +65,26 @@ export const useBridgeTxStatus = ({
if (!checkStatus) return
if (isComplete) return
;(async () => {
let _kappa

if (!kappa) {
console.log('fetching kappa')
_kappa = await getKappa()
if (fetchedKappa === null) {
let _kappa = await getKappa()
setFetchedKappa(_kappa)
} else {
_kappa = kappa
}

console.log('fetching tx status')
const txStatus = await getBridgeTxStatus(
destinationChainId,
bridgeModuleName,
_kappa
)
if (fetchedKappa) {
const txStatus = await getBridgeTxStatus(
destinationChainId,
bridgeModuleName,
fetchedKappa
)

if (txStatus !== null) {
setIsComplete(txStatus)
if (txStatus !== null && txStatus === true && fetchedKappa !== null) {
setIsComplete(true)
} else {
setIsComplete(false)
}
}
})()
}, [currentTime, checkStatus])
}, [currentTime, checkStatus, fetchedKappa])

return [isComplete, fetchedKappa]
}
88 changes: 36 additions & 52 deletions packages/synapse-interface/slices/_transactions/reducer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createSlice } from '@reduxjs/toolkit'
import { PayloadAction, createSlice } from '@reduxjs/toolkit'

import { Chain, Token } from '@/utils/types'
import StateManagedBridge from '@/pages/state-managed-bridge'

Check failure on line 4 in packages/synapse-interface/slices/_transactions/reducer.ts

View workflow job for this annotation

GitHub Actions / lint

'StateManagedBridge' is defined but never used

Check failure on line 4 in packages/synapse-interface/slices/_transactions/reducer.ts

View workflow job for this annotation

GitHub Actions / lint

'StateManagedBridge' is defined but never used

/** TODO: Rename entire slice once done refactoring prior Activity flow */
export interface _TransactionDetails {
Expand All @@ -18,75 +19,58 @@ export interface _TransactionDetails {
}

export interface _TransactionsState {
[transactionHash: string]: _TransactionDetails
transactions: any[]
}

export const initialState: _TransactionsState = {}
export const initialState: _TransactionsState = {
transactions: [],
}

export const transactionsSlice = createSlice({
name: 'transactions',
name: '_transactions',
initialState,
reducers: {
addTransaction: (
transactions: _TransactionsState,
{
payload: {
originTxHash,
originValue,
bridgeModuleName,
originChain,
originToken,
destinationChain,
destinationToken,
estimatedTime,
timestamp,
},
}
) => {
if (!originTxHash) return

transactions[originTxHash] = {
originTxHash,
originValue,
bridgeModuleName,
originChain,
originToken,
destinationChain,
destinationToken,
estimatedTime,
timestamp,
kappa: null,
isComplete: false,
}
addTransaction: (state, action: PayloadAction<any>) => {
state.transactions.push(action.payload)
},
removeTransaction: (
transactions: _TransactionsState,
{ payload: { originTxHash } }
state,
action: PayloadAction<{ originTxHash: string }>
) => {
if (transactions[originTxHash]) {
delete transactions[originTxHash]
}
const { originTxHash } = action.payload
state.transactions = state.transactions.filter(
(tx) => tx.originTxHash !== originTxHash
)
},
updateTransactionKappa: (
transactions: _TransactionsState,
{ payload: { originTxHash, kappa } }
state,
action: PayloadAction<{ originTxHash: string; kappa: string }>
) => {
const tx = transactions[originTxHash]
if (!tx) return
const { originTxHash, kappa } = action.payload

const txIndex = state.transactions.findIndex(
(tx) => tx.originTxHash === originTxHash
)

tx.kappa = kappa
if (txIndex !== -1) {
state.transactions[txIndex].kappa = kappa
}
},
completeTransaction: (
transactions: _TransactionsState,
{ payload: { originTxHash } }
state,
action: PayloadAction<{ originTxHash: string; kappa: string }>
) => {
const tx = transactions[originTxHash]
if (!tx) return
const { originTxHash } = action.payload

tx.isComplete = true
const txIndex = state.transactions.findIndex(
(tx) => tx.originTxHash === originTxHash
)
if (txIndex !== -1) {
state.transactions[txIndex].isComplete = true
}
},
clearTransactions: (transactions: _TransactionsState) => {
transactions = {} // eslint-disable-line
clearTransactions: (state) => {
state.transactions = []
},
},
})
Expand Down
Loading

0 comments on commit d0e6a01

Please sign in to comment.