Skip to content
Open
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
33 changes: 31 additions & 2 deletions src/components/transactions/Repay/RepayActions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ import { queryKeysFactory } from 'src/ui-config/queries';
import { useShallow } from 'zustand/shallow';

import { TxActionsWrapper } from '../TxActionsWrapper';
import { APPROVAL_GAS_LIMIT, checkRequiresApproval } from '../utils';
import { APPROVAL_GAS_LIMIT, checkRequiresApproval, getRepayAmountToApprove } from '../utils';
import { RepayAllowance, RepayAllowanceControl } from './RepayAllowanceControl';

export interface RepayActionProps extends BoxProps {
amountToRepay: string;
Expand Down Expand Up @@ -78,6 +79,7 @@ export const RepayActions = ({
const { sendTx } = useWeb3Context();
const queryClient = useQueryClient();
const [signatureParams, setSignatureParams] = useState<SignedParams | undefined>();
const [allowance, setAllowance] = useState(RepayAllowance.UNLIMITED);
const {
approvalTxState,
mainTxState,
Expand All @@ -104,15 +106,29 @@ export const RepayActions = ({

setLoadingTxns(fetchingApprovedAmount);

// Single source for what the approval has to cover: the gate below and the approval we
// build must never disagree, or a successful approval gets rejected on the next render.
const amountRequiringApproval = Number(amountToRepay) === -1 ? maxApproveNeeded : amountToRepay;

const requiresApproval =
!repayWithATokens &&
Number(amountToRepay) !== 0 &&
checkRequiresApproval({
approvedAmount: approvedAmount?.amount || '0',
amount: Number(amountToRepay) === -1 ? maxApproveNeeded : amountToRepay,
amount: amountRequiringApproval,
signedAmount: signatureParams ? signatureParams.amount : '0',
});

const amountToApprove = getRepayAmountToApprove({
amountRequiringApproval,
isMaxRepay: Number(amountToRepay) === -1,
decimals: poolReserve.decimals,
});

// Permit already signs for an exact amount, so the choice only applies to approve().
const canChooseAllowance = !repayWithATokens && !usePermit && Number(amountToRepay) !== 0;
const approveExactAmount = canChooseAllowance && allowance === RepayAllowance.EXACT;

if (requiresApproval && approvalTxState?.success) {
// There was a successful approval tx, but the approval amount is not enough.
// Clear the state to prompt for another approval.
Expand All @@ -127,6 +143,9 @@ export const RepayActions = ({
symbol,
decimals: poolReserve.decimals,
signatureAmount: amountToRepay,
amountToApprove: approveExactAmount
? parseUnits(amountToApprove, poolReserve.decimals).toString()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This runs during render, and getRepayAmountToApprove returns the typed string untouched on the partial branch. The repay input has no decimalScale (AssetInput.tsx:39), so USDC (6dp) + 1.1234567 + "Exact amount" throws fractional component exceeds decimals and takes the modal down. The existing parseUnits calls are inside action()'s try/catch, so today the same input just fails the tx.

.decimalPlaces(decimals, BigNumber.ROUND_UP).toString(10) on both branches fixes it, and stops the footer showing more decimals than the token has.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed - NumberFormatCustom has no decimalScale, so 7dp on a 6dp token is reachable by typing, and this one runs at render rather than inside action().

getRepayAmountToApprove now rounds on both branches (.decimalPlaces(decimals, ROUND_UP).toString(10)), so parseUnits cannot throw and the footer stops showing decimals the token does not have. Rounding up rather than down keeps the approval at or above the gate target, so no approve loop. Two tests added in utils.test.ts for the trim and for the gate still passing afterwards.

: undefined,
onApprovalTxConfirmed: fetchApprovedAmount,
onSignTxCompleted: (signedParams) => setSignatureParams(signedParams),
chainId,
Expand Down Expand Up @@ -256,6 +275,16 @@ export const RepayActions = ({
actionText={<Trans>Repay {symbol}</Trans>}
actionInProgressText={<Trans>Repaying {symbol}</Trans>}
tryPermit={permitAvailable}
approvalOptions={
canChooseAllowance ? (
<RepayAllowanceControl
allowance={allowance}
setAllowance={setAllowance}
exactAmount={amountToApprove}
symbol={symbol}
/>
) : undefined
}
requiresApprovalReset={requiresApprovalReset}
/>
);
Expand Down
113 changes: 113 additions & 0 deletions src/components/transactions/Repay/RepayAllowanceControl.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import { CheckIcon } from '@heroicons/react/outline';
import { CogIcon } from '@heroicons/react/solid';
import { Trans } from '@lingui/macro';
import {
Box,
ListItemIcon,
ListItemText,
Menu,
MenuItem,
SvgIcon,
Typography,
} from '@mui/material';
import * as React from 'react';

export enum RepayAllowance {
EXACT = 'exact',
UNLIMITED = 'unlimited',
}

interface RepayAllowanceControlProps {
allowance: RepayAllowance;
setAllowance: (allowance: RepayAllowance) => void;
/** Full-precision amount that will be approved when EXACT is selected. */
exactAmount: string;
symbol: string;
}

/**
* Repay's own allowance picker, rather than an option on the shared
* ApprovalMethodToggleButton. Being Repay-specific is the point: it knows the amount, so
* it can show the figure the approval gate is asking for. That number is otherwise
* invisible, which is what left users re-approving an allowance they thought was ample.
*/
export const RepayAllowanceControl = ({
allowance,
setAllowance,
exactAmount,
symbol,
}: RepayAllowanceControlProps) => {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const isExact = allowance === RepayAllowance.EXACT;

const select = (next: RepayAllowance) => {
setAllowance(next);
setAnchorEl(null);
};

return (
<Box sx={{ display: 'inline-flex', alignItems: 'center', mb: 2 }}>
<Typography variant="subheader2" color="text.secondary">
<Trans>Allowance</Trans>&nbsp;
</Typography>
<Box
onClick={(event: React.MouseEvent<HTMLDivElement>) => setAnchorEl(event.currentTarget)}
sx={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}
data-cy="repayAllowanceChange"
>
<Typography variant="subheader2" color="info.main" component="span">
{isExact ? `${exactAmount} ${symbol}` : <Trans>Unlimited</Trans>}
</Typography>
<SvgIcon sx={{ fontSize: 16, ml: 1, color: 'info.main' }}>
<CogIcon />
</SvgIcon>
</Box>

<Menu
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={() => setAnchorEl(null)}
keepMounted={true}
data-cy={`repayAllowanceMenu_${allowance}`}
>
<MenuItem
data-cy="repayAllowanceOption_exact"
selected={isExact}
onClick={() => select(RepayAllowance.EXACT)}
>
<ListItemText
primaryTypographyProps={{ variant: 'subheader1' }}
secondaryTypographyProps={{ variant: 'caption' }}
secondary={
<Trans>
{exactAmount} {symbol} — covers interest accruing before the transaction lands
</Trans>
}
>
<Trans>Exact amount</Trans>
</ListItemText>
<ListItemIcon>
<SvgIcon>{isExact && <CheckIcon />}</SvgIcon>
</ListItemIcon>
</MenuItem>

<MenuItem
data-cy="repayAllowanceOption_unlimited"
selected={!isExact}
onClick={() => select(RepayAllowance.UNLIMITED)}
>
<ListItemText
primaryTypographyProps={{ variant: 'subheader1' }}
secondaryTypographyProps={{ variant: 'caption' }}
secondary={<Trans>No further approvals needed for future repays</Trans>}
>
<Trans>Unlimited</Trans>
</ListItemText>
<ListItemIcon>
<SvgIcon>{!isExact && <CheckIcon />}</SvgIcon>
</ListItemIcon>
</MenuItem>
</Menu>
</Box>
);
};
7 changes: 3 additions & 4 deletions src/components/transactions/Repay/RepayModalContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import {
DetailsNumberLineWithSub,
TxModalDetails,
} from '../FlowCommons/TxModalDetails';
import { getSafeAmountToRepayAll } from '../utils';
import { RepayActions } from './RepayActions';

interface RepayAsset extends Asset {
Expand Down Expand Up @@ -82,9 +83,7 @@ export const RepayModalContent = ({
.multipliedBy(marketReferencePriceInUsd)
.shiftedBy(-USD_DECIMALS);

const safeAmountToRepayAll = valueToBigNumber(debt)
.multipliedBy('1.0025')
.decimalPlaces(poolReserve.decimals, BigNumber.ROUND_UP);
const safeAmountToRepayAll = getSafeAmountToRepayAll(debt, poolReserve.decimals);

// calculate max amount abailable to repay
let maxAmountToRepay: BigNumber;
Expand Down Expand Up @@ -293,7 +292,7 @@ export const RepayModalContent = ({
)}

<RepayActions
maxApproveNeeded={safeAmountToRepayAll.toString()}
maxApproveNeeded={safeAmountToRepayAll.toString(10)}
poolReserve={poolReserve}
amountToRepay={isMaxSelected ? repayMax : amount}
poolAddress={
Expand Down
6 changes: 5 additions & 1 deletion src/components/transactions/TxActionsWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ interface TxActionsWrapperProps extends BoxProps {
};
tryPermit?: boolean;
permitInUse?: boolean;
/** Extra approval controls for a specific flow, shown alongside the method toggle. */
approvalOptions?: ReactNode;
event?: TrackEventProps;
}

Expand All @@ -59,6 +61,7 @@ export const TxActionsWrapper = ({
errorParams,
tryPermit,
permitInUse = false,
approvalOptions,
event,
...rest
}: TxActionsWrapperProps) => {
Expand Down Expand Up @@ -146,12 +149,13 @@ export const TxActionsWrapper = ({
return (
<Box sx={{ display: 'flex', flexDirection: 'column', mt: 12, ...sx }} {...rest}>
{approvalParams && !readOnlyModeAddress && (
<Box sx={{ display: 'flex', justifyContent: 'end', alignItems: 'center' }}>
<Box sx={{ display: 'flex', justifyContent: 'end', alignItems: 'center', gap: 4 }}>
<RightHelperText
approvalHash={approvalTxState?.txHash}
tryPermit={tryPermit}
permitInUse={permitInUse}
/>
{!approvalTxState?.txHash && approvalOptions}
</Box>
)}

Expand Down
103 changes: 103 additions & 0 deletions src/components/transactions/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { BigNumber } from 'bignumber.js';
import { parseUnits } from 'ethers/lib/utils';

import { checkRequiresApproval, getRepayAmountToApprove, getSafeAmountToRepayAll } from '../utils';

/**
* Numbers taken from the cbBTC support report on Aave V3 Ethereum
* (wallet 0xCA686974913389D42F3C5F61010503DAccDb487a, block 25703709).
* The user approved 32.7 by hand, which the UI never accepted.
*/
const DEBT = '32.68074616';
const HAND_SET_APPROVAL = '32.7';
const DECIMALS = 8;

const gateRequires = (debt: string) => getSafeAmountToRepayAll(debt, DECIMALS).toString(10);

/** Does an allowance of `approved` let the user past the approval gate for this debt? */
const passesGate = (approved: string, debt: string) =>
!checkRequiresApproval({
approvedAmount: approved,
amount: gateRequires(debt),
signedAmount: '0',
});

const approvalForMaxRepay = (debt: string) =>
getRepayAmountToApprove({
amountRequiringApproval: gateRequires(debt),
isMaxRepay: true,
decimals: DECIMALS,
});

describe('getSafeAmountToRepayAll', () => {
it('applies the full-repay buffer on top of the debt', () => {
expect(gateRequires(DEBT)).toBe('32.76244803');
});
});

describe('getRepayAmountToApprove', () => {
it('leaves a partial repay amount untouched', () => {
expect(
getRepayAmountToApprove({
amountRequiringApproval: '10.5',
isMaxRepay: false,
decimals: DECIMALS,
})
).toBe('10.5');
});

it('trims a typed amount to the token decimals so parseUnits cannot throw', () => {
// The repay input has no decimalScale, so 7dp on a 6dp token is reachable by typing.
const approved = getRepayAmountToApprove({
amountRequiringApproval: '1.1234567',
isMaxRepay: false,
decimals: 6,
});

expect(approved).toBe('1.123457');
expect(() => parseUnits(approved, 6)).not.toThrow();
});

it('rounds a typed amount up, so the trimmed approval still clears the gate', () => {
const typed = '1.1234567';
const approved = getRepayAmountToApprove({
amountRequiringApproval: typed,
isMaxRepay: false,
decimals: 6,
});

expect(new BigNumber(approved).isGreaterThanOrEqualTo(typed)).toBe(true);
expect(
checkRequiresApproval({ approvedAmount: approved, amount: typed, signedAmount: '0' })
).toBe(false);
});

it('reproduces the reported bug: a hand-set approval above the debt still fails the gate', () => {
expect(new BigNumber(HAND_SET_APPROVAL).isGreaterThan(DEBT)).toBe(true);
expect(passesGate(HAND_SET_APPROVAL, DEBT)).toBe(false);
});

it('approves an amount that satisfies the gate for a full repay', () => {
expect(passesGate(approvalForMaxRepay(DEBT), DEBT)).toBe(true);
});

it('still satisfies the gate after the debt accrues while the approval is in flight', () => {
const approved = approvalForMaxRepay(DEBT);
// Debt keeps growing, so the gate's target creeps up after we build the approval.
const accruedDebt = new BigNumber(DEBT).multipliedBy('1.002').toString(10);

// Approving exactly what the gate asked for at t0 would now fall short -
// this is what the margin exists to absorb.
expect(passesGate(gateRequires(DEBT), accruedDebt)).toBe(false);
expect(passesGate(approved, accruedDebt)).toBe(true);
});

it('never returns more decimals than the token supports', () => {
const approved = approvalForMaxRepay(DEBT);
expect(new BigNumber(approved).decimalPlaces()).toBeLessThanOrEqual(DECIMALS);
});

it('does not return exponential notation for dust-sized debts', () => {
expect(approvalForMaxRepay('0.00000001')).not.toMatch(/e/i);
});
});
Loading
Loading