Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master' into new-gas-price-oracle
Browse files Browse the repository at this point in the history
  • Loading branch information
pxrl committed Nov 29, 2024
2 parents 3f4e53c + 7c8213c commit 31eab92
Show file tree
Hide file tree
Showing 11 changed files with 270 additions and 35 deletions.
82 changes: 82 additions & 0 deletions api/cron-ping-endpoints.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { VercelResponse } from "@vercel/node";
import { ethers } from "ethers";
import { utils } from "@across-protocol/sdk";
import axios from "axios";

import { TypedVercelRequest } from "./_types";
import { HUB_POOL_CHAIN_ID, getLogger, handleErrorCondition } from "./_utils";
import { UnauthorizedError } from "./_errors";
import { CHAIN_IDs, TOKEN_SYMBOLS_MAP } from "./_constants";

const endpoints = [
{
url: "https://preview.across.to/api/swap/allowance",
params: {
amount: ethers.utils.parseUnits("1", 6).toString(),
tradeType: "minOutput",
inputToken: TOKEN_SYMBOLS_MAP.USDC.addresses[CHAIN_IDs.ARBITRUM],
originChainId: CHAIN_IDs.ARBITRUM,
outputToken: TOKEN_SYMBOLS_MAP.USDC.addresses[CHAIN_IDs.OPTIMISM],
destinationChainId: CHAIN_IDs.OPTIMISM,
depositor: "0x9A8f92a830A5cB89a3816e3D267CB7791c16b04D",
skipOriginTxEstimation: true,
refundOnOrigin: false,
},
updateIntervalSec: 10,
},
];

const maxDurationSec = 60;

const handler = async (
request: TypedVercelRequest<Record<string, never>>,
response: VercelResponse
) => {
const logger = getLogger();
logger.debug({
at: "CronPingEndpoints",
message: "Starting cron job...",
});
try {
const authHeader = request.headers?.["authorization"];
if (
!process.env.CRON_SECRET ||
authHeader !== `Bearer ${process.env.CRON_SECRET}`
) {
throw new UnauthorizedError();
}

// Skip cron job on testnet
if (HUB_POOL_CHAIN_ID !== 1) {
return;
}

const functionStart = Date.now();

const requestPromises = endpoints.map(
async ({ updateIntervalSec, url, params }) => {
while (true) {
const diff = Date.now() - functionStart;
// Stop after `maxDurationSec` seconds
if (diff >= maxDurationSec * 1000) {
break;
}
await axios.get(url, { params });
await utils.delay(updateIntervalSec);
}
}
);
await Promise.all(requestPromises);

logger.debug({
at: "CronPingEndpoints",
message: "Finished",
});
response.status(200);
response.send("OK");
} catch (error: unknown) {
return handleErrorCondition("cron-ping-endpoints", response, logger, error);
}
};

