Skip to content

Commit

Permalink
EPIC SUCCESS: web3auth connected to wagmi - login/register working - …
Browse files Browse the repository at this point in the history
…deploy contracts working - recieve address back
  • Loading branch information
Spencer-Sch committed Dec 8, 2023
1 parent 02094ca commit 8e275bb
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 125 deletions.
124 changes: 25 additions & 99 deletions packages/nextjs/components/dash-wind/features/user/Login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,14 @@ import { Address, createWalletClient, custom } from "viem";
import { polygonMumbai } from "viem/chains";
// import { Address, createWalletClient, custom } from "viem";
// import { polygonMumbai } from "viem/chains";
import { useContractRead } from "wagmi";
import { useAccount, useConnect, useContractRead } from "wagmi";
import {
setIsAdmin,
/*setIsAdmin,*/
setIsConnected,
} from "~~/auth/authSlice";
import { web3auth } from "~~/auth/web3auth";
import { MyState, useMyDispatch, useMySelector } from "~~/components/dash-wind/app/store";
import { useMyDispatch } from "~~/components/dash-wind/app/store";

//import { get } from "http";

Expand All @@ -34,12 +35,14 @@ function Login() {
// const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState("");
const [loginObj, setLoginObj] = useState(INITIAL_LOGIN_OBJ);
const { isConnected } = useMySelector((state: MyState) => state.auth);
// const { isConnected } = useMySelector((state: MyState) => state.auth);
const router = useRouter();
const dispatch = useMyDispatch();
//const userAddress = getAccounts();
// state to store user address once it is fetched
const [userAddress, setUserAddress] = useState<string | null>(null);
const { address: wagmiAddress, isConnected: wagmiIsConnected } = useAccount();
const { connect, connectors, error } = useConnect();

useEffect(() => {
async function fetchAddress() {
Expand Down Expand Up @@ -72,127 +75,50 @@ function Login() {
}) as { data: boolean | undefined };

console.log("is owner: ", isOwner);
console.log("user address contract read: ", [getAccounts()]);
console.log("wagmi account address: ", wagmiAddress);
console.log("wagmi account isConnected: ", wagmiIsConnected);

useEffect(() => {
if (typeof isOwner !== "undefined") {
// Ensure the value is not undefined
if (isOwner) {
// Redirect to owner's dashboard
router.push("/dapp/dashboard");
} else {
// Redirect to employee or general user dashboard
router.push("/dapp/dashboard");
}
}
}, [isOwner, router]);

/*-------------------------------------*/

/*-------------------------------------*/
// Kaz & Trevor
//
// const {
// data: isEmployee,
// // isError,
// // isLoading,
// } = useContractRead({
// address: process.env.NEXT_PUBLIC_PAYROLL_CONTRACT_ADDRESS,
// abi: payrollABI,
// functionName: "doesEmployeeExist",
// args: [
// /* problem: figure out how to getAccount() address here */
// userAddress
// ],
// chainId: Number(chainId),
// });
/*-------------------------------------*/

// // Web3Auth
// async function login() {
// if (isConnected) {
// // await determineIfAccountIsAdmin();
// // if (!isEmployee) {
// // //until the hook is working, this is going to prevent us from being directed to the dashboard
// // return;
// // }
// router.push("/dapp/dashboard");
// return;
// }

// try {
// await web3auth.connect();
// if (web3auth.connected) {
// dispatch(setIsConnected({ isConnected: true }));
// //const userAddress = await getAccounts(); // Retrieve user's address

// await determineIfAccountIsAdmin();
// if (!isEmployee) {
// // until the hook is working, this is going to prevent us from being directed to the dashboard
// return;
// }
// router.push("/dapp/dashboard");
// }
// } catch (error) {
// console.error(error);
// }
// }

// Web3Auth
// Wagmi Connect
async function login() {
if (isConnected) {
// await determineIfAccountIsAdmin();
if (web3auth.connected) {
dispatch(setIsConnected({ isConnected: true }));
if (!isOwner) {
//until the hook is working, this is going to prevent us from being directed to the dashboard
dispatch(setIsAdmin({ isAdmin: false }));
router.push("/dapp/dashboard");

return;
}
dispatch(setIsAdmin({ isAdmin: true }));
router.push("/dapp/dashboard");
return;
}

try {
await web3auth.connect();
connect({ connector: connectors[6] });
if (error) {
console.error("wagmi connect error: from Login - login(): ", error);
}
if (web3auth.connected) {
dispatch(setIsConnected({ isConnected: true }));

//const userAddress = await getAccounts(); // Retrieve user's address

// await determineIfAccountIsAdmin();
const address = await getAccounts(); // Retrieve user's address
if (address) {
setUserAddress(address);
}
if (!isOwner) {
// until the hook is working, this is going to prevent us from being directed to the dashboard
dispatch(setIsAdmin({ isAdmin: false }));
router.push("/dapp/dashboard");

return;
}
dispatch(setIsAdmin({ isAdmin: true }));
router.push("/dapp/dashboard");
}
} catch (error) {
console.error(error);
}
}

// async function determineIfAccountIsAdmin() {
// // set loading === true ???
// const userAddress = getAccounts();
// if (!userAddress) {
// console.error("from determineIfAccountIsAdmin - address is undefined");
// return;
// }

// if (!owner) {
// console.error("From determineIfAccountIsAdmin: ownerData from Payroll Contract is undefined");
// return;
// }

// /*-------------------------------------*/
// // Kaz & Trevor
// // need to see what shape `owner` will be on return
// const isAdmin = userAddress === owner ? true : false;
// dispatch(setIsAdmin({ isAdmin: isAdmin }));
// /*-------------------------------------*/
// // set loading === false ???
// }

// func to grab the connected wallet address
async function getAccounts() {
if (!web3auth.provider) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { UpdateFormValues } from "../../types/FormTypes";
import LandingIntro from "./LandingIntro";
import { Address, createWalletClient, custom } from "viem";
import { polygonMumbai } from "viem/chains";
import { useConnect } from "wagmi";
import { setIsConnected } from "~~/auth/authSlice";
import { web3auth } from "~~/auth/web3auth";
import { useMyDispatch } from "~~/components/dash-wind/app/store";
Expand All @@ -22,12 +23,17 @@ function Register() {
const [registerState, setRegisterState] = useState<RegisterState>("init");
const [registerObj, setRegisterObj] = useState(INITIAL_REGISTER_OBJ);
const [walletAddress, setWalletAddress] = useState<Address | null>(null);
const { connect, connectors, error } = useConnect();

const dispatch = useMyDispatch();
//@note is this working? working for register page?

async function login() {
try {
await web3auth.connect();
connect({ connector: connectors[6] });
if (error) {
console.error("wagmi connect error: from Register - login(): ", error);
}
if (web3auth.connected) {
dispatch(setIsConnected({ isConnected: true }));
}
Expand Down
85 changes: 60 additions & 25 deletions packages/nextjs/components/web-3-crew/register-page/DeployForm.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import React from "react";
import React, { useState } from "react";
import Link from "next/link";
import PayrollFactory from "../../../../hardhat/artifacts/contracts/PayrollFactory.sol/PayrollFactory.json";
import { Address, parseEther } from "viem";
import { useContractWrite } from "wagmi";
import { web3auth } from "~~/auth/web3auth";
import {
Address,
parseEther,
trim,
/*parseEther*/
} from "viem";
import { useContractEvent, useContractWrite } from "wagmi";
// import { web3auth } from "~~/auth/web3auth";
import { MyState, useMySelector } from "~~/components/dash-wind/app/store";
import ErrorText from "~~/components/dash-wind/components/Typography/ErrorText";
import { Address as AddressDisplay } from "~~/components/scaffold-eth/Address";

Expand All @@ -13,55 +19,89 @@ interface props {
ownerAddress: Address | null;
}
// Check if the user is connected
const isConnected = web3auth.connected;
const payrollFactoryAddress = "0xfe44aB0B966E57F126130BE6401546c7351484ad";
// const isConnected = web3auth.connected;
const payrollFactoryAddress = process.env.NEXT_PUBLIC_FACTORY_CONTRACT_ADDRESS;
const payrollFactoryABI = PayrollFactory.abi;

export default function DeployForm({ ownerAddress }: props) {
//const { data: contractData } = useDeployedContractInfo("PayrollFactory");
const { isConnected } = useMySelector((state: MyState) => state.auth);
const [newPayrollContractAddress, setNewPayrollContractAddress] = useState("");
const [newTokenTransferorContractAddress, setNewTokenTransferorContractAddress] = useState("");

/*-------------------------------------*/
// Kaz & Trevor -- think this is the right way to do it
// but running in browser it seems to always be looking for the connected address
// see no action in the terminal when the button is clicked
// deploy company contract after registration of account
// const { config } = usePrepareContractWrite({
// usePrepareContractWrite({
// address: payrollFactoryAddress,
// // abi: contractData?.abi,
// abi: payrollFactoryABI,
// functionName: "deployPayrollAndTokenTransferor",
// value: parseEther("1", "wei"),
// onSuccess(data) {
// args: [],
// value: 1_000_000n,
// gas: 1_000_000n,
// onSuccess(data: any) {
// console.log("contract deployed! Data: ", data); //will data be the contract addresses?
// },
// onError(error) {
// onError(error: any) {
// console.error("contract deploy error!", error); //error message
// },
// });

// const { data, write, isLoading, isSuccess } = useContractWrite(config);

//console.log("config: ", config);

const { data, isLoading, isSuccess, write } = useContractWrite({
address: payrollFactoryAddress,
abi: payrollFactoryABI,
functionName: "deployPayrollAndTokenTransferor",
args: [],
value: parseEther("0.000000000000000001"),
// value: 100_000_000_000_000_000n,
onSuccess(data: any) {
console.log("contract deployed! Data: ", data); //will data be the contract addresses?
},
onError(error: any) {
console.error("contract deploy error!", error); //error message
},
});
console.log("write: ", write);
console.log("data: ", data);
// console.log("write: ", write);
// console.log("data: ", data);

// Function to handle button click
const handleDeployClick = () => {
if (isConnected) {
write({
args: [],
//from: ownerAddress,
value: parseEther("1", "wei"),
});
console.log("writing...");
write();
} else {
console.log("Wallet not connected");
}
};

useContractEvent({
address: payrollFactoryAddress,
abi: payrollFactoryABI,
eventName: "TokenTransferorDeployed",
listener(log) {
console.log("TokenTransferorDeployed: ", trim(log[0].data));
setNewTokenTransferorContractAddress(trim(log[0].data).toString());
},
});
useContractEvent({
address: payrollFactoryAddress,
abi: payrollFactoryABI,
eventName: "PayrollDeployed",
listener(log) {
console.log("PayrollDeployed: ", trim(log[0].data).toString().slice(0, 42));
setNewPayrollContractAddress(trim(log[0].data).toString().slice(0, 42));
},
});
// 0x5898400727c49fc2453993e017f01f44077e508b; // 42
// 0xde9e1226a501921472da36c57b9acbe75891bf1
return (
<div className="py-24 px-10 relative">
<h2 className="text-2xl font-semibold mb-2 text-center">Deploy Payroll Contract</h2>
Expand All @@ -74,14 +114,7 @@ export default function DeployForm({ ownerAddress }: props) {
</div>
{/* <button onClick={() => writeAsync()} className="btn mt-2 w-full btn-primary mb-4"> */}
<button
// onClick={() =>
// write({
// args: [],
// //from: ownerAddress,
// value: parseEther("1", "wei"),
// })
// }
onClick={handleDeployClick}
onClick={() => handleDeployClick()}
disabled={isLoading || isSuccess ? true : false}
className={"btn mt-2 w-full btn-primary mb-4" + (isLoading ? " loading" : "")}
>
Expand All @@ -95,7 +128,9 @@ export default function DeployForm({ ownerAddress }: props) {
{data && (
<div className="flex flex-col mt-5">
<p>Payroll Contract Address:</p>
{/* <p>{data}</p> */}
<AddressDisplay format="long" address={newPayrollContractAddress} />
<p>Token Transferor Contract Address:</p>
<AddressDisplay format="long" address={newTokenTransferorContractAddress} />
{/* <AddressDisplay address={contractAddress} format="long" size="base" /> */}
</div>
)}
Expand Down

0 comments on commit 8e275bb

Please sign in to comment.