Skip to content

Commit

Permalink
1723 inconsistent display (passportxyz#1733)
Browse files Browse the repository at this point in the history
* fix(app): remove old log

* chore(app): handle signature errors that are thrown from ceramic login

* fix(app): instantiate session vars after wallet

* fix(app): fix build
  • Loading branch information
tim-schultz authored Oct 3, 2023
1 parent 32b3bfe commit 8a9b325
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 15 deletions.
1 change: 1 addition & 0 deletions app/__test-fixtures__/contextTestHelpers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export const makeTestUserContext = (initialState?: Partial<UserContextState>): U
dbAccessTokenStatus: "idle",
userWarning: undefined,
setUserWarning: jest.fn(),
setWalletConnectionError: jest.fn(),
...initialState,
};
};
Expand Down
17 changes: 17 additions & 0 deletions app/__tests__/pages/Home.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -100,4 +100,21 @@ describe("Welcome navigation", () => {
);
expect(navigate).toHaveBeenCalledWith("/welcome");
});
it("should show wallet connection error toast if error is encountered", async () => {
renderWithContext(
{
...mockUserContext,
wallet: {} as WalletState,
walletConnectionError: "error",
setWalletConnectionError: jest.fn(),
},
{ ...mockCeramicContext, passport: undefined },
<Router>
<Home />
</Router>
);
await waitFor(() => {
expect(screen.getByText("Connection Error"));
});
});
});
2 changes: 1 addition & 1 deletion app/components/ExpiredStampsPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ const ExpiredStampsList = ({ className }: StampsListProps) => {

export const ExpiredStampsPanel = ({ className }: { className: string }) => {
const { expiredProviders } = useContext(CeramicContext);
console.log("ExpiredStampsPanel", expiredProviders);

return (
<div
className={`flex flex-col items-center rounded border border-foreground-3 bg-gradient-to-b from-background to-background-2 text-xl text-foreground-2 ${className}`}
Expand Down
42 changes: 29 additions & 13 deletions app/context/userContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,8 @@ export interface UserContextState {
loggingIn: boolean;
userWarning?: UserWarning;
setUserWarning: (warning?: UserWarning) => void;
walletConnectionError?: string;
setWalletConnectionError: (error?: string) => void;
}

const startingState: UserContextState = {
Expand All @@ -69,6 +71,7 @@ const startingState: UserContextState = {
loggingIn: false,
userWarning: undefined,
setUserWarning: () => {},
setWalletConnectionError: () => {},
};

export const pillLocalStorage = (platform?: string): void => {
Expand Down Expand Up @@ -98,6 +101,7 @@ export const UserContextProvider = ({ children }: { children: any }) => {
const [loggingIn, setLoggingIn] = useState<boolean>(false);
const [dbAccessToken, setDbAccessToken] = useState<string | undefined>();
const [dbAccessTokenStatus, setDbAccessTokenStatus] = useState<DbAuthTokenStatus>("idle");
const [walletConnectionError, setWalletConnectionError] = useState<string | undefined>();

// clear all state
const clearState = (): void => {
Expand Down Expand Up @@ -194,6 +198,18 @@ export const UserContextProvider = ({ children }: { children: any }) => {
}
};

const handleConnectionError = async (sessionKey: string, dbCacheTokenKey: string, wallet: WalletState) => {
// disconnect wallet
await disconnect({
label: wallet.label || "",
});
// then clear local state
clearState();

window.localStorage.removeItem(sessionKey);
window.localStorage.removeItem(dbCacheTokenKey);
};

// Attempt to login to Ceramic (on mainnet only)
const passportLogin = async (): Promise<void> => {
// check that passportLogin isn't mid-way through
Expand All @@ -202,6 +218,10 @@ export const UserContextProvider = ({ children }: { children: any }) => {
const hasCorrectChainId = MULTICHAIN_ENABLED ? true : await ensureMainnet();
// mark that we're attempting to login
setLoggingIn(true);

let sessionKey = "";
let dbCacheTokenKey = "";

// with loaded chainId
if (hasCorrectChainId) {
// store in localstorage
Expand All @@ -210,18 +230,16 @@ export const UserContextProvider = ({ children }: { children: any }) => {
try {
const address = wallet.accounts[0].address;
const ethAuthProvider = new EthereumAuthProvider(wallet.provider, wallet.accounts[0].address.toLowerCase());

// Sessions will be serialized and stored in localhost
// The sessions are bound to an ETH address, this is why we use the address in the session key
const sessionKey = `didsession-${address}`;
const dbCacheTokenKey = `dbcache-token-${address}`;
sessionKey = `didsession-${address}`;
dbCacheTokenKey = `dbcache-token-${address}`;
const sessionStr = window.localStorage.getItem(sessionKey);

// @ts-ignore
// When sessionStr is null, this will create a new selfId. We want to avoid this, becasue we want to make sure
// that chainId 1 is in the did
let selfId = !!sessionStr ? await ceramicConnect(ethAuthProvider, sessionStr) : null;

if (
// @ts-ignore
!selfId ||
Expand Down Expand Up @@ -263,16 +281,12 @@ export const UserContextProvider = ({ children }: { children: any }) => {
// @ts-ignore
selfId?.client?.session?.expireInSecs < 3600
) {
// disconnect from the invalid chain
await disconnect({
label: wallet.label || "",
});
// then clear local state
clearState();

window.localStorage.removeItem(sessionKey);
window.localStorage.removeItem(dbCacheTokenKey);
await handleConnectionError(sessionKey, dbCacheTokenKey, wallet);
}
} catch (error) {
await handleConnectionError(sessionKey, dbCacheTokenKey, wallet);
setWalletConnectionError((error as Error).message);
datadogRum.addError(error);
} finally {
// mark that this login attempt is complete
setLoggingIn(false);
Expand Down Expand Up @@ -423,6 +437,8 @@ export const UserContextProvider = ({ children }: { children: any }) => {
loggingIn,
userWarning,
setUserWarning,
walletConnectionError,
setWalletConnectionError,
};

return <UserContext.Provider value={providerProps}>{children}</UserContext.Provider>;
Expand Down
24 changes: 23 additions & 1 deletion app/pages/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import HeaderContentFooterGrid from "../components/HeaderContentFooterGrid";
import SIWEButton from "../components/SIWEButton";
import { checkShowOnboard } from "../utils/helpers";
import BodyWrapper from "../components/BodyWrapper";
import { useToast } from "@chakra-ui/react";
import { DoneToastContent } from "../components/DoneToastContent";

const Footer = () => (
<>
Expand All @@ -23,7 +25,8 @@ const Footer = () => (
);

export default function Home() {
const { toggleConnection, wallet } = useContext(UserContext);
const { toggleConnection, wallet, walletConnectionError, setWalletConnectionError } = useContext(UserContext);
const toast = useToast();

const navigate = useNavigate();

Expand All @@ -38,6 +41,24 @@ export default function Home() {
}
}, [wallet]);

useEffect(() => {
if (walletConnectionError) {
toast({
duration: 6000,
isClosable: true,
render: (result: any) => (
<DoneToastContent
title={"Connection Error"}
body={walletConnectionError}
icon="../assets/verification-failed-bright.svg"
result={result}
/>
),
});
setWalletConnectionError(undefined);
}
}, [walletConnectionError]);

return (
<PageRoot useLegacyBackground={true} className="text-color-1">
<HeaderContentFooterGrid>
Expand All @@ -57,6 +78,7 @@ export default function Home() {
participate across the web3.
</div>
<SIWEButton data-testid="connectWalletButton" onClick={toggleConnection} className="mt-10" />
{walletConnectionError && <div>{walletConnectionError}</div>}
</div>
</PageWidthGrid>
</BodyWrapper>
Expand Down

0 comments on commit 8a9b325

Please sign in to comment.