Skip to content

Commit

Permalink
Merge pull request #60 from Web3Auth/feat/embed-complete-logout
Browse files Browse the repository at this point in the history
Feat/embed complete logout
  • Loading branch information
himanshuchawla009 authored Sep 14, 2024
2 parents c1d1410 + 3918915 commit 44c8edf
Show file tree
Hide file tree
Showing 12 changed files with 398 additions and 354 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"@types/node": "^16.18.98",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@web3auth/global-accounts-sdk": "file:web3auth-global-accounts-sdk-0.1.1-2.tgz",
"@web3auth/global-accounts-sdk": "file:web3auth-global-accounts-sdk-0.1.1-0.tgz",
"axios": "^1.7.2",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.1",
Expand Down
433 changes: 277 additions & 156 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

152 changes: 1 addition & 151 deletions src/app/home/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,112 +19,13 @@ import Home from "@/components/Home";

export default function HomePage() {
const [isLoading, setIsLoading] = useState(true);
const [mintSuccess, setMintSuccess] = useState(false);
const [nftSuccess, setNftSuccess] = useState(false);
// todo: change this before deployment or move it to env
const { walletProvider, address, selectedEnv } = useWallet();
const { address } = useWallet();

useEffect(() => {
setTimeout(() => setIsLoading(false), 4000);
}, []);

const [mintNftState, setMintNftState] = useState({
minting: false,
mintSuccess: false,
mintError: "",
mintRedirectUrl: "",
});

async function mintNft() {
try {
const data = encodeFunctionData({
abi: erc721Abi,
functionName: "mint",
args: [address],
});

const resp = await walletProvider?.request({
method: "eth_sendTransaction",
params: {
from: address,
to: nftContractAddress,
data,
value: "0",
},
});
if (resp) {
// setMintSuccess(true);
setMintNftState({
mintError: "",
minting: true,
mintSuccess: false,
mintRedirectUrl: `https://jiffyscan.xyz/userOpHash/${resp}`,
});
waitForMinting(resp);
}
return `${calculateBaseUrl(
selectedEnv
)}/wallet/nft/${nftContractAddress}`;
} catch (e: unknown) {
console.error("error minting nft", e);
throw e;
} finally {
}
}

async function waitForMinting(hash: Hex) {
const bundlerClient = createClient({
chain: polygonAmoy,
transport: http(
"https://rpc.zerodev.app/api/v2/bundler/779a8e75-8332-4e4f-b6e5-acfec9f777d9"
),
}).extend(bundlerActions(ENTRYPOINT_ADDRESS_V07));

// wait for user op hash to be completed
const userOperationByHash = await bundlerClient.waitForUserOperationReceipt(
{
hash,
timeout: 1000 * 60 * 3,
pollingInterval: 1000 * 3,
}
);
if (userOperationByHash.receipt) {
setMintNftState({
mintError: "",
minting: false,
mintSuccess: true,
mintRedirectUrl: mintNftState.mintRedirectUrl,
});
setNftSuccess(true);
}
}

async function importAccount(randWallet: IRandomWallet) {
try {
if (address) {
const { privateKey, publicKey, keyType } = randWallet;
let sessionId = OpenloginSessionManager.generateRandomSessionKey();
const sessionMgr = new OpenloginSessionManager({ sessionId });
sessionId = await sessionMgr.createSession({
privateKey,
publicKey,
keyType,
});

const response = await walletProvider?.request({
method: "wallet_importW3aSession",
params: {
sessionId,
},
});
console.log("Response", response);
}
} catch (e: unknown) {
console.error("error importing account", e);
throw e;
}
}

return (
<main className="flex flex-col">
<>
Expand Down Expand Up @@ -178,57 +79,6 @@ export default function HomePage() {
) : (
<>
<Home address={address} />

{/* <section className="md:h-dvh flex-grow flex flex-col items-center justify-center relative z-1 bg-darkCard py-11 px-9 pb-20 w-full">
<Image
src={"/images/cross-chain-gradient.png"}
alt="cross chain"
width={400}
height={400}
className="z-0 w-full h-full opacity-50 absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2"
/>
<div className="flex flex-col items-center justify-center text-center">
<Button cursorClassName="cursor-default" title="Demo"></Button>
<NonImportFlow
mintState={mintNftState}
handleMintNft={mintNft}
address={address}
selectedEnv={selectedEnv}
/>
</div>
</section>
<section className="flex-grow p-10 md:py-32 md:px-20 text-center w-full">
<p className="gradient-text text-3xl md:text-5xl font-bold md:w-[80%]">
Keeping track of multiple chains can be overwhelming. Let us
make it easier for you.
</p>
</section>
<section className="md:h-dvh flex-grow flex flex-col items-center justify-center relative z-1 bg-darkCard py-11 px-9 pb-20">
<Image
src={"/images/cross-chain-gradient.png"}
alt="cross chain"
width={400}
height={400}
className="z-0 w-full h-full opacity-50 absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2"
/>
<div className="flex flex-col items-center justify-center text-center w-full">
<Button cursorClassName="cursor-default" title="Demo"></Button>
<ImportFlow
handleImportAccount={importAccount}
handleMintNft={mintNft}
selectedEnv={selectedEnv}
mintState={mintNftState}
/>
</div>
</section>
<Footer />
<Modal isOpen={mintSuccess} onClose={() => setMintSuccess(false)}>
<MintSuccess />
</Modal> */}
</>
)}
</>
Expand Down
24 changes: 15 additions & 9 deletions src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ import { parseSdkError } from "@/utils/utils";

export default function Home() {
const router = useRouter();
const { setAddress, walletProvider, setLoggedIn, showNextLoginModal, setShowNextLoginModal } = useWallet();

const [isLoading, setIsLoading] = useState(false);
const { setAddress, walletProvider, setLoggedIn, loggedIn } = useWallet();
// error message
const [errorText, setErrorText] = useState("");
const [subErrorText, setSubErrorText] = useState("");
Expand All @@ -23,14 +23,11 @@ export default function Home() {
>(() => Promise.resolve());
const [displayErrorPopup, setDisplayErrorPopup] = useState(false);

async function loginOrRegister() {
async function loginOrRegister(loginParams?: { showLoggedOutModal?: boolean }) {
setIsLoading(true);
setDisplayErrorPopup(false);
try {
const response = await walletProvider?.request({
method: "eth_requestAccounts",
params: [],
});
const response = await walletProvider?.connect(loginParams);
const loggedInAddress = (response as string[])[0];
setAddress(loggedInAddress);
setLoggedIn(walletProvider?.connected || false);
Expand All @@ -54,15 +51,24 @@ export default function Home() {
}

useEffect(() => {
if (walletProvider?.connected && loggedIn) {
if (walletProvider?.connected) {
router.push("/home");
}
}, [walletProvider, loggedIn, router]);
}, [walletProvider, router]);

useEffect(() => {
if (showNextLoginModal) {
setShowNextLoginModal(false);
(async () => {
await loginOrRegister({ showLoggedOutModal: showNextLoginModal });
})()
}
}, [showNextLoginModal]);

return (
<main className="flex flex-col">
<Navbar address={""} showButton={false} />
<Web3Pay actionButtonText="Create Testnet Web3Pay Account" onActionButtonClick={loginOrRegister} isLoading={isLoading} />
<Web3Pay actionButtonText="Create Testnet Web3Pay Account" onActionButtonClick={() => loginOrRegister()} isLoading={isLoading} />

<Modal
isOpen={displayErrorPopup}
Expand Down
7 changes: 1 addition & 6 deletions src/components/ConnectStep.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,7 @@ const ConnectStep = ({
displayName: "Test Wallet",
});

const response = await walletProvider?.request({
method: "wallet_importW3aSession",
params: {
sessionId,
},
});
const response = await walletProvider?.importExternalWallet(sessionId);
console.log("Response", response);
setCompletedSteps([...completedSteps, "connect"]);

Expand Down
2 changes: 1 addition & 1 deletion src/components/CrossMintingStep.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ const CrossMintingStep = ({
args: [web3PayAddress],
});

const resp = await walletProvider?.request({
const resp = await walletProvider?.request<`0x${string}`>({
method: "eth_sendTransaction",
params: {
from: web3PayAddress,
Expand Down
3 changes: 2 additions & 1 deletion src/components/Home.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import Navbar from "./ui/Navbar";
import CrossMintingStep from "./CrossMintingStep";
import ConnectStep from "./ConnectStep";
import { IRandomWallet } from "@/utils/interfaces";
import useMintStore, { MINT_STEPS, STEPS } from "@/lib/store/mint";
import useMintStore, { STEPS } from "@/lib/store/mint";
import Button from "./ui/Button";

const Home = ({ address }: { address: string }) => {
Expand All @@ -19,6 +19,7 @@ const Home = ({ address }: { address: string }) => {
setRandomWallet(randomWallet);
setActiveStep(STEPS.CROSS_CHAIN_MINTING);
};

return (
<>
<Navbar
Expand Down
44 changes: 44 additions & 0 deletions src/components/LogoutPopup.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { useWallet } from "@/context/walletContext";
import useMintStore from "@/lib/store/mint";
import { HiExclamationCircle } from "react-icons/hi";
import { text } from "stream/consumers";

const LogoutPopup = ({ onCancel }: {
onCancel: () => void;
}) => {
const { resetMintState } = useMintStore();
const { walletProvider } = useWallet();

const handleLogout = async () => {
resetMintState();
await walletProvider?.disconnect();
};

return (
<div className="w-full flex flex-col gap-y-4 items-center justify-center">
<div className="text-center">
<p className="text-lg font-medium text-white">Confirm Logout</p>
<p className="text-sm font-normal text-gray-300 text-center mt-1 mx-auto">
You will be logged out of your application and returned to the login
screen.
</p>
</div>
<div className="flex justify-center items-center grow gap-2 w-full px-5 py-3">
<button
className="w-1/2 py-2 rounded-full cursor-pointer border border-gray-300 text-white text-base font-medium leading-normal"
onClick={onCancel}
>
Cancel
</button>
<button
className="w-1/2 py-2 bg-blue-600 rounded-full cursor-pointer border border-blue-700 text-white text-base font-medium leading-normal hover:bg-blue-700"
onClick={handleLogout}
>
Logout
</button>
</div>
</div>
);
};

export default LogoutPopup;
29 changes: 15 additions & 14 deletions src/components/ui/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import Image from "next/image";
import Button from "./Button";
import { copyToClipBoard, openInNewTab, sliceAddress } from "@/utils";
import { TbCopy, TbCircleCheck, TbLogout, TbWallet } from "react-icons/tb";
import { useWallet } from "@/context/walletContext";
import { cn } from "@/utils/utils";
import useMintStore from "@/lib/store/mint";
import { useRouter } from "next/navigation";
import { Modal } from "./Modal";
import LogoutPopup from "../LogoutPopup";

const Navbar = ({
address,
Expand All @@ -27,8 +27,7 @@ const Navbar = ({
const [copied, setCopied] = useState(false);
const [showMenu, setShowMenu] = useState(false);
const [scrollPosition, setScrollPosition] = useState(0);
const { resetMintState } = useMintStore()
const { setAddress, setLoggedIn, setWalletProvider } = useWallet();
const [showLogoutModal, setShowLogoutModal] = useState<boolean>(false);

const handleCopy = () => {
setCopied(true);
Expand All @@ -39,15 +38,6 @@ const Navbar = ({
}, 2000);
};

const handleLogout = () => {
resetMintState();
setShowMenu(false);
setAddress("");
setWalletProvider(null);
localStorage.clear();
setLoggedIn(false);
};

const handleAddressExplorer = () => {
openInNewTab(`https://amoy.polygonscan.com/address/${address}`);
};
Expand Down Expand Up @@ -144,14 +134,25 @@ const Navbar = ({
</button>
<button
className="appearance-none flex items-center gap-x-2 px-4 py-3 w-full"
onClick={handleLogout}
onClick={() => {
setShowMenu(false);
setShowLogoutModal(true);
}}
>
<TbLogout className="text-red-400 text-xl" />
<p className="text-red-400 text-sm font-normal">Log out</p>
</button>
</div>
</div>
) : null}
<Modal
isOpen={showLogoutModal}
onClose={() => setShowLogoutModal(false)}
>
<LogoutPopup onCancel={() => {
setShowLogoutModal(false);
}} />
</Modal>
</div>
);
};
Expand Down
Loading

0 comments on commit 44c8edf

Please sign in to comment.