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.

: 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
76 changes: 76 additions & 0 deletions src/components/transactions/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { BigNumber } from 'bignumber.js';

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('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);
});
});
45 changes: 45 additions & 0 deletions src/components/transactions/utils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { BigNumberValue, valueToBigNumber } from '@aave/math-utils';
import { BigNumber } from 'bignumber.js';
import { CollateralType } from 'src/helpers/types';
import { ComputedUserReserveData } from 'src/hooks/app-data-provider/useAppDataProvider';
Expand All @@ -20,6 +21,50 @@ export const useFlashloan = (healthFactor: string, hfEffectOfFromAmount: string)
export const APPROVAL_GAS_LIMIT = 65000;
export const APPROVE_DELEGATION_GAS_LIMIT = 55000;

/**
* Safety margin added to the debt when repaying the full balance. Debt accrues between
* reading it and the transaction landing, so the allowance has to cover a little more
* than the figure we last read.
*/
export const REPAY_ALL_BUFFER = '1.0025';

/**
* Additional margin applied on top of `REPAY_ALL_BUFFER` when building the approval
* itself. `checkRequiresApproval` compares the allowance against a target derived from
* live debt, so that target creeps upward while the approval is in flight; approving
* exactly what the gate asked for would leave the user re-approving forever.
*/
export const REPAY_ALL_APPROVAL_MARGIN = '1.0025';

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.

The margin leaves a residual allowance, which breaks USDT on Ethereum. Exact on a max repay approves debt * 1.0025 * 1.0025 but only pulls the debt, so ~0.5% survives. USDT reverts approve(spender, non-zero) over a non-zero allowance, and the reset path returns early when signatureAmount === '-1' (useApprovalTx.tsx:79), which is the max-repay case. The next full repay fails at gas estimation.

Unlimited never hit this since requiresApproval stays false after one max approval. Either hide Exact for USDT-on-Ethereum, or key needsUSDTApprovalReset off the approval amount rather than signatureAmount.


/** The amount the approval gate demands before a full repay is allowed to proceed. */
export const getSafeAmountToRepayAll = (debt: BigNumberValue, decimals: number): BigNumber =>
valueToBigNumber(debt).multipliedBy(REPAY_ALL_BUFFER).decimalPlaces(decimals, BigNumber.ROUND_UP);

/**
* The amount to put in an `approve` call for a repay, given whatever
* `checkRequiresApproval` is being asked to accept.
*
* Must never come out below that figure, or the approval succeeds and the gate rejects it
* on the next render, trapping the user in an approve loop.
*/
export const getRepayAmountToApprove = ({
amountRequiringApproval,
isMaxRepay,
decimals,
}: {
amountRequiringApproval: string;
isMaxRepay: boolean;
decimals: number;
}): string =>
// A typed amount is fixed, so the gate's target cannot drift away from it. A full repay
// is derived from live debt and does drift, hence the margin.
isMaxRepay
? valueToBigNumber(amountRequiringApproval)
.multipliedBy(REPAY_ALL_APPROVAL_MARGIN)
.decimalPlaces(decimals, BigNumber.ROUND_UP)
.toString(10)
: amountRequiringApproval;

export const checkRequiresApproval = ({
approvedAmount,
signedAmount,
Expand Down
2 changes: 1 addition & 1 deletion src/hooks/useApprovalTx.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ export const useApprovalTx = ({
action: ProtocolAction.approval,
txState: 'success',
asset: assetAddress,
amount: MAX_UINT_AMOUNT,
amount: amountToApprove ?? MAX_UINT_AMOUNT,

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.

amountToApprove is base units, so the Amplitude tokenAmount on GENERAL.TRANSACTION will report 3276244803 next to the 32.68 every other caller sends (RepayActions.tsx:209, SupplyActions.tsx:276). formatUnits(amountToApprove, decimals) keeps it consistent.

Not repay-only either: Bridge, Umbrella stake and unstake already pass amountToApprove, so their approval events change shape too.

assetName: symbol,
});
if (onApprovalTxConfirmed) {
Expand Down
2 changes: 1 addition & 1 deletion src/locales/el/messages.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/locales/en/messages.js

Large diffs are not rendered by default.

Loading
Loading