Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

consolidates useIsValidAddress #3361

Merged
merged 1 commit into from
Mar 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import {
TextInput,
UserIcon,
} from "@coral-xyz/react-common";
import type { TokenDataWithPrice } from "@coral-xyz/recoil";
import {
blockchainTokenData,
useActiveEthereumWallet,
Expand All @@ -21,6 +20,7 @@ import {
useAnchorContext,
useAvatarUrl,
useEthereumCtx,
useIsValidAddress,
useLoader,
useUser,
} from "@coral-xyz/recoil";
Expand All @@ -36,8 +36,6 @@ import {
useNavigation as useNavigationEphemeral,
} from "../../../common/Layout/NavStack";

import { useIsValidAddress } from "./Send";

let debouncedTimer = 0;

export interface SendData {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
/* eslint-disable react-hooks/exhaustive-deps */
import React, { type ChangeEvent, useEffect, useState } from "react";
import { StyleSheet, View } from "react-native";
import {
getHashedName,
getNameAccountKey,
NameRegistryState,
} from "@bonfida/spl-name-service";
import {
Blockchain,
ETH_NATIVE_MINT,
Expand Down Expand Up @@ -38,14 +32,12 @@ import {
useDarkMode,
useEthereumCtx,
useFriendship,
useIsValidAddress,
useLoader,
useUser,
} from "@coral-xyz/recoil";
import { styles as makeStyles, useCustomTheme } from "@coral-xyz/themes";
import { Typography } from "@mui/material";
import { TldParser } from "@onsol/tldparser";
import type { Connection } from "@solana/web3.js";
import { PublicKey, SystemProgram } from "@solana/web3.js";
import { BigNumber, ethers } from "ethers";

import { ApproveTransactionDrawer } from "../../../common/ApproveTransactionDrawer";
Expand Down Expand Up @@ -194,7 +186,7 @@ export function Send({
return () => {
nav.setOptions({ headerTitle: prev });
};
}, []);
}, []); // eslint-disable-line

const {
isValidAddress,
Expand Down Expand Up @@ -228,7 +220,7 @@ export function Send({
)
);
}
}, [blockchain, token]);
}, [blockchain, token]); // eslint-disable-line

const amountSubFee = BigNumber.from(token!.nativeBalance).sub(feeOffset);
const maxAmount = amountSubFee.gt(0) ? amountSubFee : BigNumber.from(0);
Expand Down Expand Up @@ -794,145 +786,3 @@ export function Error({
</div>
);
}

