Skip to content

Commit

Permalink
BIP-49: Misc Improvements (#802)
Browse files Browse the repository at this point in the history
  • Loading branch information
BeanstalkFarmsOperations authored Aug 5, 2024
2 parents d49812a + ad09f10 commit b5a1e6e
Show file tree
Hide file tree
Showing 54 changed files with 2,647 additions and 861 deletions.
30 changes: 16 additions & 14 deletions projects/ui/src/components/Chop/Actions/Chop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,8 @@ import FarmModeField from '~/components/Common/Form/FarmModeField';
import Token, { ERC20Token, NativeToken } from '~/classes/Token';
import { Beanstalk } from '~/generated/index';
import useToggle from '~/hooks/display/useToggle';
import { useBeanstalkContract } from '~/hooks/ledger/useContract';
import useFarmerBalances from '~/hooks/farmer/useFarmerBalances';
import useTokenMap from '~/hooks/chain/useTokenMap';
import { useSigner } from '~/hooks/ledger/useSigner';
import useAccount from '~/hooks/ledger/useAccount';
import usePreferredToken, {
PreferredToken,
Expand Down Expand Up @@ -59,6 +57,7 @@ import useFormMiddleware from '~/hooks/ledger/useFormMiddleware';
import useSdk from '~/hooks/sdk';
import useBDV from '~/hooks/beanstalk/useBDV';
import { BalanceFrom } from '~/components/Common/Form/BalanceFromRow';
import { useUnripe } from '~/state/bean/unripe/updater';

type ChopFormValues = FormState & {
destination: FarmToMode | undefined;
Expand Down Expand Up @@ -283,9 +282,10 @@ const PREFERRED_TOKENS: PreferredToken[] = [

const Chop: FC<{}> = () => {
/// Ledger
const sdk = useSdk();
const account = useAccount();
const { data: signer } = useSigner();
const beanstalk = useBeanstalkContract(signer);
const beanstalk = sdk.contracts.beanstalk;
const [refetchUnripe] = useUnripe();

/// Farmer
const farmerBalances = useFarmerBalances();
Expand Down Expand Up @@ -313,7 +313,7 @@ const Chop: FC<{}> = () => {
values: ChopFormValues,
formActions: FormikHelpers<ChopFormValues>
) => {
let txToast;
const txToast = new TransactionToast({});
try {
middleware.before();

Expand All @@ -323,7 +323,7 @@ const Chop: FC<{}> = () => {
if (!state.amount?.gt(0))
throw new Error('No Unfertilized token to Chop.');

txToast = new TransactionToast({
txToast.setToastMessages({
loading: `Chopping ${displayFullBN(state.amount)} ${
state.token.symbol
}...`,
Expand All @@ -339,20 +339,22 @@ const Chop: FC<{}> = () => {
txToast.confirming(txn);

const receipt = await txn.wait();
await Promise.all([refetchFarmerBalances()]); // should we also refetch the penalty?
await Promise.all([refetchFarmerBalances(), refetchUnripe()]);
txToast.success(receipt);
formActions.resetForm();
} catch (err) {
if (txToast) {
txToast.error(err);
} else {
const errorToast = new TransactionToast({});
errorToast.error(err);
}
txToast.error(err);
formActions.setSubmitting(false);
}
},
[account, beanstalk, refetchFarmerBalances, farmerBalances, middleware]
[
account,
beanstalk,
farmerBalances,
middleware,
refetchFarmerBalances,
refetchUnripe,
]
);

return (
Expand Down
26 changes: 4 additions & 22 deletions projects/ui/src/components/Chop/ChopConditions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import {
} from '@mui/material';
import HelpOutlineIcon from '@mui/icons-material/HelpOutline';
import { useSelector } from 'react-redux';
import { displayBN, displayFullBN } from '../../util';
import { BeanstalkPalette, FontSize } from '../App/muiTheme';
import { AppState } from '~/state';
import useChainConstant from '~/hooks/chain/useChainConstant';
import { UNRIPE_BEAN } from '~/constants/tokens';

import { FC } from '~/types';
import { BeanstalkPalette, FontSize } from '../App/muiTheme';
import { displayBN, displayFullBN } from '../../util';

const ChopConditions: FC<{}> = () => {
const { fertilized, recapFundedPct, unfertilized } = useSelector<
Expand All @@ -33,7 +33,7 @@ const ChopConditions: FC<{}> = () => {
<Stack gap={1}>
<Typography variant="h4">Chop Conditions</Typography>
<Grid container spacing={2}>
<Grid item xs={6} md={3.7}>
<Grid item xs={6}>
<Stack gap={0.5}>
<Tooltip
title="The claim to future Ripe assets you are forfeiting by Chopping."
Expand Down Expand Up @@ -69,7 +69,7 @@ const ChopConditions: FC<{}> = () => {
)}
</Stack>
</Grid>
<Grid item xs={6} md={3.7}>
<Grid item xs={6}>
<Stack gap={0.5}>
<Tooltip
title="The ratio of Ripe to Unripe assets."
Expand All @@ -87,24 +87,6 @@ const ChopConditions: FC<{}> = () => {
</Typography>
</Stack>
</Grid>
<Grid item xs={6} md={4.6}>
<Stack gap={0.5}>
<Tooltip
title="The percentage of Sprouts that have become Rinsable."
placement="top"
>
<Typography variant="body1">
Debt Repaid to Fertilizer&nbsp;
<HelpOutlineIcon
sx={{ color: 'text.secondary', fontSize: FontSize.sm }}
/>
</Typography>
</Tooltip>
<Typography variant="bodyLarge" fontWeight="400">
{pctDebtRepaid.times(100).toFixed(4)}%
</Typography>
</Stack>
</Grid>
</Grid>
</Stack>
</Card>
Expand Down
32 changes: 28 additions & 4 deletions projects/ui/src/components/Common/TxnToast.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import React, { useCallback } from 'react';
import { ContractReceipt, ContractTransaction } from 'ethers';
import toast from 'react-hot-toast';
import { Box, IconButton, Link, Typography } from '@mui/material';
import { Box, IconButton, Link } from '@mui/material';
import ClearIcon from '@mui/icons-material/Clear';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import useChainConstant from '~/hooks/chain/useChainConstant';
Expand Down Expand Up @@ -45,7 +45,15 @@ export function ToastAlert({
overflow: 'hidden',
}}
>
<Box sx={{ pl: 1, pr: 2, flex: 1, alignSelf: 'flex-start', textAlign: 'center' }}>
<Box
sx={{
pl: 1,
pr: 2,
flex: 1,
alignSelf: 'flex-start',
textAlign: 'center',
}}
>
<span>
{desc}
{hash && (
Expand Down Expand Up @@ -125,6 +133,12 @@ type ToastMessages = {
error?: string;
};

const defaultToastMessages: ToastMessages = {
loading: 'Confirming transaction...',
success: 'Transaction confirmed.',
error: 'Transaction failed.',
};

/**
* A lightweight wrapper around react-hot-toast
* to minimize repetitive Toast code when issuing transactions.
Expand All @@ -136,13 +150,23 @@ export default class TransactionToast {
/** */
toastId: any;

constructor(messages: ToastMessages) {
this.messages = messages;
constructor(messages: Partial<ToastMessages>) {
this.messages = {
...defaultToastMessages,
...messages,
};
this.toastId = toast.loading(<ToastAlert desc={this.messages.loading} />, {
duration: Infinity,
});
}

setToastMessages(messages: Partial<ToastMessages>) {
this.messages = {
...this.messages,
...messages,
};
}

/**
* Shows a loading message with Etherscan txn link while
* a transaction is confirming
Expand Down
53 changes: 10 additions & 43 deletions projects/ui/src/components/Silo/Actions/Convert.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import {
FormStateNew,
FormTxnsFormState,
SettingInput,
SettingSwitch,
SmartSubmitButton,
TxnSettings,
} from '~/components/Common/Form';
Expand Down Expand Up @@ -66,7 +65,6 @@ import { AppState } from '~/state';
type ConvertFormValues = FormStateNew & {
settings: {
slippage: number;
allowUnripeConvert: boolean;
};
maxAmountIn: BigNumber | undefined;
tokenOut: Token | undefined;
Expand All @@ -79,16 +77,6 @@ type ConvertQuoteHandlerParams = {

// -----------------------------------------------------------------------

const filterTokenList = (
fromToken: Token,
allowUnripeConvert: boolean,
list: Token[]
): Token[] => {
if (allowUnripeConvert || !fromToken.isUnripe) return list;

return list.filter((token) => token.isUnripe);
};

const ConvertForm: FC<
FormikProps<ConvertFormValues> & {
/** List of tokens that can be converted to. */
Expand All @@ -103,7 +91,7 @@ const ConvertForm: FC<
plantAndDoX: ReturnType<typeof usePlantAndDoX>;
}
> = ({
tokenList: tokenListFull,
tokenList,
siloBalances,
handleQuote,
plantAndDoX,
Expand All @@ -123,23 +111,6 @@ const ConvertForm: FC<
const unripeTokens = useSelector<AppState, AppState['_bean']['unripe']>(
(_state) => _state._bean.unripe
);
const [tokenList, setTokenList] = useState(
filterTokenList(
values.tokens[0].token,
values.settings.allowUnripeConvert,
tokenListFull
)
);

useEffect(() => {
setTokenList(
filterTokenList(
values.tokens[0].token,
values.settings.allowUnripeConvert,
tokenListFull
)
);
}, [tokenListFull, values.settings.allowUnripeConvert, values.tokens]);

const plantCrate = plantAndDoX?.crate?.bn;

Expand Down Expand Up @@ -223,12 +194,16 @@ const ConvertForm: FC<
}

useEffect(() => {
if (confirmText.toUpperCase() === 'CHOP MY ASSETS') {
setChoppingConfirmed(true);
if (isChopping) {
if (confirmText.toUpperCase() === 'CHOP MY ASSETS') {
setChoppingConfirmed(true);
} else {
setChoppingConfirmed(false);
}
} else {
setChoppingConfirmed(false);
setChoppingConfirmed(true);
}
}, [confirmText, setChoppingConfirmed]);
}, [isChopping, confirmText, setChoppingConfirmed]);

function getBDVTooltip(instantBDV: BigNumber, depositBDV: BigNumber) {
return (
Expand All @@ -244,6 +219,7 @@ const ConvertForm: FC<
}

function showOutputBDV() {
if (isChopping) return bdvOut || ZERO_BN;
return MaxBN(depositsBDV || ZERO_BN, bdvOut || ZERO_BN);
}

Expand Down Expand Up @@ -292,7 +268,6 @@ const ConvertForm: FC<
tokenOut?.address === sdk.tokens.BEAN_WSTETH_WELL_LP.address);

setIsChopping(chopping);
if (!chopping) setChoppingConfirmed(true);
}
})();
}, [sdk, setFieldValue, tokenIn, tokenOut]);
Expand Down Expand Up @@ -636,7 +611,6 @@ const ConvertPropProvider: FC<{
// Settings
settings: {
slippage: 0.05,
allowUnripeConvert: false,
},
// Token Inputs
tokens: [
Expand Down Expand Up @@ -958,13 +932,6 @@ const ConvertPropProvider: FC<{
label="Slippage Tolerance"
endAdornment="%"
/>
{/* Only show the switch if we are on an an unripe silo's page */}
{fromToken.isUnripe && (
<SettingSwitch
name="settings.allowUnripeConvert"
label="Allow Converts to Ripe (Chop)"
/>
)}
</TxnSettings>
<ConvertForm
handleQuote={handleQuote}
Expand Down
3 changes: 1 addition & 2 deletions projects/ui/src/components/Silo/Whitelist.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -751,9 +751,8 @@ const Whitelist: FC<{
title="Chop Amount"
gap={0.25}
variant="h4"
// After Chop Change, update this to: recap rate * Total LP Underlying urBEANETH * BeanEth LP Price
amount={`${unripeTokens[token.address]?.penalty?.times(100).toFixed(3)}%`}
subtitle="The amount of BEANETH received for Chopping 1 urBEANETH."
subtitle="The amount of BEANwstETH received for Chopping 1 urBEANwstETH."
/>
) : (
<Stat
Expand Down
6 changes: 3 additions & 3 deletions projects/ui/src/hooks/chain/useTokenMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@ import { useMemo } from 'react';
import { Token } from '@beanstalk/sdk';
import TokenOld from '~/classes/Token';
import { ChainConstant, TokenMap } from '~/constants';
import useGetChainToken from './useGetChainToken';
import { getTokenIndex } from '~/util';
import useGetChainToken from './useGetChainToken';

export default function useTokenMap<T extends Token | TokenOld>(
list: (T | ChainConstant<T>)[]
list: (T | ChainConstant<T>)[] | Set<T>
) {
const getChainToken = useGetChainToken();
return useMemo(
() =>
list.reduce<TokenMap<T>>((acc, curr) => {
[...list].reduce<TokenMap<T>>((acc, curr) => {
// If this entry in the list is a Token and not a TokenMap, we
// simply return the token. Otherwise we get the appropriate chain-
// specific Token. This also dedupes tokens by address.
Expand Down
2 changes: 1 addition & 1 deletion projects/ui/src/state/bean/unripe/updater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export const useUnripe = () => {
// bean:3crv, which had 18 decimals
return new BigNumber(result.toString()).div(1e18);
}
return tokenResult(unripeTokens[addr])(result); // Is this correct ?
return tokenResult(unripeTokens[addr])(result);
}),
])
)
Expand Down
Loading

0 comments on commit b5a1e6e

Please sign in to comment.