Skip to content

Commit

Permalink
improve: remove god hook
Browse files Browse the repository at this point in the history
  • Loading branch information
james-a-morris committed Nov 2, 2023
1 parent bd09774 commit 34c3b8c
Show file tree
Hide file tree
Showing 8 changed files with 121 additions and 119 deletions.
30 changes: 1 addition & 29 deletions src/hooks/useCoingeckoPrice.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,16 @@
import { utils } from "@across-protocol/sdk-v2";
import { BigNumber } from "ethers";
import { useCallback } from "react";
import { useQuery } from "react-query";
import { fixedPointAdjustment, getTokenByAddress } from "utils";
import { ConvertDecimals } from "utils/convertdecimals";
import getApiEndpoint from "utils/serverless-api";

export function useCoingeckoPrice(
l1Token: string,
baseCurrency: string,
enabled: boolean = true
) {
const query = useQuery(
return useQuery(
["price", l1Token, baseCurrency],
async () => getApiEndpoint().coingecko(l1Token, baseCurrency),
{
enabled,
}
);
const convertTokenToBaseCurrency = useCallback(
(amount?: BigNumber) => {
// Resolve the price as an 18 decimal big number which takes
// the form {PRICE} / 1 token
const price = query.data?.price;
// If the price is not defined yet, return undefined
if (!utils.isDefined(price) || !utils.isDefined(amount)) {
return undefined;
}
// Resolve token decimals
const { decimals } = getTokenByAddress(l1Token);
// Convert the amount to the base currency
const convertedAmount = ConvertDecimals(decimals, 18)(amount);
// Return the product of the price and the amount
return price.mul(convertedAmount).div(fixedPointAdjustment);
},
[l1Token, query.data]
);

return {
...query,
convertTokenToBaseCurrency,
};
}
32 changes: 32 additions & 0 deletions src/hooks/useTokenConversion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { utils } from "@across-protocol/sdk-v2";
import { useCoingeckoPrice } from "./useCoingeckoPrice";
import { BigNumber } from "ethers";
import { useCallback } from "react";
import { fixedPointAdjustment, getToken, getTokenByAddress } from "utils";
import { ConvertDecimals } from "utils/convertdecimals";

export function useTokenConversion(symbol: string, baseCurrency: string) {
const token = getToken(symbol);
const l1Token = token.mainnetAddress!;
const query = useCoingeckoPrice(
l1Token,
baseCurrency,
utils.isDefined(l1Token)
);
const convertTokenToBaseCurrency = useCallback(
(amount?: BigNumber) => {
const price = query.data?.price;
if (!utils.isDefined(price) || !utils.isDefined(amount)) {
return undefined;
}
const { decimals } = getTokenByAddress(l1Token);
const convertedAmount = ConvertDecimals(decimals, 18)(amount);
return price.mul(convertedAmount).div(fixedPointAdjustment);
},
[l1Token, query.data?.price]
);
return {
convertTokenToBaseCurrency,
baseCurrency,
};
}
6 changes: 0 additions & 6 deletions src/views/Bridge/Bridge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,6 @@ const Bridge = () => {
handleSelectToken,
handleSelectFromChain,
handleSelectToChain,
depositReferralReward,
convertTokensToBaseCurrency,
} = useBridge();

return (
Expand Down Expand Up @@ -74,8 +72,6 @@ const Bridge = () => {
toAccount={toAccount}
currentTokenMaxApy={currentTokenMaxApy}
isCurrentTokenMaxApyLoading={isCurrentTokenMaxApyLoading}
convertTokensToBaseCurrency={convertTokensToBaseCurrency}
depositReferralReward={depositReferralReward}
/>
) : (
<BridgeForm
Expand All @@ -100,8 +96,6 @@ const Bridge = () => {
isBridgeDisabled={isBridgeDisabled}
validationError={amountValidationError}
balance={balance}
convertTokensToBaseCurrency={convertTokensToBaseCurrency}
depositReferralReward={depositReferralReward}
/>
)}
</Wrapper>
Expand Down
6 changes: 0 additions & 6 deletions src/views/Bridge/components/BridgeForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,6 @@ type BridgeFormProps = {
buttonLabel: string;
isBridgeDisabled: boolean;
validationError?: AmountInputError;
convertTokensToBaseCurrency: ConvertTokensToBaseCurrencyType;
depositReferralReward?: BigNumber;
};

const BridgeForm = ({
Expand Down Expand Up @@ -79,8 +77,6 @@ const BridgeForm = ({
buttonLabel,
isBridgeDisabled,
validationError,
convertTokensToBaseCurrency,
depositReferralReward,
}: BridgeFormProps) => {
return (
<>
Expand Down Expand Up @@ -165,8 +161,6 @@ const BridgeForm = ({
Boolean(toAccount?.isContract)
)
)}
convertTokensToBaseCurrency={convertTokensToBaseCurrency}
depositReferralReward={depositReferralReward}
/>
{isWrongChain ? (
<Button onClick={onClickChainSwitch}>Switch Network</Button>
Expand Down
7 changes: 0 additions & 7 deletions src/views/Bridge/components/DepositConfirmation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import { getReceiveTokenSymbol } from "../utils";
import { ToAccount } from "../hooks/useToAccount";
import { useAmplitude } from "hooks/useAmplitude";
import { ampli } from "ampli";
import { ConvertTokensToBaseCurrencyType } from "../hooks/useBridge";

type DepositConfirmationProps = {
currentFromRoute: number | undefined;
Expand All @@ -49,8 +48,6 @@ type DepositConfirmationProps = {

currentTokenMaxApy?: BigNumber;
isCurrentTokenMaxApyLoading?: boolean;
convertTokensToBaseCurrency: ConvertTokensToBaseCurrencyType;
depositReferralReward?: BigNumber;
};

const logoMapping: {
Expand Down Expand Up @@ -84,8 +81,6 @@ const DepositConfirmation = ({
explorerLink: _explorerLink,
elapsedTimeFromDeposit,
currentTokenMaxApy,
convertTokensToBaseCurrency,
depositReferralReward,
}: DepositConfirmationProps) => {
const explorerLink = _explorerLink ?? "https://etherscan.io";

Expand Down Expand Up @@ -246,8 +241,6 @@ const DepositConfirmation = ({
Boolean(toAccount?.isContract)
)
)}
convertTokensToBaseCurrency={convertTokensToBaseCurrency}
depositReferralReward={depositReferralReward}
/>
<Divider />
<Button disabled={transactionPending} onClick={onClickNewTx}>
Expand Down
32 changes: 13 additions & 19 deletions src/views/Bridge/components/EstimatedTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,13 @@ import {
capitalizeFirstLetter,
COLORS,
formatUnits,
formatUnitsFnBuilder,
getChainInfo,
getToken,
TokenInfo,
} from "utils";

import TokenFee from "./TokenFee";
import { useState } from "react";
import { ConvertTokensToBaseCurrencyType } from "../hooks/useBridge";
import { useEstimatedTable } from "../hooks/useEstimatedTable";

type EstimatedTableProps = {
fromChainId: number;
Expand All @@ -31,8 +29,6 @@ type EstimatedTableProps = {
token: TokenInfo;
dataLoaded: boolean;
receiveToken: TokenInfo;
convertTokensToBaseCurrency: ConvertTokensToBaseCurrencyType;
depositReferralReward?: BigNumber;
};

const PriceFee = ({
Expand Down Expand Up @@ -74,22 +70,20 @@ const EstimatedTable = ({
token,
totalReceived,
receiveToken,
convertTokensToBaseCurrency: { l1: convertL1Token, acx: convertACXToken },
depositReferralReward,
}: EstimatedTableProps) => {
const [isDetailedFeesAvailable, setIsDetailedFeesAvailable] = useState(false);
const ArrowIcon = isDetailedFeesAvailable ? ArrowIconUp : ArrowIconDown;
const hasDepositReferralReward =
depositReferralReward && depositReferralReward.gt(0);
const {
isDetailedFeesAvailable,
setIsDetailedFeesAvailable,
referralRewardAsBaseCurrency,
gasFeeAsBaseCurrency,
bridgeFeeAsBaseCurrency,
netFeeAsBaseCurrency,
formatUsd,
depositReferralReward,
hasDepositReferralReward,
} = useEstimatedTable(token, gasFee, bridgeFee);

const referralRewardAsBaseCurrency = convertACXToken(depositReferralReward);
const gasFeeAsBaseCurrency = convertL1Token(gasFee);
const bridgeFeeAsBaseCurrency = convertL1Token(bridgeFee);
const netFeeAsBaseCurrency =
gasFeeAsBaseCurrency && bridgeFeeAsBaseCurrency
? gasFeeAsBaseCurrency.add(bridgeFeeAsBaseCurrency)
: undefined;
const formatUsd = formatUnitsFnBuilder(18);
const ArrowIcon = isDetailedFeesAvailable ? ArrowIconUp : ArrowIconDown;

return (
<Wrapper>
Expand Down
53 changes: 1 addition & 52 deletions src/views/Bridge/hooks/useBridge.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useCallback, useEffect, useState } from "react";
import { utils } from "@across-protocol/sdk-v2";

import { useConnection, useIsWrongNetwork, useAmplitude } from "hooks";
Expand All @@ -12,10 +12,7 @@ import { useToAccount } from "./useToAccount";
import { useSelectRoute } from "./useSelectRoute";
import { useTransferQuote } from "./useTransferQuote";
import { useAmountInput, useValidAmount } from "./useAmountInput";
import { useCoingeckoPrice } from "hooks/useCoingeckoPrice";
import { fixedPointAdjustment, getToken, parseUnits } from "utils";
import { BigNumber } from "ethers";
import { useReferralSummary } from "hooks/useReferralSummary";

export type ConvertTokensToBaseCurrencyType = {
l1: (amount?: BigNumber) => BigNumber | undefined;
Expand Down Expand Up @@ -50,19 +47,6 @@ export function useBridge() {
handleTransactionCompleted,
} = useBridgeDepositTracking();

const { convertTokenToBaseCurrency: convertL1ToBaseCurrency } =
useCoingeckoPrice(selectedRoute.l1TokenAddress, "usd");

const { convertTokenToBaseCurrency: convertACXToBaseCurrency } =
useCoingeckoPrice(getToken("ACX").mainnetAddress!, "usd");

const convertTokensToBaseCurrency: ConvertTokensToBaseCurrencyType = {
l1: convertL1ToBaseCurrency,
acx: convertACXToBaseCurrency,
};

const { summary: referralSummary } = useReferralSummary(account);

const { data: selectedRoutePool, isLoading: isSelectedRoutePoolLoading } =
useStakingPool(selectedRoute.l1TokenAddress);

Expand Down Expand Up @@ -94,39 +78,6 @@ export function useBridge() {
estimatedTime,
} = usedTransferQuote || {};

const depositReferralReward = useMemo(() => {
const fees = usedTransferQuote?.quotedFees;

if (!utils.isDefined(referralSummary) || !utils.isDefined(fees)) {
return undefined;
}
// Find total fees in terms of the token being bridged
const totalFees = fees.lpFee.total.add(fees.relayerFee.total);
// Convert the fees to usd using the token price
const totalFeesUSD = convertL1ToBaseCurrency(totalFees);
// Find the exchange rate for 1.0 token of ACX
const acxExchangeRate = convertACXToBaseCurrency(parseUnits("1", 18));
// Verify that the two usd values are defined
if (!utils.isDefined(totalFeesUSD) || !utils.isDefined(acxExchangeRate)) {
return undefined;
}
// Resolve total fees in terms of ACX
const totalFeesACX = totalFeesUSD
.mul(fixedPointAdjustment)
.div(acxExchangeRate);
// We can treat this as a percentage with 18 decimals
const feePct = parseUnits(referralSummary.referralRate.toString(), 18);
// Find the total referral reward as a percentage of the total fees
const referralReward = totalFeesACX.mul(feePct).div(fixedPointAdjustment);
// Return the referral reward in terms of ACX
return referralReward;
}, [
convertACXToBaseCurrency,
convertL1ToBaseCurrency,
referralSummary,
usedTransferQuote?.quotedFees,
]);

const { amountValidationError, isAmountValid } = useValidAmount(
parsedAmount,
quotedFees?.isAmountTooLow,
Expand Down Expand Up @@ -236,7 +187,5 @@ export function useBridge() {
handleSelectToken,
isCurrentTokenMaxApyLoading: isSelectedRoutePoolLoading,
currentTokenMaxApy: selectedRoutePool?.apyData.maxApy,
convertTokensToBaseCurrency,
depositReferralReward,
};
}
74 changes: 74 additions & 0 deletions src/views/Bridge/hooks/useEstimatedTable.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { utils } from "@across-protocol/sdk-v2";
import { BigNumber } from "ethers";
import { useConnection } from "hooks";
import { useReferralSummary } from "hooks/useReferralSummary";
import { useTokenConversion } from "hooks/useTokenConversion";
import { useMemo, useState } from "react";
import {
TokenInfo,
fixedPointAdjustment,
formatUnitsFnBuilder,
parseUnits,
} from "utils";

export function useEstimatedTable(
token: TokenInfo,
gasFee?: BigNumber,
bridgeFee?: BigNumber
) {
const [isDetailedFeesAvailable, setIsDetailedFeesAvailable] = useState(false);

const { account } = useConnection();
const { summary: referralSummary } = useReferralSummary(account);

const { convertTokenToBaseCurrency: convertL1ToBaseCurrency } =
useTokenConversion(token.symbol, "usd");
const { convertTokenToBaseCurrency: convertRewardToBaseCurrency } =
useTokenConversion("ACX", "usd");

const depositReferralReward = useMemo(() => {
if (!utils.isDefined(referralSummary) || !utils.isDefined(bridgeFee)) {
return undefined;
}
const totalFeesUSD = convertL1ToBaseCurrency(bridgeFee);
const acxExchangeRate = convertRewardToBaseCurrency(parseUnits("1", 18));
if (!utils.isDefined(totalFeesUSD) || !utils.isDefined(acxExchangeRate)) {
return undefined;
}
const totalFeesACX = totalFeesUSD
.mul(fixedPointAdjustment)
.div(acxExchangeRate);
const feePct = parseUnits(referralSummary.referralRate.toString(), 18);
return totalFeesACX.mul(feePct).div(fixedPointAdjustment);
}, [
referralSummary,
bridgeFee,
convertL1ToBaseCurrency,
convertRewardToBaseCurrency,
]);

const referralRewardAsBaseCurrency = convertRewardToBaseCurrency(
depositReferralReward
);
const gasFeeAsBaseCurrency = convertL1ToBaseCurrency(gasFee);
const bridgeFeeAsBaseCurrency = convertL1ToBaseCurrency(bridgeFee);
const netFeeAsBaseCurrency =
gasFeeAsBaseCurrency && bridgeFeeAsBaseCurrency
? gasFeeAsBaseCurrency.add(bridgeFeeAsBaseCurrency)
: undefined;
const formatUsd = formatUnitsFnBuilder(18);
const hasDepositReferralReward =
depositReferralReward && depositReferralReward.gt(0);

return {
isDetailedFeesAvailable,
setIsDetailedFeesAvailable,
referralRewardAsBaseCurrency,
gasFeeAsBaseCurrency,
bridgeFeeAsBaseCurrency,
netFeeAsBaseCurrency,
formatUsd,
depositReferralReward,
hasDepositReferralReward,
};
}

0 comments on commit 34c3b8c

Please sign in to comment.