utils#ChainId TypeScript Examples
The following examples show how to use
utils#ChainId.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: hooks.ts From frontend-v1 with GNU Affero General Public License v3.0 | 5 votes |
export function useSend() {
const dispatch = useAppDispatch();
const actions = bindActionCreators(
{
tokenAction,
amountAction,
fromChainAction,
toChainAction,
toAddressAction,
sendErrorAction,
},
dispatch
);
const send = useAppSelector((state) => state.send);
const sendAcross = useSendAcross();
const sendOptimism = useSendOptimism();
const sendArbitrum = useSendArbitrum();
const sendBoba = useSendBoba();
const setSend = {
setToken: actions.tokenAction,
setAmount: actions.amountAction,
setFromChain: actions.fromChainAction,
setToChain: actions.toChainAction,
setToAddress: actions.toAddressAction,
setError: actions.sendErrorAction,
};
if (send.fromChain === ChainId.MAINNET && send.toChain === ChainId.OPTIMISM) {
return {
...send,
...setSend,
...sendOptimism,
};
}
if (send.fromChain === ChainId.MAINNET && send.toChain === ChainId.ARBITRUM) {
return {
...send,
...setSend,
...sendArbitrum,
};
}
if (send.fromChain === ChainId.MAINNET && send.toChain === ChainId.BOBA) {
return {
...send,
...setSend,
...sendBoba,
};
}
return {
...send,
...setSend,
...sendAcross,
};
}
Example #2
Source File: Confirmation.tsx From frontend-v1 with GNU Affero General Public License v3.0 | 5 votes |
MAINNET_ETH = TOKENS_LIST[ChainId.MAINNET].find(
(t) => t.symbol === "ETH"
)
Example #3
Source File: AddressSelection.tsx From frontend-v1 with GNU Affero General Public License v3.0 | 4 votes |
AddressSelection: React.FC = () => {
const { isConnected } = useConnection();
const { toChain, toAddress, fromChain, setToAddress } = useSend();
const [address, setAddress] = useState("");
const [open, setOpen] = useState(false);
const dispatch = useAppDispatch();
const sendState = useAppSelector((state) => state.send);
const { trackEvent } = useMatomo();
const {
isOpen,
selectedItem,
getLabelProps,
getToggleButtonProps,
getItemProps,
getMenuProps,
} = useSelect({
items: CHAINS_SELECTION,
defaultSelectedItem: sendState.currentlySelectedToChain,
selectedItem: sendState.currentlySelectedToChain,
onSelectedItemChange: ({ selectedItem }) => {
if (selectedItem) {
// Matomo track toChain selection
trackEvent({
category: "send",
action: "setToChain",
name: selectedItem.chainId.toString(),
});
const nextState = { ...sendState, toChain: selectedItem.chainId };
dispatch(actions.toChain(nextState));
dispatch(actions.updateSelectedToChain(selectedItem));
const nsToChain = { ...sendState };
if (selectedItem.chainId === ChainId.MAINNET) {
nsToChain.fromChain = ChainId.OPTIMISM;
dispatch(actions.fromChain(nsToChain));
dispatch(actions.updateSelectedFromChain(CHAINS_SELECTION[0]));
}
}
},
});
useEffect(() => {
if (toAddress) {
setAddress(toAddress);
}
}, [toAddress]);
const toggle = () => {
// modal is closing, reset address to the current toAddress
if (!isConnected) return;
if (open) setAddress(toAddress || address);
setOpen((oldOpen) => !oldOpen);
};
const clearInput = () => {
setAddress("");
};
const handleChange = (evt: React.ChangeEvent<HTMLInputElement>) => {
setAddress(evt.target.value);
};
const isValid = !address || isValidAddress(address);
const handleSubmit = () => {
if (isValid && address) {
setToAddress({ toAddress: address });
toggle();
}
};
const isL1toL2 = fromChain === ChainId.MAINNET;
return (
<AnimatePresence>
<LastSection>
<Wrapper>
<SectionTitle>To</SectionTitle>
<InputGroup>
<RoundBox as="label" {...getLabelProps()}>
<ToggleButton type="button" {...getToggleButtonProps()}>
<Logo src={selectedItem?.logoURI} alt={selectedItem?.name} />
<div>
<ToggleChainName>
{selectedItem?.name === "Ether"
? "Mainnet"
: selectedItem?.name}
</ToggleChainName>
{toAddress && <Address>{shortenAddress(toAddress)}</Address>}
</div>
<ToggleIcon />
</ToggleButton>
</RoundBox>
<Menu isOpen={isOpen} {...getMenuProps()}>
{isOpen &&
sendState.currentlySelectedToChain.chainId !==
ChainId.MAINNET &&
CHAINS_SELECTION.map((t, index) => {
return (
<Item
className={
t === sendState.currentlySelectedToChain ||
t.chainId === ChainId.MAINNET
? "disabled"
: ""
}
{...getItemProps({ item: t, index })}
key={t.chainId}
>
<Logo src={t.logoURI} alt={t.name} />
<div>{t.name}</div>
<span className="layer-type">
{t.chainId !== ChainId.MAINNET ? "L2" : "L1"}
</span>
</Item>
);
})}
{isOpen &&
sendState.currentlySelectedToChain.chainId ===
ChainId.MAINNET && (
<>
<ItemWarning
initial={{ y: -10 }}
animate={{ y: 0 }}
exit={{ y: -10 }}
>
<p>
Transfers between L2 chains is not possible at this time
</p>
</ItemWarning>
{CHAINS_SELECTION.map((t, index) => {
return (
<Item
className={"disabled"}
{...getItemProps({ item: t, index })}
key={t.chainId}
initial={{ y: -10 }}
animate={{ y: 0 }}
exit={{ y: -10 }}
>
<Logo src={t.logoURI} alt={t.name} />
<div>{t.name}</div>
<span className="layer-type">
{index !== CHAINS_SELECTION.length - 1
? "L2"
: "L1"}
</span>
</Item>
);
})}
</>
)}
</Menu>
</InputGroup>
{!isL1toL2 && (
<ChangeWrapper onClick={toggle}>
<ChangeButton className={!isConnected ? "disabled" : ""}>
Change account
</ChangeButton>
</ChangeWrapper>
)}
</Wrapper>
<Dialog isOpen={open} onClose={toggle}>
<h3>Send To</h3>
<div>Address on {CHAINS[toChain].name}</div>
<InputWrapper>
<Input onChange={handleChange} value={address} />
<ClearButton onClick={clearInput}>
<XOctagon
fill="var(--color-gray-300)"
stroke="var(--color-white)"
/>
</ClearButton>
{!isValid && <InputError>Not a valid address</InputError>}
</InputWrapper>
<ButtonGroup>
<CancelButton onClick={toggle}>Cancel</CancelButton>
<SecondaryButton
onClick={handleSubmit}
disabled={!isValid || !address}
>
Save Changes
</SecondaryButton>
</ButtonGroup>
</Dialog>
</LastSection>
</AnimatePresence>
);
}
Example #4
Source File: ChainSelection.tsx From frontend-v1 with GNU Affero General Public License v3.0 | 4 votes |
ChainSelection: React.FC = () => {
const { init } = onboard;
const { isConnected, provider, chainId, error } = useConnection();
const sendState = useAppSelector((state) => state.send);
const dispatch = useAppDispatch();
const { trackEvent } = useMatomo();
/*
The following block will attempt to change the dropdown when the user connects the app.
Otherwise, it just makes sure to map the dropdown value when the currentSelected block changes.
This will also change the dropdown value in <AddressSelection /> because of the hook in there.
*/
const previousChainId = usePrevious(chainId);
useEffect(() => {
if (chainId && previousChainId === undefined) {
const findChain = CHAINS_SELECTION.find((x) => x.chainId === chainId);
const notFindChain = CHAINS_SELECTION.filter(
(x) => x.chainId !== chainId
);
if (findChain && notFindChain) {
dispatch(actions.updateSelectedFromChain(findChain));
dispatch(
actions.updateSelectedToChain(notFindChain[notFindChain.length - 1])
);
dispatch(
actions.fromChain({ ...sendState, fromChain: findChain.chainId })
);
dispatch(
actions.toChain({
...sendState,
toChain: notFindChain[notFindChain.length - 1].chainId,
})
);
}
}
}, [
chainId,
previousChainId,
sendState.currentlySelectedFromChain,
dispatch,
sendState,
]);
const wrongNetworkSend =
provider &&
chainId &&
(error instanceof UnsupportedChainIdError ||
chainId !== sendState.currentlySelectedFromChain.chainId);
const buttonText = wrongNetworkSend
? `Switch to ${CHAINS[sendState.currentlySelectedFromChain.chainId].name}`
: !isConnected
? "Connect Wallet"
: null;
const handleClick = () => {
if (!provider) {
init();
} else if (wrongNetworkSend) {
switchChain(provider, sendState.currentlySelectedFromChain.chainId);
}
};
const {
isOpen,
selectedItem,
getLabelProps,
getToggleButtonProps,
getItemProps,
getMenuProps,
} = useSelect({
items: CHAINS_SELECTION,
defaultSelectedItem: sendState.currentlySelectedFromChain,
selectedItem: sendState.currentlySelectedFromChain,
onSelectedItemChange: ({ selectedItem }) => {
if (selectedItem) {
// Matomo track fromChain
trackEvent({
category: "send",
action: "setFromChain",
name: selectedItem.chainId.toString(),
});
const nextState = { ...sendState, fromChain: selectedItem.chainId };
dispatch(actions.fromChain(nextState));
dispatch(actions.updateSelectedFromChain(selectedItem));
const nsToChain = { ...sendState, toChain: ChainId.MAINNET };
if (selectedItem.chainId === ChainId.MAINNET) {
nsToChain.toChain = ChainId.OPTIMISM;
dispatch(actions.toChain(nsToChain));
dispatch(actions.updateSelectedToChain(CHAINS_SELECTION[0]));
}
if (
selectedItem.chainId !== ChainId.MAINNET &&
sendState.currentlySelectedToChain.chainId !== ChainId.MAINNET
) {
dispatch(
actions.updateSelectedToChain(
CHAINS_SELECTION[CHAINS_SELECTION.length - 1]
)
);
}
}
},
});
return (
<Section>
<Wrapper>
{disableSendForm && (
<SendBlockedWarning>
<div>
Across V1 sending is disabled, please visit{" "}
<a href="https://v2.across.to" target="_blank" rel="noreferrer">
{" "}
Across V2
</a>{" "}
</div>
</SendBlockedWarning>
)}
<SectionTitle>From</SectionTitle>
<InputGroup>
<RoundBox as="label" {...getLabelProps()}>
<ToggleButton type="button" {...getToggleButtonProps()}>
<Logo src={selectedItem?.logoURI} alt={selectedItem?.name} />
<ToggleChainName>{selectedItem?.name}</ToggleChainName>
<ToggleIcon />
</ToggleButton>
</RoundBox>
<Menu isOpen={isOpen} {...getMenuProps()}>
{isOpen &&
CHAINS_SELECTION.map((t, index) => {
return (
<Item
className={
t === sendState.currentlySelectedFromChain
? "disabled"
: ""
}
{...getItemProps({ item: t, index })}
initial={{ y: -10 }}
animate={{ y: 0 }}
exit={{ y: -10 }}
key={t.chainId}
>
<Logo src={t.logoURI} alt={t.name} />
<div>{t.name}</div>
<span className="layer-type">
{index !== CHAINS_SELECTION.length - 1 ? "L2" : "L1"}
</span>
</Item>
);
})}
</Menu>
</InputGroup>
{(wrongNetworkSend || !isConnected) && (
<ConnectButton onClick={handleClick}>{buttonText}</ConnectButton>
)}
</Wrapper>
</Section>
);
}
Example #5
Source File: CoinSelection.tsx From frontend-v1 with GNU Affero General Public License v3.0 | 4 votes |
CoinSelection = () => {
const { account, isConnected } = useConnection();
const { setAmount, setToken, amount, token, fees } = useSend();
const { trackEvent } = useMatomo();
const [error, setError] = React.useState<Error>();
const sendState = useAppSelector((state) => state.send);
const tokenList = useMemo(() => {
const filterByToChain = (token: Token) =>
TOKENS_LIST[sendState.currentlySelectedToChain.chainId].some(
(element) => element.symbol === token.symbol
);
if (
sendState.currentlySelectedFromChain.chainId === ChainId.MAINNET &&
sendState.currentlySelectedToChain.chainId === ChainId.OPTIMISM
) {
// Note: because of how Optimism treats WETH, it must not be sent over their canonical bridge.
return TOKENS_LIST[sendState.currentlySelectedFromChain.chainId]
.filter((element) => element.symbol !== "WETH")
.filter(filterByToChain);
}
return TOKENS_LIST[sendState.currentlySelectedFromChain.chainId].filter(
filterByToChain
);
}, [
sendState.currentlySelectedFromChain.chainId,
sendState.currentlySelectedToChain.chainId,
]);
const { data: balances } = useBalances(
{
account: account!,
chainId: sendState.currentlySelectedFromChain.chainId,
},
{ skip: !account }
);
const tokenBalanceMap = useMemo(() => {
return TOKENS_LIST[sendState.currentlySelectedFromChain.chainId].reduce(
(acc, val, idx) => {
return {
...acc,
[val.address]: balances ? balances[idx] : undefined,
};
},
{} as Record<string, BigNumber | undefined>
);
}, [balances, sendState.currentlySelectedFromChain.chainId]);
const [dropdownItem, setDropdownItem] = useState(() =>
tokenList.find((t) => t.address === token)
);
// Adjust coin dropdown when chain id changes, as some tokens don't exist on all chains.
useEffect(() => {
const newToken = tokenList.find(
(t) => t.address === ethers.constants.AddressZero
);
setInputAmount("");
// since we are resetting input to 0, reset any errors
setError(undefined);
setAmount({ amount: BigNumber.from("0") });
setDropdownItem(() => newToken);
setToken({ token: newToken?.address || "" });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [sendState.currentlySelectedFromChain.chainId, tokenList]);
const {
isOpen,
selectedItem,
getLabelProps,
getToggleButtonProps,
getItemProps,
getMenuProps,
} = useSelect({
items: tokenList,
defaultSelectedItem: tokenList.find((t) => t.address === token),
selectedItem: dropdownItem,
onSelectedItemChange: ({ selectedItem }) => {
if (selectedItem) {
// Matomo track token selection
trackEvent({
category: "send",
action: "setAsset",
name: selectedItem.symbol,
});
setInputAmount("");
// since we are resetting input to 0, reset any errors
setError(undefined);
setAmount({ amount: BigNumber.from("0") });
setToken({ token: selectedItem.address });
setDropdownItem(selectedItem);
}
},
});
const [inputAmount, setInputAmount] = React.useState<string>(
selectedItem && amount.gt("0")
? formatUnits(amount, selectedItem.decimals)
: ""
);
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const value = event.target.value;
setInputAmount(value);
if (value === "") {
setAmount({ amount: ethers.constants.Zero });
setError(undefined);
return;
}
try {
const amount = parseUnits(value, selectedItem!.decimals);
// just throw an error if lt 0 and let the catch set the parsing error
if (amount.lt(0)) throw new Error();
setAmount({ amount });
if (error instanceof ParsingError) {
setError(undefined);
}
} catch (e) {
setError(new ParsingError());
}
};
// checks for insufficient balance errors
useEffect(() => {
if (amount && inputAmount) {
// clear the previous error if it is not a parsing error
setError((oldError) => {
if (oldError instanceof ParsingError) {
return oldError;
}
return undefined;
});
if (balances && amount.gt(0)) {
const selectedIndex = tokenList.findIndex(
({ address }) => address === token
);
const balance = tokenBalanceMap[token];
const isEth = tokenList[selectedIndex]?.symbol === "ETH";
if (
balance &&
amount.gt(
isEth
? balance.sub(ethers.utils.parseEther(FEE_ESTIMATION))
: balance
)
) {
setError(new Error("Insufficient balance."));
}
}
}
}, [balances, amount, token, tokenList, inputAmount, tokenBalanceMap]);
const handleMaxClick = () => {
if (balances && selectedItem) {
const selectedIndex = tokenList.findIndex(
({ address }) => address === selectedItem.address
);
const isEth = tokenList[selectedIndex].symbol === "ETH";
let balance = tokenBalanceMap[token];
if (balance) {
if (isEth) {
balance = max(
balance.sub(ethers.utils.parseEther(FEE_ESTIMATION)),
0
);
}
setAmount({ amount: balance });
setInputAmount(formatUnits(balance, selectedItem.decimals));
} else {
setAmount({ amount: ethers.BigNumber.from("0") });
setInputAmount(
formatUnits(ethers.BigNumber.from("0"), selectedItem.decimals)
);
}
}
};
const errorMsg = error
? error.message
: fees?.isAmountTooLow
? "Bridge fee is high for this amount. Send a larger amount."
: fees?.isLiquidityInsufficient
? `Insufficient liquidity for ${selectedItem?.symbol}.`
: undefined;
const showError =
error ||
(fees?.isAmountTooLow && amount.gt(0)) ||
(fees?.isLiquidityInsufficient && amount.gt(0));
return (
<AnimatePresence>
<Section>
<Wrapper>
<SectionTitle>Asset</SectionTitle>
<InputGroup>
<RoundBox as="label" {...getLabelProps()}>
<ToggleButton type="button" {...getToggleButtonProps()}>
<Logo src={selectedItem?.logoURI} alt={selectedItem?.name} />
<div>{selectedItem?.symbol}</div>
<ToggleIcon />
</ToggleButton>
</RoundBox>
<RoundBox
as="label"
htmlFor="amount"
style={{
// @ts-expect-error TS does not likes custom CSS vars
"--color": error
? "var(--color-error-light)"
: "var(--color-white)",
"--outline-color": error
? "var(--color-error)"
: "var(--color-primary)",
}}
>
<MaxButton onClick={handleMaxClick} disabled={!isConnected}>
max
</MaxButton>
<Input
placeholder="0.00"
id="amount"
value={inputAmount}
onChange={handleChange}
/>
</RoundBox>
<Menu {...getMenuProps()} isOpen={isOpen}>
{isOpen &&
tokenList.map((token, index) => (
<Item
{...getItemProps({ item: token, index })}
initial={{ y: -10 }}
animate={{ y: 0 }}
exit={{ y: -10 }}
key={token.address}
>
<Logo src={token.logoURI} alt={token.name} />
<div>{token.name}</div>
<div>
{tokenBalanceMap &&
formatUnits(
tokenBalanceMap[token.address] || "0",
tokenList[index].decimals
)}
</div>
</Item>
))}
</Menu>
</InputGroup>
{showError && <ErrorBox>{errorMsg}</ErrorBox>}
</Wrapper>
</Section>
</AnimatePresence>
);
}
Example #6
Source File: PoolSelection.tsx From frontend-v1 with GNU Affero General Public License v3.0 | 4 votes |
PoolSelection: FC<Props> = ({ token, setToken, position }) => {
const { account } = useConnection();
const { data: balances } = useBalances(
{
account: account!,
chainId: ChainId.MAINNET,
},
{ skip: !account }
);
const {
isOpen,
selectedItem,
getLabelProps,
getToggleButtonProps,
getItemProps,
getMenuProps,
} = useSelect({
items: TOKENS_LIST[ChainId.MAINNET],
defaultSelectedItem: token,
onSelectedItemChange: ({ selectedItem }) => {
if (selectedItem) {
setToken(selectedItem);
}
},
});
return (
<AnimatePresence>
<Wrapper>
{migrationPoolV2Warning ? (
<MigrationWarning>
<div>
If you have not migrated liquidity from Across v1 to Across v2,
please follow{" "}
<a
href="https://docs.across.to/v2/migrating-from-v1"
target="_blank"
rel="noreferrer"
>
{" "}
these instructions
</a>{" "}
</div>
</MigrationWarning>
) : null}
<SectionTitle>Select pool</SectionTitle>
<InputGroup>
<RoundBox as="label" {...getLabelProps()}>
<ToggleButton type="button" {...getToggleButtonProps()}>
<Logo src={selectedItem?.logoURI} alt={selectedItem?.name} />
<div>{selectedItem?.symbol}</div>
<ToggleIcon />
</ToggleButton>
</RoundBox>
<Menu {...getMenuProps()} isOpen={isOpen}>
{isOpen &&
TOKENS_LIST[ChainId.MAINNET].map((t, index) => {
return (
<Item
{...getItemProps({ item: t, index })}
key={t.address}
initial={{ y: -10 }}
animate={{ y: 0 }}
exit={{ y: -10 }}
>
<Logo src={t.logoURI} alt={t.name} />
<div>{t.name}</div>
<div>
{balances && formatUnits(balances[index], t.decimals)}
</div>
</Item>
);
})}
</Menu>
</InputGroup>
</Wrapper>
</AnimatePresence>
);
}
Example #7
Source File: SendAction.tsx From frontend-v1 with GNU Affero General Public License v3.0 | 4 votes |
SendAction: React.FC = () => {
const {
amount,
token,
send,
hasToApprove,
canApprove,
canSend,
toAddress,
approve,
fees,
spender,
} = useSend();
const { signer, account, name } = useConnection();
const sendState = useAppSelector((state) => state.send);
const [isInfoModalOpen, setOpenInfoModal] = useState(false);
const toggleInfoModal = () => setOpenInfoModal((oldOpen) => !oldOpen);
const [isSendPending, setSendPending] = useState(false);
const [isApprovalPending, setApprovalPending] = useState(false);
const { addTransaction } = useTransactions();
const { addDeposit } = useDeposits();
const [updateEthBalance] = api.endpoints.ethBalance.useLazyQuery();
const { trackEvent } = useMatomo();
// trigger balance update
const [updateBalances] = api.endpoints.balances.useLazyQuery();
const tokenInfo = TOKENS_LIST[
sendState.currentlySelectedFromChain.chainId
].find((t) => t.address === token);
const { error, addError, removeError } = useContext(ErrorContext);
const { refetch } = useAllowance(
{
owner: account!,
spender,
chainId: sendState.currentlySelectedFromChain.chainId,
token,
amount,
},
{ skip: !account }
);
const handleApprove = async () => {
const tx = await approve();
if (tx) {
addTransaction({ ...tx, meta: { label: TransactionTypes.APPROVE } });
await tx.wait(CONFIRMATIONS);
refetch();
}
};
const handleSend = async () => {
const { tx, fees } = await send();
if (tx && fees) {
addTransaction({ ...tx, meta: { label: TransactionTypes.DEPOSIT } });
const receipt = await tx.wait(CONFIRMATIONS);
addDeposit({
tx: receipt,
toChain: sendState.currentlySelectedToChain.chainId,
fromChain: sendState.currentlySelectedFromChain.chainId,
amount,
token,
toAddress,
fees,
});
// update balances after tx
if (account) {
updateEthBalance({
chainId: sendState.currentlySelectedFromChain.chainId,
account,
});
updateBalances({
chainId: sendState.currentlySelectedFromChain.chainId,
account,
});
}
}
};
const handleClick = () => {
if (amount.lte(0) || !signer || disableSendForm) {
return;
}
if (hasToApprove) {
setApprovalPending(true);
handleApprove()
.catch((err) => {
addError(new Error(`Error in approve call: ${err.message}`));
console.error(err);
})
.finally(() => setApprovalPending(false));
return;
}
if (canSend) {
// Matomo track send transactions
trackEvent({
category: "send",
action: "bridge",
name:
tokenInfo &&
JSON.stringify({
symbol: tokenInfo.symbol,
from: sendState.currentlySelectedFromChain.chainId,
to: sendState.currentlySelectedToChain.chainId,
}),
value: tokenInfo && Number(formatUnits(amount, tokenInfo.decimals)),
});
setSendPending(true);
if (error) removeError();
handleSend()
.catch((err) => {
addError(new Error(`Error with send call: ${err.message}`));
console.error(err);
})
// this actually happens after component unmounts, which is not good. it causes a react warning, but we need
// it here if user cancels the send. so keep this until theres a better way.
.finally(() => setSendPending(false));
}
};
const buttonMsg = () => {
if (isSendPending) return "Sending in progress...";
if (isApprovalPending) return "Approval in progress...";
if (hasToApprove) return "Approve";
return "Send";
};
const amountMinusFees = useMemo(() => {
if (sendState.currentlySelectedFromChain.chainId === ChainId.MAINNET) {
return amount;
}
return receiveAmount(amount, fees);
}, [amount, fees, sendState.currentlySelectedFromChain.chainId]);
const buttonDisabled =
isSendPending ||
isApprovalPending ||
(!hasToApprove && !canSend) ||
(hasToApprove && !canApprove) ||
amountMinusFees.lte(0);
const isWETH = tokenInfo?.symbol === "WETH";
return (
<AccentSection>
<Wrapper>
{amount.gt(0) && fees && tokenInfo && (
<>
<InfoHeadlineContainer>
<SlippageDisclaimer>
<ConfettiIcon />
All transfers are slippage free!
</SlippageDisclaimer>
<FeesButton onClick={toggleInfoModal}>Fees info</FeesButton>
</InfoHeadlineContainer>
<InfoContainer>
<Info>
{`Time to ${
CHAINS[sendState.currentlySelectedToChain.chainId].name
}`}
<div>
{getEstimatedDepositTime(
sendState.currentlySelectedToChain.chainId
)}
</div>
</Info>
{sendState.currentlySelectedFromChain.chainId !==
ChainId.MAINNET && (
<Info>
<div>Ethereum Network Gas</div>
<div>
{formatUnits(
fees.instantRelayFee.total.add(fees.slowRelayFee.total),
tokenInfo.decimals
)}{" "}
{tokenInfo.symbol}
</div>
</Info>
)}
<Info>
<div>
{sendState.currentlySelectedFromChain.chainId ===
ChainId.MAINNET
? "Native Bridge Fee"
: "Across Bridge Fee"}
</div>
<div>
{sendState.currentlySelectedFromChain.chainId ===
ChainId.MAINNET
? "Free"
: `${formatUnits(fees.lpFee.total, tokenInfo.decimals)}
${tokenInfo.symbol}`}
</div>
</Info>
</InfoContainer>
<AmountToReceive>
You will receive
<span>
{formatUnits(amountMinusFees, tokenInfo.decimals)}{" "}
{isWETH ? "ETH" : tokenInfo.symbol}
</span>
</AmountToReceive>
</>
)}
<PrimaryButton
onClick={handleClick}
disabled={buttonDisabled || !!disableSendForm}
>
<span>{buttonMsg()}</span>
</PrimaryButton>
{name && name === "WalletConnect" && (
<WalletConnectWarning>
<span>
Do not change networks after connecting to Across with
WalletConnect. Across is not responsible for wallet-based
integration issues with WalletConnect.
</span>
</WalletConnectWarning>
)}
{sendState.currentlySelectedFromChain.chainId === ChainId.MAINNET && (
<L1Info>
<div>L1 to L2 transfers use the destination’s native bridge</div>
</L1Info>
)}
</Wrapper>
<InformationDialog isOpen={isInfoModalOpen} onClose={toggleInfoModal} />
</AccentSection>
);
}
Example #8
Source File: hooks.ts From frontend-v1 with GNU Affero General Public License v3.0 | 4 votes |
export function useSendArbitrum() {
const [bridge, setBridge] = useState<Bridge | undefined>();
const [bridgeAddress, setBridgeAddress] = useState("");
const { isConnected, chainId, account, signer } = useConnection();
const {
fromChain,
toChain,
toAddress,
amount,
token,
currentlySelectedFromChain,
currentlySelectedToChain,
error,
} = useAppSelector((state) => state.send);
const { block } = useL2Block();
const { balance: balanceStr } = useBalance({
chainId: fromChain,
account,
tokenAddress: token,
});
const balance = BigNumber.from(balanceStr);
const [refetchAllowance, { data: allowance }] =
chainApi.endpoints.allowance.useLazyQuery();
const canApprove = balance.gte(amount) && amount.gte(0);
const hasToApprove = allowance?.hasToApprove ?? true;
//TODO: Add fees
const [fees] = useState({
instantRelayFee: {
total: BigNumber.from("0"),
pct: BigNumber.from("0"),
},
slowRelayFee: {
total: BigNumber.from("0"),
pct: BigNumber.from("0"),
},
lpFee: {
total: BigNumber.from("0"),
pct: BigNumber.from("0"),
},
isAmountTooLow: false,
isLiquidityInsufficient: false,
});
useEffect(() => {
initBridgeClient();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [signer, account, fromChain, toChain, isConnected]);
const initBridgeClient = async () => {
if (!signer || !account) return;
if (fromChain !== ChainId.MAINNET) return;
if (toChain !== ChainId.ARBITRUM) return;
if (!isConnected) return;
const provider = PROVIDERS[ChainId.ARBITRUM]();
try {
const bridge = await Bridge.init(signer, provider.getSigner(account));
setBridge(bridge);
} catch (error) {
console.error(error);
}
};
const send = useCallback(async () => {
if (!bridge || !isConnected) return {};
if (
!(await validateContractAndChain(
(
await bridge.l1Bridge.getInbox()
).address,
fromChain,
bridge.l1Bridge.l1Signer
))
) {
return {};
}
if (token === ethers.constants.AddressZero) {
return {
tx: await bridge.depositETH(amount),
fees,
};
} else {
const depositParams = await bridge.getDepositTxParams({
erc20L1Address: token,
amount,
destinationAddress: toAddress,
});
return {
tx: await bridge.deposit(depositParams),
fees,
};
}
}, [bridge, amount, fees, token, isConnected, toAddress, fromChain]);
const approve = useCallback(() => {
if (!bridge) return;
return bridge.approveToken(token, MAX_APPROVAL_AMOUNT);
}, [bridge, token]);
useEffect(() => {
if (!bridge || !account || !token || !chainId || !amount) return;
bridge.l1Bridge
.getGatewayAddress(token)
.then((spender) => {
setBridgeAddress(spender);
return refetchAllowance({
owner: account,
spender,
chainId,
token,
amount,
});
})
.catch(console.error);
}, [bridge, amount, token, chainId, account, refetchAllowance]);
const hasToSwitchChain =
isConnected && currentlySelectedFromChain.chainId !== chainId;
const canSend = useMemo(
() =>
currentlySelectedFromChain.chainId &&
block &&
currentlySelectedToChain.chainId &&
amount &&
token &&
fees &&
toAddress &&
isValidAddress(toAddress) &&
!hasToApprove &&
!hasToSwitchChain &&
!error &&
balance.gte(amount),
[
currentlySelectedFromChain.chainId,
block,
currentlySelectedToChain.chainId,
amount,
token,
fees,
toAddress,
hasToApprove,
hasToSwitchChain,
error,
balance,
]
);
return {
canSend,
canApprove,
hasToApprove,
hasToSwitchChain,
send,
approve,
fees,
spender: bridgeAddress,
};
}
Example #9
Source File: hooks.ts From frontend-v1 with GNU Affero General Public License v3.0 | 4 votes |
export function useSendBoba() {
const [bobaBridge] = useState(new BobaBridgeClient());
const [bridgeAddress, setBridgeAddress] = useState("");
const { isConnected, chainId, account, signer } = useConnection();
const {
fromChain,
amount,
token,
currentlySelectedFromChain,
currentlySelectedToChain,
toAddress,
error,
} = useAppSelector((state) => state.send);
const { block } = useL2Block();
const { balance: balanceStr } = useBalance({
chainId: fromChain,
account,
tokenAddress: token,
});
const balance = BigNumber.from(balanceStr);
const { data: allowance } = useAllowance(
{
chainId: fromChain,
token,
owner: account!,
spender: bridgeAddress,
amount,
},
{ skip: !account || !isConnected || !chainId }
);
const canApprove = balance.gte(amount) && amount.gte(0);
const hasToApprove = allowance?.hasToApprove ?? true;
//TODO: Add fees
const [fees] = useState({
instantRelayFee: {
total: BigNumber.from("0"),
pct: BigNumber.from("0"),
},
slowRelayFee: {
total: BigNumber.from("0"),
pct: BigNumber.from("0"),
},
lpFee: {
total: BigNumber.from("0"),
pct: BigNumber.from("0"),
},
isAmountTooLow: false,
isLiquidityInsufficient: false,
});
useEffect(() => {
if (!bobaBridge) return;
bobaBridge
.getL1BridgeAddress(chainId as number, PROVIDERS[ChainId.MAINNET]())
.then((address) => {
setBridgeAddress(address);
})
.catch(() => {
setBridgeAddress("");
});
}, [bobaBridge, chainId]);
const send = useCallback(async () => {
if (!isConnected || !signer) return {};
if (!(await validateContractAndChain(bridgeAddress, fromChain, signer))) {
return {};
}
if (token === ethers.constants.AddressZero) {
return {
tx: await bobaBridge.depositEth(signer, amount),
fees,
};
} else {
const pairToken = bobaErc20Pairs()[token];
if (!pairToken) return {};
return {
tx: await bobaBridge.depositERC20(signer, token, pairToken, amount),
fees,
};
}
}, [
amount,
fees,
token,
isConnected,
bobaBridge,
signer,
fromChain,
bridgeAddress,
]);
const approve = useCallback(() => {
if (!signer) return;
return bobaBridge.approve(signer, token, MAX_APPROVAL_AMOUNT);
}, [bobaBridge, signer, token]);
const hasToSwitchChain =
isConnected && currentlySelectedFromChain.chainId !== chainId;
const canSend = useMemo(
() =>
currentlySelectedFromChain.chainId &&
block &&
currentlySelectedToChain.chainId &&
amount &&
token &&
fees &&
toAddress &&
isValidAddress(toAddress) &&
!hasToApprove &&
!hasToSwitchChain &&
!error &&
balance.gte(amount),
[
currentlySelectedFromChain.chainId,
block,
currentlySelectedToChain.chainId,
amount,
token,
fees,
toAddress,
hasToApprove,
hasToSwitchChain,
error,
balance,
]
);
return {
canSend,
canApprove,
hasToApprove,
hasToSwitchChain,
send,
approve,
fees,
spender: bridgeAddress,
};
}
Example #10
Source File: Pool.tsx From frontend-v1 with GNU Affero General Public License v3.0 | 4 votes |
Pool: FC = () => {
const [token, setToken] = useState<Token>(TOKENS_LIST[ChainId.MAINNET][2]);
const [showSuccess, setShowSuccess] = useState<ShowSuccess | undefined>();
const [depositUrl, setDepositUrl] = useState("");
const [loadingPoolState, setLoadingPoolState] = useState(false);
const [defaultTab, setDefaultTab] = useState("Add");
const pool = useAppSelector((state) => state.pools.pools[token.bridgePool]);
const connection = useAppSelector((state) => state.connection);
const userPosition = useAppSelector((state) =>
get(state, [
"pools",
"users",
state?.connection?.account || "",
token.bridgePool,
])
);
const { isConnected, account, provider, error, chainId } = useConnection();
const queries = useAppSelector((state) => state.api.queries);
const { balance, refetch: refetchBalance } = useBalance({
chainId: ChainId.MAINNET,
account,
tokenAddress: token.address,
});
const wrongNetwork =
provider &&
(error instanceof UnsupportedChainIdError ||
chainId !== DEFAULT_TO_CHAIN_ID);
// Update pool info when token changes
useEffect(() => {
setLoadingPoolState(true);
poolClient.updatePool(token.bridgePool).then((res) => {
setLoadingPoolState(false);
});
}, [token, setLoadingPoolState]);
useEffect(() => {
if (isConnected && connection.account && token.bridgePool) {
poolClient.updateUser(connection.account, token.bridgePool);
}
}, [isConnected, connection.account, token.bridgePool]);
useEffect(() => {
// Recheck for balances. note: Onboard provider is faster than ours.
if (depositUrl) {
setTimeout(() => {
refetchBalance();
}, 15000);
}
}, [depositUrl, refetchBalance]);
return (
<Layout>
{!showSuccess ? (
<Wrapper>
<PoolSelection
wrongNetwork={wrongNetwork}
token={token}
setToken={setToken}
position={
userPosition
? ethers.BigNumber.from(userPosition.positionValue)
: ethers.BigNumber.from("0")
}
/>
{!loadingPoolState ? (
<PoolForm
wrongNetwork={wrongNetwork}
symbol={token.symbol}
icon={token.logoURI}
decimals={token.decimals}
tokenAddress={token.address}
totalPoolSize={
pool && pool.totalPoolSize
? ethers.BigNumber.from(pool.totalPoolSize)
: ethers.BigNumber.from("0")
}
apy={
pool && pool.estimatedApy
? `${Number(pool.estimatedApy) * 100}`
: "0"
}
projectedApr={
pool && pool.projectedApr
? `${Number(pool.projectedApr) * 100}`
: "0"
}
position={
userPosition
? ethers.BigNumber.from(userPosition.positionValue)
: ethers.BigNumber.from("0")
}
feesEarned={
userPosition
? max(ethers.BigNumber.from(userPosition.feesEarned), 0)
: ethers.BigNumber.from("0")
}
totalPosition={
userPosition
? ethers.BigNumber.from(userPosition.positionValue)
: ethers.BigNumber.from("0")
}
lpTokens={
userPosition
? ethers.BigNumber.from(userPosition.lpTokens)
: ethers.BigNumber.from("0")
}
bridgeAddress={token.bridgePool}
ethBalance={
account
? // Very odd key assigned to these values.
queries[`ethBalance({"account":"${account}","chainId":1})`]
: null
}
erc20Balances={
account
? queries[`balances({"account":"${account}","chainId":1})`]
: null
}
setShowSuccess={setShowSuccess}
setDepositUrl={setDepositUrl}
balance={balance.toString()}
refetchBalance={refetchBalance}
defaultTab={defaultTab}
setDefaultTab={setDefaultTab}
utilization={
pool && pool.liquidityUtilizationCurrent
? pool.liquidityUtilizationCurrent
: "0"
}
/>
) : (
<LoadingWrapper>
<LoadingInfo>
<LoadingLogo src={token.logoURI} />
<InfoText>{token.symbol} Pool</InfoText>
<BouncingDotsLoader type={"big" as BounceType} />
</LoadingInfo>
<LoadingPositionWrapper />
<BigLoadingPositionWrapper />
</LoadingWrapper>
)}
</Wrapper>
) : (
<DepositSuccess
depositUrl={depositUrl}
setShowSuccess={setShowSuccess}
showSuccess={showSuccess}
setDepositUrl={setDepositUrl}
/>
)}
</Layout>
);
}