Skip to content

Commit

Permalink
fix (dis)connection errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Jennievon committed Dec 6, 2023
1 parent 5c72f5b commit f0a2ca8
Show file tree
Hide file tree
Showing 11 changed files with 214 additions and 150 deletions.
25 changes: 14 additions & 11 deletions tools/walletextension/frontend/src/api/ethRequests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export const getSignature = async (account: string, data: any) => {
});
};

export const getUserID = async (provider: ethers.providers.Web3Provider) => {
export const getToken = async (provider: ethers.providers.Web3Provider) => {
if (!provider) {
showToast(
ToastType.DESTRUCTIVE,
Expand All @@ -88,12 +88,12 @@ export const getUserID = async (provider: ethers.providers.Web3Provider) => {

try {
if (await isTenChain()) {
const id = await provider.send(requestMethods.getStorageAt, [
const token = await provider.send(requestMethods.getStorageAt, [
userStorageAddress,
getRandomIntAsString(0, 1000),
null,
]);
return id;
return token;
} else {
return null;
}
Expand Down Expand Up @@ -128,16 +128,18 @@ export async function addNetworkToMetaMask(rpcUrls: string[]) {
}

export async function authenticateAccountWithTenGatewayEIP712(
userID: string,
token: string,
account: string
): Promise<any> {
if (!userID) {
showToast(ToastType.INFO, "User ID is required to revoke accounts");
return;
if (!token) {
return showToast(
ToastType.INFO,
"Encryption token not found. Please try again later."
);
}

try {
const isAuthenticated = await accountIsAuthenticated(userID, account);
const isAuthenticated = await accountIsAuthenticated(token, account);
if (isAuthenticated.status) {
return {
status: true,
Expand All @@ -148,17 +150,18 @@ export async function authenticateAccountWithTenGatewayEIP712(
...typedData,
message: {
...typedData.message,
"Encryption Token": "0x" + userID,
"Encryption Token": "0x" + token,
},
};
const signature = await getSignature(account, data);

const auth = await authenticateUser(userID, {
const auth = await authenticateUser(token, {
signature,
address: account,
});
console.log("🚀 ~ file: ethRequests.ts:166 ~ auth:", auth);
return auth;
} catch (error) {
} catch (error: any) {
throw error;
}
}
14 changes: 7 additions & 7 deletions tools/walletextension/frontend/src/api/gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,21 @@ export async function fetchVersion(): Promise<string> {
}

export async function accountIsAuthenticated(
userID: string,
token: string,
account: string
): Promise<AuthenticationResponse> {
return await httpRequest<AuthenticationResponse>({
method: "get",
url: pathToUrl(apiRoutes.queryAccountUserID),
url: pathToUrl(apiRoutes.queryAccountToken),
searchParams: {
token: userID,
token,
a: account,
},
});
}

export const authenticateUser = async (
userID: string,
token: string,
authenticateFields: {
signature: string;
address: string;
Expand All @@ -36,17 +36,17 @@ export const authenticateUser = async (
url: pathToUrl(apiRoutes.authenticate),
data: authenticateFields,
searchParams: {
token: userID,
token,
},
});
};

export async function revokeAccountsApi(userID: string): Promise<string> {
export async function revokeAccountsApi(token: string): Promise<string> {
return await httpRequest<string>({
method: "get",
url: pathToUrl(apiRoutes.revoke),
searchParams: {
token: userID,
token,
},
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ const ConnectWalletButton = () => {
<>
<Link2Icon className="h-4 w-4 mr-1" />
Connect
<span className="hidden sm:inline">&nbsp;Account(s)</span>
</>
)}
</Button>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,8 @@ const Disconnected = () => {
<div className="space-y-4">
<p>
By connecting your wallet to Ten and signing the signature request
you will get a unique user id, which is also your{" "}
<b>viewing key</b>. It is contained in the RPC link and unique for
each user.
you will get a unique token, which is also your <b>viewing key</b>
. It is contained in the RPC link and unique for each user.
</p>
<Alert variant={"warning"} className="flex items-center space-x-2">
<Terminal className="h-4 w-4" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import {
import { ToastType } from "@/types/interfaces";
import {
authenticateAccountWithTenGatewayEIP712,
getUserID,
getToken,
} from "@/api/ethRequests";
import { ethers } from "ethers";
import ethService from "@/services/ethService";
Expand All @@ -37,7 +37,7 @@ export const WalletConnectionProvider = ({
children,
}: WalletConnectionProviderProps) => {
const [walletConnected, setWalletConnected] = useState(false);
const [userID, setUserID] = useState<string>("");
const [token, setToken] = useState<string>("");
const [version, setVersion] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [accounts, setAccounts] = useState<Account[] | null>(null);
Expand All @@ -57,75 +57,132 @@ export const WalletConnectionProvider = ({
if (!ethereum) {
return;
}
const status = await ethService.isUserConnectedToTenChain(userID);
const status = await ethService.isUserConnectedToTenChain(token);
await fetchUserAccounts();
setWalletConnected(status);
};

const initialize = async () => {
const providerInstance = new ethers.providers.Web3Provider(ethereum);
setProvider(providerInstance);
await ethService.checkIfMetamaskIsLoaded(providerInstance);
const id = await getUserID(providerInstance);
setUserID(id);
handleAccountsChanged();
const accounts = await ethService.getAccounts(providerInstance);
setAccounts(accounts || null);
setVersion(await fetchVersion());
setLoading(false);
if (!ethereum) {
showToast(
ToastType.DESTRUCTIVE,
"Please install Metamask to connect your wallet."
);
return;
}
try {
const providerInstance = new ethers.providers.Web3Provider(ethereum);
setProvider(providerInstance);
await ethService.checkIfMetamaskIsLoaded(providerInstance);

const fetchedToken = await getToken(providerInstance);
setToken(fetchedToken);
const status = await ethService.isUserConnectedToTenChain(fetchedToken);
setWalletConnected(status);

const accounts = await ethService.getAccounts(providerInstance);
setAccounts(accounts || null);
setVersion(await fetchVersion());
} catch (error) {
showToast(
ToastType.DESTRUCTIVE,
"Error initializing wallet connection. Please refresh the page."
);
} finally {
setLoading(false);
}
};

const connectAccount = async (account: string) => {
if (!userID) {
showToast(ToastType.INFO, "User ID is required to connect an account.");
return;
}
await authenticateAccountWithTenGatewayEIP712(userID, account);
const { status } = await accountIsAuthenticated(userID, account);
if (status) {
showToast(ToastType.SUCCESS, "Account authenticated!");
setAccounts((accounts) => {
if (!accounts) {
return null;
}
return accounts.map((acc) => {
if (acc.name === account) {
return {
...acc,
connected: status,
};
try {
if (!token) {
showToast(
ToastType.INFO,
"Encryption token is required to connect an account."
);
return;
}
await authenticateAccountWithTenGatewayEIP712(token, account);
const { status } = await accountIsAuthenticated(token, account);
if (status) {
showToast(ToastType.SUCCESS, "Account authenticated!");
setAccounts((accounts) => {
if (!accounts) {
return null;
}
return acc;
return accounts.map((acc) => {
if (acc.name === account) {
return {
...acc,
connected: status,
};
}
return acc;
});
});
});
} else {
} else {
showToast(ToastType.DESTRUCTIVE, "Account authentication failed.");
}
} catch (error) {
showToast(ToastType.DESTRUCTIVE, "Account authentication failed.");
}
};

const revokeAccounts = async () => {
if (!userID) {
showToast(ToastType.INFO, "User ID is required to revoke accounts");
if (!token) {
showToast(
ToastType.INFO,
"Encryption token is required to revoke accounts"
);
return;
}
const revokeResponse = await revokeAccountsApi(userID);
const revokeResponse = await revokeAccountsApi(token);
if (revokeResponse === ToastType.SUCCESS) {
showToast(ToastType.DESTRUCTIVE, "Accounts revoked!");
setAccounts(null);
setWalletConnected(false);
setUserID("");
setToken("");
}
};

const fetchUserAccounts = async () => {
const accounts = await ethService.getAccounts(provider);
setAccounts(accounts || null);
setWalletConnected(true);
if (!provider) {
showToast(
ToastType.INFO,
"Provider is required to fetch user accounts. Please connect your wallet."
);
return;
}

try {
const accounts = await ethService.getAccounts(provider);
const token = await getToken(provider);
setToken(token);
let updatedAccounts: Account[] = [];

updatedAccounts = await Promise.all(
accounts!.map(async (account) => {
await ethService.authenticateWithGateway(token, account.name);
const { status } = await accountIsAuthenticated(token, account.name);
return {
...account,
connected: status,
};
})
);
setAccounts(updatedAccounts || null);
} catch (error) {
showToast(ToastType.DESTRUCTIVE, "Error fetching user accounts.");
} finally {
setWalletConnected(true);
setLoading(false);
}
};

const walletConnectionContextValue: WalletConnectionContextType = {
walletConnected,
accounts,
userID,
token,
connectAccount,
version,
revokeAccounts,
Expand Down
2 changes: 1 addition & 1 deletion tools/walletextension/frontend/src/lib/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const testnetUrls = {
};

export const SWITCHED_CODE = 4902;
export const userIDHexLength = 40;
export const tokenHexLength = 40;

export const tenGatewayVersion = "v1";
export const tenChainIDDecimal = 443;
Expand Down
7 changes: 4 additions & 3 deletions tools/walletextension/frontend/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import {
tenChainIDHex,
tenGatewayAddress,
testnetUrls,
userIDHexLength,
tokenHexLength,
} from "./constants";

export function cn(...inputs: ClassValue[]) {
Expand All @@ -17,8 +17,8 @@ export function formatTimeAgo(unixTimestampSeconds: string) {
return formatDistanceToNow(date, { addSuffix: true });
}

export function isValidUserIDFormat(value: string) {
return typeof value === "string" && value.length === userIDHexLength;
export function isValidTokenFormat(value: string) {
return typeof value === "string" && value.length === tokenHexLength;
}

export function getRandomIntAsString(min: number, max: number) {
Expand All @@ -27,6 +27,7 @@ export function getRandomIntAsString(min: number, max: number) {
const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;
return randomInt.toString();
}

export function getNetworkName() {
switch (tenGatewayAddress) {
case testnetUrls.uat.url:
Expand Down
2 changes: 1 addition & 1 deletion tools/walletextension/frontend/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const NavLinks: NavLink[] = [];
export const apiRoutes = {
join: `/${tenGatewayVersion}/join/`,
authenticate: `/${tenGatewayVersion}/authenticate/`,
queryAccountUserID: `/${tenGatewayVersion}/query/`,
queryAccountToken: `/${tenGatewayVersion}/query/`,
revoke: `/${tenGatewayVersion}/revoke/`,
version: `/version/`,
};
Expand Down
Loading

0 comments on commit f0a2ca8

Please sign in to comment.