Skip to content

Commit

Permalink
fix a bunch of issues with pending txns (#5777)
Browse files Browse the repository at this point in the history
* fix a bunch of issues with pending txns

* rm log

* type the response of fetchTransaction properly

* code review changes
  • Loading branch information
walmat authored May 31, 2024
1 parent 4ea28bf commit 416ea1d
Show file tree
Hide file tree
Showing 6 changed files with 27 additions and 15 deletions.
5 changes: 3 additions & 2 deletions src/components/coin-row/FastTransactionCoinRow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { TwoCoinsIcon } from '../coin-icon/TwoCoinsIcon';
import Spinner from '../Spinner';
import * as lang from '@/languages';
import RainbowCoinIcon from '../coin-icon/RainbowCoinIcon';
import { checkForPendingSwap } from '@/screens/transaction-details/helpers/checkForPendingSwap';

export const getApprovalLabel = ({ approvalAmount, asset, type }: Pick<RainbowTransaction, 'type' | 'asset' | 'approvalAmount'>) => {
if (!approvalAmount || !asset) return;
Expand Down Expand Up @@ -70,7 +71,7 @@ const swapTypeValues = (changes: RainbowTransaction['changes'], status: RainbowT

const activityValues = (transaction: RainbowTransaction, nativeCurrency: NativeCurrencyKey) => {
const { changes, direction, type, status } = transaction;
if (['swap', 'wrap', 'unwrap'].includes(type)) return swapTypeValues(changes, status);
if (checkForPendingSwap(transaction)) return swapTypeValues(changes, status);
if (['approve', 'revoke'].includes(type)) return approvalTypeValues(transaction as RainbowTransaction);

const change = changes?.filter(c => c?.direction === direction && c?.asset.type !== 'nft')[0];
Expand All @@ -83,7 +84,7 @@ const activityValues = (transaction: RainbowTransaction, nativeCurrency: NativeC
valueSymbol = '+';
}

if (!change) return;
if (!change?.asset) return;

const { balance } = change.asset;

Expand Down
7 changes: 4 additions & 3 deletions src/raps/actions/crosschainSwap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,8 @@ export const crosschainSwap = async ({

const transaction = {
data: parameters.quote.data,
from: parameters.quote.from as Address,
to: parameters.quote.to as Address,
value: parameters.quote.value?.toString(),
asset: {
...parameters.assetToBuy,
Expand Down Expand Up @@ -203,8 +205,7 @@ export const crosschainSwap = async ({
value: quote.buyAmountMinusFees.toString(),
},
],
from: parameters.quote.from as Address,
to: parameters.quote.to as Address,
gasLimit,
hash: swap.hash as TxHash,
// TODO: MARK - Replace this once we migrate network => chainId
network,
Expand All @@ -213,7 +214,7 @@ export const crosschainSwap = async ({
status: 'pending',
type: 'swap',
flashbots: parameters.flashbots,
...gasParams,
...gasParamsToUse,
} satisfies NewTransaction;

addNewTransaction({
Expand Down
4 changes: 3 additions & 1 deletion src/resources/transactions/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { ADDYS_API_KEY } from 'react-native-dotenv';
import { parseTransaction } from '@/parsers/transactions';
import { Network } from '@/networks/types';
import { RainbowError, logger } from '@/logger';
import { TransactionApiResponse } from './types';

export type ConsolidatedTransactionsResult = QueryFunctionResult<typeof consolidatedTransactionsQueryFunction>;
export type PaginatedTransactions = { pages: ConsolidatedTransactionsResult[] };
Expand Down Expand Up @@ -37,7 +38,7 @@ export const fetchTransaction = async ({
try {
const chainId = getNetworkObj(network).id;
const url = `https://addys.p.rainbow.me/v3/${chainId}/${address}/transactions/${hash}`;
const response = await rainbowFetch(url, {
const response = await rainbowFetch<{ payload: { transaction: TransactionApiResponse } }>(url, {
method: 'get',
params: {
currency: currency.toLowerCase(),
Expand All @@ -47,6 +48,7 @@ export const fetchTransaction = async ({
Authorization: `Bearer ${ADDYS_API_KEY}`,
},
});

const tx = response?.data?.payload?.transaction || {};
if (!tx) {
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { CardSize } from '@/components/unique-token/CardSize';
import ImgixImage from '@/components/images/ImgixImage';
import { View } from 'react-native';
import ChainBadge from '@/components/coin-icon/ChainBadge';
import { checkForPendingSwap } from '../helpers/checkForPendingSwap';

type Props = {
transaction: RainbowTransaction;
Expand All @@ -31,7 +32,7 @@ export const TransactionDetailsValueAndFeeSection: React.FC<Props> = ({ transact
const assetData = transaction?.asset;
const change = transaction?.changes?.[0];

const isPendingSwap = ['swap', 'wrap', 'unwrap'].includes(transaction.type) && transaction.status === 'pending';
const isPendingSwap = checkForPendingSwap(transaction);

const value = change?.value || transaction.balance?.display;
const valueDisplay = value ? convertRawAmountToBalance(value || '', assetData!).display : '';
Expand Down
18 changes: 10 additions & 8 deletions src/screens/transaction-details/components/TransactionMasthead.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import ImageAvatar from '@/components/contacts/ImageAvatar';
import RainbowCoinIcon from '@/components/coin-icon/RainbowCoinIcon';
import { Network } from '@/networks/types';
import * as lang from '@/languages';
import { checkForPendingSwap } from '../helpers/checkForPendingSwap';

const TransactionMastheadHeight = android ? 153 : 135;

Expand Down Expand Up @@ -81,7 +82,6 @@ function CurrencyTile({
const accountAddress = useSelector((state: AppState) => state.settings.accountAddress);
const theme = useTheme();

// @ts-ignore
const { contacts } = useContacts();

const { userAccounts, watchedAccounts } = useUserAccounts();
Expand All @@ -95,15 +95,15 @@ function CurrencyTile({
watchedAccounts.find(account => isLowerCaseMatch(account.address, address))
);
}
}, [address]);
}, [address, userAccounts, watchedAccounts]);

const formattedAddress = formatAddressForDisplay(address, 4, 6);
const [fetchedEnsName, setFetchedEnsName] = useState<string | undefined>();
const [fetchedEnsImage, setFetchedEnsImage] = useState<string | undefined>();
const [imageLoaded, setImageLoaded] = useState(!!addressAccount?.image);

const accountEmoji = useMemo(() => returnStringFirstEmoji(addressAccount?.label), [addressAccount]);
const accountName = useMemo(() => removeFirstEmojiFromString(addressAccount?.label), []);
const accountName = useMemo(() => removeFirstEmojiFromString(addressAccount?.label), [addressAccount?.label]);
const avatarColor =
addressAccount?.color ?? addressContact?.color ?? theme.colors.avatarBackgrounds[addressHashedColorIndex(address) || 1];
const emoji = accountEmoji || addressHashedEmoji(address);
Expand Down Expand Up @@ -141,7 +141,7 @@ function CurrencyTile({
});
}
}
}, [fetchedEnsName]);
}, [addressAccount?.image, addressContact?.ens, fetchedEnsName]);

const colorForAsset = usePersistentDominantColorFromImage(showAsset ? asset?.icon_url : imageUrl) || avatarColor;

Expand Down Expand Up @@ -280,14 +280,16 @@ const DoubleChevron = () => (
export default function TransactionMasthead({ transaction }: { transaction: RainbowTransaction }) {
const nativeCurrency = useSelector((state: AppState) => state.settings.nativeCurrency);

const isPendingSwap = checkForPendingSwap(transaction);

const inputAsset = useMemo(() => {
const change = transaction?.changes?.find(a => a?.direction === 'in');

if (!change?.asset) return undefined;

// NOTE: For pending transactions let's use the change value
// since the balance hasn't been updated yet.
if (['swap', 'wrap', 'unwrap'].includes(transaction.type) && transaction.status === 'pending') {
if (isPendingSwap) {
const inAssetValueDisplay = `${handleSignificantDecimals(convertRawAmountToDecimalFormat(change?.value?.toString() || '0', change?.asset.decimals || 18), change?.asset.decimals || 18)} ${change?.asset.symbol}`;
return {
inAssetValueDisplay,
Expand All @@ -311,7 +313,7 @@ export default function TransactionMasthead({ transaction }: { transaction: Rain
: '-',
...inAsset,
};
}, []);
}, [isPendingSwap, nativeCurrency, transaction?.changes]);

const outputAsset = useMemo(() => {
const change = transaction?.changes?.find(a => a?.direction === 'out');
Expand All @@ -320,7 +322,7 @@ export default function TransactionMasthead({ transaction }: { transaction: Rain

// NOTE: For pending transactions let's use the change value
// since the balance hasn't been updated yet.
if (['swap', 'wrap', 'unwrap'].includes(transaction.type) && transaction.status === 'pending') {
if (isPendingSwap) {
const inAssetValueDisplay = `${handleSignificantDecimals(convertRawAmountToDecimalFormat(change?.value?.toString() || '0', change?.asset.decimals || 18), change?.asset.decimals || 18)} ${change?.asset.symbol}`;
return {
inAssetValueDisplay,
Expand All @@ -345,7 +347,7 @@ export default function TransactionMasthead({ transaction }: { transaction: Rain
: '-',
...outAsset,
};
}, []);
}, [isPendingSwap, nativeCurrency, transaction?.changes]);

const contractImage = transaction?.contract?.iconUrl;
const contractName = transaction?.contract?.name;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { RainbowTransaction } from '@/entities';

export const checkForPendingSwap = (transaction: RainbowTransaction) => {
return ['swap', 'wrap', 'unwrap'].includes(transaction.type) && transaction.status === 'pending';
};

0 comments on commit 416ea1d

Please sign in to comment.