export default handler;
47 changes: 34 additions & 13 deletions src/components/AmountInput/AmountInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import { Text } from "components/Text";
import { Tooltip } from "components/Tooltip";
import { useTokenConversion } from "hooks/useTokenConversion";
import {
COLORS,
QUERIESV2,
formatUSD,
formatUnitsWithMaxFractions,
getToken,
isDefined,
isNumberEthersParseable,
parseUnits,
} from "utils";
Expand All @@ -25,6 +25,7 @@ export type Props = {
onClickMaxBalance: () => void;
inputTokenSymbol: string;
validationError?: string;
validationWarning?: string;
dataCy?: string;
disableErrorText?: boolean;
disableInput?: boolean;
Expand All @@ -41,15 +42,22 @@ export function AmountInput({
onClickMaxBalance,
inputTokenSymbol,
validationError,
validationWarning,
disableErrorText,
disableInput,
disableMaxButton,
displayTokenIcon,
}: Props) {
const token = getToken(inputTokenSymbol);

const isAmountValid =
(amountInput ?? "") === "" || !isDefined(validationError);
const validationLevel =
(amountInput ?? "") === ""
? "valid"
: validationError
? "error"
: validationWarning
? "warning"
: "valid";

const { convertTokenToBaseCurrency } = useTokenConversion(
inputTokenSymbol,
Expand All @@ -68,7 +76,7 @@ export function AmountInput({

return (
<Wrapper>
<InputGroupWrapper valid={isAmountValid}>
<InputGroupWrapper validationLevel={validationLevel}>
{displayTokenIcon ? (
token.logoURIs?.length === 2 ? (
<IconPairContainer>
Expand All @@ -84,7 +92,7 @@ export function AmountInput({
) : null}
<Input
type="number"
valid={isAmountValid}
validationLevel={validationLevel}
placeholder="Enter amount"
value={amountInput}
onWheel={(e) => e.currentTarget.blur()}
Expand Down Expand Up @@ -130,9 +138,9 @@ export function AmountInput({
${formatUSD(estimatedUsdInputAmount)}
</Text>
)}
{!isAmountValid && !disableErrorText && (
<Text size="md" color="error">
{validationError}
{validationLevel !== "valid" && !disableErrorText && (
<Text size="md" color={validationError ? "error" : "warning"}>
{validationError || validationWarning}
</Text>
)}
</InfoTextWrapper>
Expand All @@ -143,9 +151,24 @@ export function AmountInput({
export default AmountInput;

interface IValidInput {
valid: boolean;
validationLevel: "valid" | "error" | "warning";
}

const colorMap = {
valid: {
border: COLORS["grey-600"],
text: COLORS["white-100"],
},
error: {
border: COLORS.red,
text: COLORS.red,
},
warning: {
border: COLORS.yellow,
text: COLORS.yellow,
},
};

const Wrapper = styled.div`
display: flex;
flex-direction: column;
Expand All @@ -159,7 +182,7 @@ const InputGroupWrapper = styled.div<IValidInput>`
align-items: center;
padding: 9px 12px 9px 16px;
background: #2d2e33;
border: 1px solid ${({ valid }) => (valid ? "#3E4047" : "#f96c6c")};
border: 1px solid ${({ validationLevel }) => colorMap[validationLevel].border};
border-radius: 12px;
height: 48px;
gap: 8px;
Expand All @@ -173,9 +196,7 @@ const Input = styled.input<IValidInput>`
font-weight: 400;
font-size: 18px;
line-height: 26px;
color: #e0f3ff;
color: ${({ valid }) => (valid ? "#e0f3ff" : "#f96c6c")};
color: ${({ validationLevel }) => colorMap[validationLevel].text};
background: none;
width: 100%;
Expand Down
75 changes: 75 additions & 0 deletions src/hooks/useIndexerDepositTracking.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { useQueries } from "@tanstack/react-query";
import axios from "axios";
import { BigNumber } from "ethers";
import { indexerApiBaseUrl, isDefined } from "utils";

/**
* A hook used to track the statuses of multiple deposits via the indexer API
* @param deposits Array of deposit objects containing `originChainId` and `depositId`
*/
export function useIndexerDepositsTracking(
deposits: {
originChainId?: number;
depositId?: number;
}[]
) {
const queries = useQueries({
queries: deposits.map((deposit) => ({
queryKey: [
"indexer_deposit_tracking",
deposit.originChainId,
deposit.depositId,
] as [string, number, number],
enabled:
isDefined(deposit.originChainId) &&
isDefined(deposit.depositId) &&
isDefined(indexerApiBaseUrl),
queryFn: async (): Promise<BigNumber | undefined> => {
try {
const response = await axios.get(
`${indexerApiBaseUrl}/deposit/status`,
{
params: {
originChainId: deposit.originChainId,
depositId: deposit.depositId,
},
}
);
return response.data;
} catch (e) {
// FIXME: for now we ignore since this is for load testing purposes
}
},
refetchInterval: 5_000, // 5 seconds
})),
});

return queries.map((query) => ({
depositStatus: query.data ?? undefined,
...query,
}));
}

/**
* A hook used to track a single deposit status via the indexer API
* @param originChainId The chain ID of the deposit's origin
* @param depositId The deposit ID
*/
export function useIndexerDepositTracking(
originChainId?: number,
depositId?: number
) {
const [singleDeposit] = useIndexerDepositsTracking(
isDefined(originChainId) && isDefined(depositId)
? [{ originChainId, depositId }]
: []
);

return (
singleDeposit ?? {
depositStatus: undefined,
isLoading: false,
isError: false,
}
);
}
3 changes: 3 additions & 0 deletions src/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -536,3 +536,6 @@ export const vercelApiBaseUrl =
export const defaultSwapSlippage = Number(
process.env.REACT_APP_DEFAULT_SWAP_SLIPPAGE || 0.5
);

export const indexerApiBaseUrl =
process.env.REACT_APP_INDEXER_BASE_URL || undefined;
2 changes: 2 additions & 0 deletions src/views/Bridge/Bridge.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const Bridge = () => {
fees,
balance,
amountValidationError,
amountValidationWarning,
userAmountInput,
swapSlippage,
parsedAmountInput,
Expand Down Expand Up @@ -78,6 +79,7 @@ const Bridge = () => {
buttonLabel={buttonLabel}
isBridgeDisabled={isBridgeDisabled}
validationError={amountValidationError}
validationWarning={amountValidationWarning}
balance={balance}
isQuoteLoading={isQuoteLoading}
swapQuote={swapQuote}
Expand Down
48 changes: 38 additions & 10 deletions src/views/Bridge/components/AmountInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { AmountInputError, SelectedRoute } from "../utils";
import { formatUnitsWithMaxFractions, getToken } from "utils";
import { BridgeLimits } from "hooks";

const validationErrorTextMap = {
const validationErrorTextMap: Record<AmountInputError, string> = {
[AmountInputError.INSUFFICIENT_BALANCE]:
"Insufficient balance to process this transfer.",
[AmountInputError.PAUSED_DEPOSITS]:
Expand All @@ -16,6 +16,8 @@ const validationErrorTextMap = {
[AmountInputError.INVALID]: "Only positive numbers are allowed as an input.",
[AmountInputError.AMOUNT_TOO_LOW]:
"The amount you are trying to bridge is too low.",
[AmountInputError.PRICE_IMPACT_TOO_HIGH]:
"Price impact is too high. Check back later when liquidity is restored.",
};

type Props = {
Expand All @@ -25,6 +27,7 @@ type Props = {
onClickMaxBalance: () => void;
selectedRoute: SelectedRoute;
validationError?: AmountInputError;
validationWarning?: AmountInputError;
limits?: BridgeLimits;
};

Expand All @@ -35,6 +38,7 @@ export function AmountInput({
onClickMaxBalance,
selectedRoute,
validationError,
validationWarning,
limits,
}: Props) {
return (
Expand All @@ -47,15 +51,20 @@ export function AmountInput({
}
validationError={
validationError
? validationErrorTextMap[validationError]
.replace("[INPUT_TOKEN]", selectedRoute.fromTokenSymbol)
.replace(
"[MAX_DEPOSIT]",
`${formatUnitsWithMaxFractions(
limits?.maxDeposit || 0,
getToken(selectedRoute.fromTokenSymbol).decimals
)} ${selectedRoute.fromTokenSymbol}`
)
? getValidationErrorText({
validationError: validationError,
selectedRoute,
limits,
})
: undefined
}
validationWarning={
validationWarning
? getValidationErrorText({
validationError: validationWarning,
selectedRoute,
limits,
})
: undefined
}
onChangeAmountInput={onChangeAmountInput}
Expand All @@ -67,4 +76,23 @@ export function AmountInput({
);
}

function getValidationErrorText(props: {
validationError?: AmountInputError;
selectedRoute: SelectedRoute;
limits?: BridgeLimits;
}) {
if (!props.validationError) {
return undefined;
}
return validationErrorTextMap[props.validationError]
.replace("[INPUT_TOKEN]", props.selectedRoute.fromTokenSymbol)
.replace(
"[MAX_DEPOSIT]",
`${formatUnitsWithMaxFractions(
props.limits?.maxDeposit || 0,
getToken(props.selectedRoute.fromTokenSymbol).decimals
)} ${props.selectedRoute.fromTokenSymbol}`
);
}

export default AmountInput;
Loading

0 comments on commit 31eab92

Please sign in to comment.