// TODO(peter) share between extension/mobile
export function useIsValidAddress(
blockchain: Blockchain,
address: string,
solanaConnection?: Connection,
ethereumProvider?: ethers.providers.Provider
) {
const [addressError, setAddressError] = useState<boolean>(false);
const [isFreshAccount, setIsFreshAccount] = useState<boolean>(false); // Not used for now.
const [accountValidated, setAccountValidated] = useState<boolean>(false);
const [normalizedAddress, setNormalizedAddress] = useState<string>(address);

// This effect validates the account address given.
useEffect(() => {
if (accountValidated) {
setAccountValidated(false);
}
if (address === "") {
setAccountValidated(false);
setAddressError(false);
return;
}
(async () => {
if (blockchain === Blockchain.SOLANA) {
let pubkey;

if (!solanaConnection) {
return;
}

// SNS Domain
if (address.endsWith(".sol")) {
try {
const hashedName = await getHashedName(address.replace(".sol", ""));
const nameAccountKey = await getNameAccountKey(
hashedName,
undefined,
new PublicKey("58PwtjSDuFHuUkYjH9BYnnQKHfwo9reZhC2zMJv9JPkx") // SOL TLD Authority
);

const owner = await NameRegistryState.retrieve(
solanaConnection,
nameAccountKey
);

pubkey = owner.registry.owner;
} catch (e) {
setAddressError(true);
return;
}
}

// ANS by ONSOL
if (!pubkey && address.split(".").length === 2) {
try {
// address would be e.g. miester.poor
const parser = new TldParser(solanaConnection);
const owner = await parser.getOwnerFromDomainTld(address);
if (!owner) {
setAddressError(true);
// Not a valid domain don't bother continuing since it has a dot in it.
return;
}
pubkey = owner;
} catch (e) {
setAddressError(true);
return;
}
}

if (!pubkey) {
// Solana address validation
try {
pubkey = new PublicKey(address);
} catch (err) {
setAddressError(true);
// Not valid address so don't bother validating it.
return;
}
}

const account = await solanaConnection?.getAccountInfo(pubkey);

// Null data means the account has no lamports. This is valid.
if (!account) {
setIsFreshAccount(true);
setAccountValidated(true);
setNormalizedAddress(pubkey.toString());
return;
}

// Only allow system program accounts to be given. ATAs only!
if (!account.owner.equals(SystemProgram.programId)) {
setAddressError(true);
return;
}

// The account data has been successfully validated.
setAddressError(false);
setAccountValidated(true);
setNormalizedAddress(pubkey.toString());
} else if (blockchain === Blockchain.ETHEREUM) {
// Ethereum address validation
let checksumAddress;

if (!ethereumProvider) {
return;
}

if (address.includes(".eth")) {
try {
checksumAddress = await ethereumProvider?.resolveName(address);
} catch (e) {
setAddressError(true);
return;
}
}

if (!checksumAddress) {
try {
checksumAddress = ethers.utils.getAddress(address);
} catch (e) {
setAddressError(true);
return;
}
}

setAddressError(false);
setAccountValidated(true);
setNormalizedAddress(checksumAddress);
}
})();
}, [address]);

return {
isValidAddress: accountValidated,
isFreshAddress: isFreshAccount,
isErrorAddress: addressError,
normalizedAddress: normalizedAddress,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import {
PrimaryButton,
ProxyImage,
SecondaryButton,
TextInput,
} from "@coral-xyz/react-common";
import {
appStoreMetaTags,
Expand All @@ -36,13 +35,14 @@ import {
useDecodedSearchParams,
useEthereumCtx,
useEthereumExplorer,
useIsValidAddress,
useNavigation,
useOpenPlugin,
useSolanaCtx,
useSolanaExplorer,
useUser,
} from "@coral-xyz/recoil";
import { styles, useCustomTheme } from "@coral-xyz/themes";
import { useCustomTheme } from "@coral-xyz/themes";
import { Whatshot } from "@mui/icons-material";
import MoreHorizIcon from "@mui/icons-material/MoreHoriz";
import { Button, IconButton, Typography } from "@mui/material";
Expand Down Expand Up @@ -73,7 +73,6 @@ import { SendEthereumConfirmationCard } from "../Balances/TokensWidget/Ethereum"
import {
Error as ErrorConfirmation,
Sending,
useIsValidAddress,
useStyles,
} from "../Balances/TokensWidget/Send";
import { SendSolanaConfirmationCard } from "../Balances/TokensWidget/Solana";
Expand Down
1 change: 0 additions & 1 deletion packages/app-mobile/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { Blockchain } from "@coral-xyz/common";
import Images from "../Images";

export { useIsONELive } from "./useIsONELive";
export { useIsValidAddress } from "./useIsValidAddress";
export { useTheme } from "./useTheme";

// TODO(peter) consolidate between extension/mobile-app or just live on S3
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,7 @@ const Stack = createStackNavigator<NftStackParamList>();
export function NftCollectiblesNavigator(): JSX.Element {
return (
<Stack.Navigator initialRouteName="NftCollectionList">
<Stack.Group
screenOptions={{ headerShown: true, headerBackTitleVisible: false }}
>
<Stack.Group screenOptions={{ headerShown: false }}>
<Stack.Screen
name="NftCollectionList"
component={NftCollectionListScreen}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
useLoader,
useSolanaCtx,
nftById,
useIsValidAddress
} from "@coral-xyz/recoil";
import { useActionSheet } from "@expo/react-native-action-sheet";
import { PublicKey } from "@solana/web3.js";
Expand Down
7 changes: 5 additions & 2 deletions packages/app-mobile/src/screens/Unlocked/SendTokenScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,11 @@ import {
toDisplayBalance,
NATIVE_ACCOUNT_RENT_EXEMPTION_LAMPORTS,
} from "@coral-xyz/common";
import { useAnchorContext, useEthereumCtx } from "@coral-xyz/recoil";
import {
useAnchorContext,
useEthereumCtx,
useIsValidAddress,
} from "@coral-xyz/recoil";
import {
PrimaryButton,
DangerButton,
Expand All @@ -36,7 +40,6 @@ import { BottomSheetModal } from "~components/BottomSheetModal";
import { ImageSvg } from "~components/ImageSvg";
import { UnstyledTokenTextInput } from "~components/TokenInputField";
import { Screen } from "~components/index";
import { useIsValidAddress } from "~hooks/useIsValidAddress";
import { useTheme as useCustomTheme } from "~hooks/useTheme";
import type { UnlockedNavigatorStackParamList } from "~navigation/UnlockedNavigator";

Expand Down
1 change: 1 addition & 0 deletions packages/recoil/src/hooks/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export * from "./useBlockchain";
export * from "./useBreakpoints";
export * from "./useFeatureGates";
export * from "./useFriendship";
export * from "./useIsValidAddress";
export * from "./useLoader";
export * from "./usePriceData";
export * from "./usePrimaryWallets";
Expand Down
Loading