utils#onboard TypeScript Examples
The following examples show how to use
utils#onboard.
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: Wallet.tsx From frontend-v1 with GNU Affero General Public License v3.0 | 5 votes |
{ init, reset } = onboard
Example #2
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 #3
Source File: AddLiquidityForm.tsx From frontend-v1 with GNU Affero General Public License v3.0 | 4 votes |
AddLiquidityForm: FC<Props> = ({
error,
amount,
onChange,
bridgeAddress,
decimals,
symbol,
tokenAddress,
setShowSuccess,
setDepositUrl,
balance,
setAmount,
wrongNetwork,
formError,
onMaxClick,
}) => {
const { addError } = useContext(ErrorContext);
const { init } = onboard;
const { isConnected, provider, signer, notify, account } = useConnection();
const { approve, allowance: getAllowance } = useERC20(tokenAddress);
const [allowance, setAllowance] = useState("0");
const [userNeedsToApprove, setUserNeedsToApprove] = useState(false);
const [txSubmitted, setTxSubmitted] = useState(false);
const [updateEthBalance] = api.endpoints.ethBalance.useLazyQuery();
const updateAllowance = useCallback(async () => {
if (!account || !provider || symbol === "ETH") return;
const allowance = await getAllowance({
account,
spender: bridgeAddress,
provider,
});
setAllowance(allowance.toString());
}, [setAllowance, getAllowance, provider, account, bridgeAddress, symbol]);
// trigger update allowance, only if bridge/token changes. ignore eth.
useEffect(() => {
if (isConnected && symbol !== "ETH" && !wrongNetwork) updateAllowance();
}, [isConnected, symbol, updateAllowance, wrongNetwork]);
// check if user needs to approve based on amount entered in form or a change in allowance
useEffect(() => {
try {
if (symbol === "ETH") {
setUserNeedsToApprove(false);
} else {
const weiAmount = toWeiSafe(amount, decimals);
const hasToApprove = weiAmount.gt(allowance);
setUserNeedsToApprove(hasToApprove);
}
} catch (err) {
// do nothing. this happens when users input is not a number and causes toWei to throw. if we dont
// catch here, app will crash when user enters something like "0."
}
}, [amount, allowance, symbol, decimals]);
const handleApprove = async () => {
try {
const tx = await approve({
amount: INFINITE_APPROVAL_AMOUNT,
spender: bridgeAddress,
signer,
});
if (tx) {
setTxSubmitted(true);
const { emitter } = notify.hash(tx.hash);
emitter.on("all", addEtherscan);
emitter.on("txConfirmed", () => {
notify.unsubscribe(tx.hash);
if (account) {
setTimeout(() => {
// these need to be delayed, because our providers need time to catch up with notifyjs.
// If we don't wait then these calls will fail to update correctly, leaving the user to have to refresh.
setTxSubmitted(false);
updateAllowance().catch((err) =>
console.error("Error checking approval:", err)
);
updateEthBalance({ chainId: 1, account });
}, 15000);
}
});
emitter.on("txFailed", () => {
notify.unsubscribe(tx.hash);
setTxSubmitted(false);
});
}
} catch (err: any) {
addError(new Error(`Error in approve call: ${err.message}`));
console.error(err);
}
};
const approveOrPoolTransactionHandler = async () => {
if (!provider) {
return init();
}
if (isConnected && userNeedsToApprove) return handleApprove();
if (isConnected && migrationPoolV2Warning) return false;
if (isConnected && Number(amount) > 0 && signer) {
const weiAmount = toWeiSafe(amount, decimals);
try {
let txId;
if (symbol === "ETH") {
txId = await poolClient.addEthLiquidity(
signer,
bridgeAddress,
weiAmount
);
} else {
txId = await poolClient.addTokenLiquidity(
signer,
bridgeAddress,
weiAmount
);
}
const transaction = poolClient.getTx(txId);
if (transaction.hash) {
setTxSubmitted(true);
const { emitter } = notify.hash(transaction.hash);
emitter.on("all", addEtherscan);
emitter.on("txConfirmed", (tx) => {
if (transaction.hash) notify.unsubscribe(transaction.hash);
setShowSuccess("deposit");
setTxSubmitted(false);
const url = `https://etherscan.io/tx/${transaction.hash}`;
setDepositUrl(url);
if (account)
setTimeout(
() => updateEthBalance({ chainId: 1, account }),
15000
);
});
emitter.on("txFailed", () => {
if (transaction.hash) notify.unsubscribe(transaction.hash);
setTxSubmitted(false);
});
}
return transaction;
} catch (err: any) {
addError(new Error(`Error in add liquidity call: ${err.message}`));
console.error("err in AddEthLiquidity call", err);
}
}
};
function buttonMessage() {
if (!isConnected) return "Connect wallet";
if (userNeedsToApprove) return "Approve";
return "Add Liquidity";
}
return (
<>
<FormHeader>Amount</FormHeader>
<InputGroup>
<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={onMaxClick} disabled={!isConnected}>
max
</MaxButton>
<Input
placeholder="0.00"
id="amount"
value={amount}
onChange={(e) => onChange(e.target.value)}
disabled={!isConnected}
/>
</RoundBox>
</InputGroup>
{isConnected && (
<Balance>
<span>
Balance: {ethers.utils.formatUnits(balance, decimals)} {symbol}
</span>
</Balance>
)}
{formError && <LiquidityErrorBox>{formError}</LiquidityErrorBox>}
{wrongNetwork && provider ? (
<FormButton onClick={() => switchChain(provider, DEFAULT_TO_CHAIN_ID)}>
Switch to {CHAINS[DEFAULT_TO_CHAIN_ID].name}
</FormButton>
) : (
<FormButton
disabled={
(!provider ||
!!formError ||
Number(amount) <= 0 ||
!!migrationPoolV2Warning) &&
isConnected
}
onClick={() => {
// Block adding liqudiity in app if REACT_APP_BLOCK_POOL_LIQUIDITY is true
if (blockLiquidity) return false;
return approveOrPoolTransactionHandler().catch((err) =>
console.error("Error on click to approve or pool tx", err)
);
}}
>
{buttonMessage()}
{txSubmitted ? <BouncingDotsLoader /> : null}
</FormButton>
)}
</>
);
}
Example #4
Source File: RemoveLiquidityForm.tsx From frontend-v1 with GNU Affero General Public License v3.0 | 4 votes |
RemoveLiqudityForm: FC<Props> = ({
removeAmount,
setRemoveAmount,
bridgeAddress,
lpTokens,
decimals,
symbol,
setShowSuccess,
setDepositUrl,
position,
feesEarned,
wrongNetwork,
totalPosition,
}) => {
const { init } = onboard;
const { isConnected, provider, signer, notify, account } = useConnection();
const [txSubmitted, setTxSubmitted] = useState(false);
const [updateEthBalance] = api.endpoints.ethBalance.useLazyQuery();
function buttonMessage() {
if (!isConnected) return "Connect wallet";
if (wrongNetwork) return "Switch to Ethereum Mainnet";
return "Remove liquidity";
}
const [errorMessage, setErrorMessage] = useState("");
useEffect(() => {
setErrorMessage("");
}, [removeAmount]);
const handleButtonClick = async () => {
if (!provider) {
init();
}
if (isConnected && removeAmount > 0 && signer) {
setErrorMessage("");
const scaler = toBN("10").pow(decimals);
const removeAmountToWei = toWeiSafe(
(removeAmount / 100).toString(),
decimals
);
const weiAmount = lpTokens.mul(removeAmountToWei).div(scaler);
try {
let txId;
if (symbol === "ETH") {
txId = await poolClient.removeEthliquidity(
signer,
bridgeAddress,
weiAmount
);
} else {
txId = await poolClient.removeTokenLiquidity(
signer,
bridgeAddress,
weiAmount
);
}
const transaction = poolClient.getTx(txId);
if (transaction.hash) {
setTxSubmitted(true);
const { emitter } = notify.hash(transaction.hash);
emitter.on("all", addEtherscan);
emitter.on("txConfirmed", (tx) => {
if (transaction.hash) notify.unsubscribe(transaction.hash);
const url = `https://etherscan.io/tx/${transaction.hash}`;
setShowSuccess("withdraw");
setDepositUrl(url);
setTxSubmitted(false);
if (account)
setTimeout(
() => updateEthBalance({ chainId: 1, account }),
15000
);
});
emitter.on("txFailed", () => {
if (transaction.hash) notify.unsubscribe(transaction.hash);
setTxSubmitted(false);
});
}
return transaction;
} catch (err: any) {
setErrorMessage(err.message);
console.error("err in RemoveLiquidity call", err);
}
}
};
const preview = isConnected
? previewRemoval(
{
totalDeposited: position,
feesEarned: max(feesEarned, 0),
positionValue: totalPosition,
},
removeAmount / 100
)
: null;
return (
<>
<RemoveAmount>
Amount: <span>{removeAmount}%</span>
</RemoveAmount>
<PoolFormSlider value={removeAmount} setValue={setRemoveAmount} />
<RemovePercentButtonsWrapper>
<RemovePercentButton onClick={() => setRemoveAmount(25)}>
25%
</RemovePercentButton>
<RemovePercentButton onClick={() => setRemoveAmount(50)}>
50%
</RemovePercentButton>
<RemovePercentButton onClick={() => setRemoveAmount(75)}>
75%
</RemovePercentButton>
<RemovePercentButton onClick={() => setRemoveAmount(100)}>
MAX
</RemovePercentButton>
</RemovePercentButtonsWrapper>
{isConnected && (
<>
<FeesBlockWrapper>
<FeesBlock>
<FeesBoldInfo>
Remove amount <FeesPercent>({removeAmount}%)</FeesPercent>
</FeesBoldInfo>
<FeesInfo>Left in pool</FeesInfo>
</FeesBlock>
<FeesBlock>
<FeesValues>
{preview && formatUnits(preview.position.recieve, decimals)}{" "}
{symbol}
</FeesValues>
<FeesValues>
{preview && formatUnits(preview.position.remain, decimals)}{" "}
{symbol}
</FeesValues>
</FeesBlock>
</FeesBlockWrapper>
<FeesBlockWrapper>
<FeesBlock>
<FeesBoldInfo>Fees claimed</FeesBoldInfo>
<FeesInfo>Left in pool</FeesInfo>
</FeesBlock>
<FeesBlock>
<FeesValues>
{preview && formatUnits(preview.fees.recieve, decimals)}{" "}
{symbol}
</FeesValues>
<FeesValues>
{preview && formatUnits(preview.fees.remain, decimals)} {symbol}
</FeesValues>
</FeesBlock>
</FeesBlockWrapper>
<FeesBlockWrapper>
<FeesBlock>
<FeesBoldInfo>You will receive</FeesBoldInfo>
</FeesBlock>
<FeesBlock>
<FeesValues>
{preview && formatUnits(preview.total.recieve, decimals)}{" "}
{symbol}
</FeesValues>
</FeesBlock>
</FeesBlockWrapper>
</>
)}
<RemoveFormButtonWrapper>
{errorMessage && (
<RemoveFormErrorBox>
<div>{errorMessage}</div>
</RemoveFormErrorBox>
)}
{wrongNetwork && provider ? (
<RemoveFormButton
onClick={() => switchChain(provider, DEFAULT_TO_CHAIN_ID)}
>
Switch to {CHAINS[DEFAULT_TO_CHAIN_ID].name}
</RemoveFormButton>
) : (
<RemoveFormButton
onClick={handleButtonClick}
disabled={wrongNetwork && !provider}
>
{buttonMessage()}
{txSubmitted ? <BouncingDotsLoader /> : null}
</RemoveFormButton>
)}
</RemoveFormButtonWrapper>
</>
);
}