Skip to content

feat: pagination on wallet UI #545

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 2 commits into
base: feat/sf-815-pagination-on-snap
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ export const List = styled.ul`
padding-inline-start: 0px;
display: flex;
flex-direction: column;
height: 100vh;
`;

export const ListItem = styled.li``;
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useAppSelector } from 'hooks/redux';
import { FC, useEffect, useRef } from 'react';
import { FC, useEffect, useRef, useState, useCallback } from 'react';
import { useStarkNetSnap } from 'services';
import { Transaction } from 'types';
import {
Expand All @@ -16,6 +16,9 @@ interface Props {

export const TransactionsListView = ({ transactions }: Props) => {
const { getTransactions } = useStarkNetSnap();
const seenCursors = useRef<Set<{ txnHash: string; blockNumber: number }>>(
new Set(),
);
const networks = useAppSelector((state) => state.networks);
const currentAccount = useAppSelector((state) => state.wallet.currentAccount);
const erc20TokenBalanceSelected = useAppSelector(
Expand All @@ -24,9 +27,68 @@ export const TransactionsListView = ({ transactions }: Props) => {
const walletTransactions = useAppSelector(
(state) => state.wallet.transactions,
);
const walletTransactionsCursor = useAppSelector(
(state) => state.wallet.transactionCursor,
);
const timeoutHandle = useRef(setTimeout(() => {}));
const chainId = networks.items[networks.activeNetwork]?.chainId;

const [isFetchingMore, setIsFetchingMore] = useState(false);

const fetchMore = useCallback(async () => {
if (
walletTransactionsCursor &&
!seenCursors.current.has({
txnHash: walletTransactionsCursor.txnHash,
blockNumber: walletTransactionsCursor.blockNumber,
})
) {
seenCursors.current.add({
txnHash: walletTransactionsCursor.txnHash,
blockNumber: walletTransactionsCursor.blockNumber,
});
setIsFetchingMore(true);

await getTransactions(
currentAccount.address,
erc20TokenBalanceSelected.address,
chainId,
false,
walletTransactionsCursor,
);

setIsFetchingMore(false);
}
}, [
walletTransactionsCursor,
getTransactions,
currentAccount.address,
erc20TokenBalanceSelected.address,
chainId,
]);

const checkIfShouldFetchMore = (
scrollTop: number,
scrollHeight: number,
clientHeight: number,
) => {
return scrollTop + clientHeight >= scrollHeight - 10;
};

const handleScroll = useCallback(
async (event: React.UIEvent<HTMLDivElement>) => {
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;

if (
checkIfShouldFetchMore(scrollTop, scrollHeight, clientHeight) &&
!isFetchingMore
) {
await fetchMore();
}
},
[isFetchingMore, fetchMore],
);

useEffect(() => {
if (chainId && erc20TokenBalanceSelected.address) {
clearTimeout(timeoutHandle.current); // cancel the timeout that was in-flight
Expand All @@ -35,10 +97,8 @@ export const TransactionsListView = ({ transactions }: Props) => {
getTransactions(
currentAccount.address,
erc20TokenBalanceSelected.address,
10,
chainId,
false,
true,
),
TRANSACTIONS_REFRESH_FREQUENCY,
);
Expand All @@ -58,27 +118,23 @@ export const TransactionsListView = ({ transactions }: Props) => {
getTransactions(
currentAccount.address,
erc20TokenBalanceSelected.address,
10,
chainId,
);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[
// eslint-disable-next-line react-hooks/exhaustive-deps
erc20TokenBalanceSelected.address,
// eslint-disable-next-line react-hooks/exhaustive-deps
erc20TokenBalanceSelected.chainId,
// eslint-disable-next-line react-hooks/exhaustive-deps
currentAccount.address,
// eslint-disable-next-line react-hooks/exhaustive-deps
currentAccount.chainId,
chainId,
],
);

return (
<Wrapper<FC<IListProps<Transaction>>>
onScroll={handleScroll}
data={transactions.length > 0 ? transactions : walletTransactions}
render={(transaction) => (
<TransactionListItem transaction={transaction} />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,8 @@ export const SendSummaryModalView = ({
getTransactions(
currentAddress,
erc20TokenBalanceSelected.address,
10,
chainId,
false,
true,
).catch((err) => {
console.error(
`handleConfirmClick: error from getTransactions: ${err}`,
Expand Down
1 change: 0 additions & 1 deletion packages/wallet-ui/src/hooks/useEstimateFee.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ export const useEstimateFee = (feeToken: FeeToken = FeeToken.ETH) => {
// - Cache does not expired but the estimation result is include deployment fee and the account is deployed, as it means the estimation result is not valid anymore
if (!cacheData || expired || (cacheData.includeDeploy && isDeployed)) {
setLoading(true);
console.log('fetching new fee', feeToken);
try {
const callData =
address + ',' + getMinAmountToSpend().toString() + ',0';
Expand Down
31 changes: 24 additions & 7 deletions packages/wallet-ui/src/services/useStarkNetSnap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ import {
updateAccount,
updateCurrentAccount,
setWalletConnection,
setTransactionCursor,
appendTransactions,
} from 'slices/walletSlice';
import { setNetworksAndActiveNetwork } from 'slices/networkSlice';
import { disableLoading, enableLoadingWithMessage } from 'slices/UISlice';
Expand Down Expand Up @@ -60,6 +62,9 @@ export const useStarkNetSnap = () => {
(state) => state.wallet.erc20TokenBalances,
);
const accounts = useAppSelector((state) => state.wallet.accounts);
const transactionDeploy = useAppSelector(
(state) => state.wallet.transactionDeploy,
);

const connectToSnap = async () => {
dispatch(enableLoadingWithMessage('Connecting...'));
Expand Down Expand Up @@ -236,6 +241,7 @@ export const useStarkNetSnap = () => {

const setErc20TokenBalance = (erc20TokenBalance: Erc20TokenBalance) => {
dispatch(setErc20TokenBalanceSelected(erc20TokenBalance));
dispatch(setTransactionDeploy(null));
};

const initTokensAndBalances = async (chainId: string, address: string) => {
Expand Down Expand Up @@ -443,38 +449,49 @@ export const useStarkNetSnap = () => {
const getTransactions = async (
senderAddress: string,
contractAddress: string,
txnsInLastNumOfDays: number,
chainId: string,
showLoading: boolean = true,
onlyFromState: boolean = false,
cursor?: { blockNumber: number; txnHash: string },
) => {
if (transactionDeploy) {
return;
}
if (showLoading) {
dispatch(enableLoadingWithMessage('Retrieving transactions...'));
}

try {
const data = await invokeSnap<Array<Transaction>>({
const response = await invokeSnap<{
transactions: Transaction[];
cursor: { txnHash: string; blockNumber: number };
}>({
method: 'starkNet_getTransactions',
params: {
senderAddress,
contractAddress,
txnsInLastNumOfDays,
cursor,
chainId,
},
});

const data = response.transactions;
const newCursor = response.cursor;

let storedTxns = data;

if (cursor) {
dispatch(appendTransactions(storedTxns));
} else {
dispatch(setTransactions(storedTxns));
}
//Set the deploy transaction
const deployTransaction = storedTxns.find(
(txn: Transaction) =>
txn.txnType === TransactionType.DEPLOY ||
txn.txnType === TransactionType.DEPLOY_ACCOUNT,
);
dispatch(setTransactionDeploy(deployTransaction));

dispatch(setTransactions(storedTxns));

dispatch(setTransactionCursor(newCursor));
return data;
} catch (error) {
dispatch(setTransactions([]));
Expand Down
14 changes: 14 additions & 0 deletions packages/wallet-ui/src/slices/walletSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export interface WalletState {
erc20TokenBalances: Erc20TokenBalance[];
erc20TokenBalanceSelected: Erc20TokenBalance;
transactions: Transaction[];
transactionCursor?: {
blockNumber: number;
txnHash: string;
};
transactionDeploy?: Transaction;
provider?: any; //TODO: metamask SDK is not export types
visibility: {
Expand All @@ -36,6 +40,7 @@ const initialState: WalletState = {
erc20TokenBalances: [],
erc20TokenBalanceSelected: {} as Erc20TokenBalance,
transactions: [],
transactionCursor: undefined,
transactionDeploy: undefined,
provider: undefined,
visibility: {
Expand Down Expand Up @@ -155,9 +160,16 @@ export const walletSlice = createSlice({
setErc20TokenBalanceSelected: (state, { payload }) => {
state.erc20TokenBalanceSelected = payload;
},
appendTransactions: (state, { payload }) => {
const transactions = state.transactions.concat(payload);
state.transactions = transactions;
},
setTransactions: (state, { payload }) => {
state.transactions = payload;
},
setTransactionCursor: (state, { payload }) => {
state.transactionCursor = payload;
},
setTransactionDeploy: (state, { payload }) => {
state.transactionDeploy = payload;
},
Expand Down Expand Up @@ -187,7 +199,9 @@ export const {
setErc20TokenBalances,
setErc20TokenBalanceSelected,
upsertErc20TokenBalance,
appendTransactions,
setTransactions,
setTransactionCursor,
setTransactionDeploy,
resetWallet,
setProvider,
Expand Down