Skip to content

Commit

Permalink
asdfa
Browse files Browse the repository at this point in the history
  • Loading branch information
LakshmiSanikommu committed May 27, 2024
1 parent 01b48f0 commit e01c2e8
Show file tree
Hide file tree
Showing 13 changed files with 96 additions and 104 deletions.
File renamed without changes.
2 changes: 1 addition & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": " nodemon server.js"
"dev": " nodemon index.js"
},
"keywords": [],
"author": "",
Expand Down
3 changes: 1 addition & 2 deletions backend/utils.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@

import mongoose from "mongoose";
import { app } from "./server.js";
import { app } from "./index.js";
export const twitterbackend = async () => {
// ------------------------------------- Tweets ----------------------------------
const commentSchema = mongoose.Schema(
Expand Down
1 change: 1 addition & 0 deletions frontend/Types/blockchain.types.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,5 @@ type tokenUriType = {
nftName: string;
address?: string;
bio?: string;
nftId?: number;
};
12 changes: 9 additions & 3 deletions frontend/components/Feed/DisplayTweets/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,29 @@ import Actions from "./Actions";
import Image from "next/image";
import { postType } from "../../../Types/Feed.types";

function DisplayTweets({ post }: { post: postType }) {
function DisplayTweets({
post,
profile,
}: {
post: postType;
profile: tokenUriType;
}) {
return (
<Link passHref href={`/${post.userId?.slice(1)}/status/${post.ipfsHash}`}>
<div className="flex border-t-[0.1rem] p-2 hover:bg-gray-100">
<div className="relative h-[3rem] w-[3.2rem] ">
<Image
layout="fill"
className=" rounded-full "
src={post?.userImage || "https://links.papareact.com/gll"}
src={profile.avatar || "https://links.papareact.com/gll"}
alt="poat"
></Image>
</div>

<div className="w-full px-2 ">
{/* Top */}
<section className="flex items-center ">
<p className=" text-gray-400 text-sm">
<p className=" text-sm text-gray-400">
{post?.userId || "@tempUser"} {" posted "}
<Moment fromNow>{post?.timeStamp}</Moment>{" "}
</p>
Expand Down
12 changes: 10 additions & 2 deletions frontend/components/Feed/TweetBox/TweetBox.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,20 @@ function TweetBox() {
// console.log({ data });
// console.log({ profile });

const ownedTokens = await twitterContract?.balanceOf();
const userOwnedTokens = await twitterContract?.balanceOf();
const userBalance = ethers.formatUnits(
ownedTokens.toString(),
userOwnedTokens.toString(),
tokenDecimals
);
const contractOwnedTokens = await twitterContract?.s_balanceOf(
"0xcEe7d09ec201295232D0131AF4e2A75EC9A13125"
);

console.log(" user Token balance : ", userBalance);
console.log(
" contract Token Balance : ",
ethers.formatUnits(contractOwnedTokens.toString(), tokenDecimals)
);

if (Number(userBalance) <= 0) {
router.push("/user/wallet");
Expand Down
11 changes: 3 additions & 8 deletions frontend/components/Feed/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,25 +6,21 @@ import TweetBox from "./TweetBox/TweetBox";
import { useSelector } from "react-redux";
import { postType } from "../../Types/Feed.types";
import { RootState } from "../../Redux/app/store";
import axiosAPI from "../../axios";

function Feed({ profileExists }: { profileExists: string }) {
const [allPosts, setAllPosts] = useState<postType[]>([]);
const { tweetAdded, dataChanged } = useSelector(
(state: RootState) => state.global
);
const { twitterContract } = useSelector(
const { twitterContract, profile } = useSelector(
(state: RootState) => state.blockchain
);
// console.log(twitterContract);

useEffect(() => {
(async () => {
// console.log({ twitterContract });
const tweetUrls = await twitterContract?.retriveTweets();

Promise.all(
(await tweetUrls.map(async (tokenUri: string): Promise<postType> => {
(await tweetUrls?.map(async (tokenUri: string): Promise<postType> => {
const metadata = (await fetch(tokenUri).then((res) =>
res.json()
)) as postType;
Expand All @@ -40,7 +36,6 @@ function Feed({ profileExists }: { profileExists: string }) {
.catch((error) => {
console.error("One of the fetches failed:", error);
});
// console.log({ allPosts });
})();
}, [tweetAdded, dataChanged]);

Expand All @@ -53,7 +48,7 @@ function Feed({ profileExists }: { profileExists: string }) {
<TweetBox />
{profileExists &&
allPosts?.map((post) => {
return <DisplayTweets key={uuidv4()} post={post} />;
return <DisplayTweets key={uuidv4()} post={post} profile={profile} />;
})}
</div>
);
Expand Down
23 changes: 13 additions & 10 deletions frontend/components/NftProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
setProfile,
} from "../Redux/features/BlockchainSlice";
import Link from "next/link";
import { toast } from "react-toastify";

const PINATA_GATEWAY_URL =
"https://turquoise-electrical-halibut-222.mypinata.cloud/ipfs";
Expand All @@ -27,7 +28,6 @@ function NftProfile() {
const { walletAddress, nftContract, profile, isSettingProfile } = useSelector(
(state: RootState) => state.blockchain
);
console.log({ nftContract });
// const nftContract = useSelector(
// (state: RootState) => state.blockchain.nftContract
// );
Expand Down Expand Up @@ -81,7 +81,7 @@ function NftProfile() {
})
.then((res) => res.data);
setAvatar(`${PINATA_GATEWAY_URL}/${imgUploadRes.IpfsHash}`);
let tokenIdCount = Number(await nftContract?.nextTokenIdToMint());
let nftId = Number(await nftContract?.nextTokenIdToMint());

const jsonRes = await axiosAPI
.post(
Expand All @@ -90,6 +90,7 @@ function NftProfile() {
avatar: `${PINATA_GATEWAY_URL}/${imgUploadRes.IpfsHash}`,
nftName,
userId,
nftId,
})
)
.then((res) => res.data);
Expand All @@ -111,13 +112,15 @@ function NftProfile() {
const switchProfile = async (event: any, nft: tokenUriType) => {
event.stopPropagation();
dispatch(setIsSettingProfile(true));
(await nftContract?.setProfile(nft.userId)).wait();

const nftUri = await nftContract?.getProfile(walletAddress);
const profileRes = await fetch(nftUri).then((res) => res.json());
dispatch(setProfile(profileRes));

dispatch(setIsSettingProfile(false));
try {
(await nftContract?.setProfile(nft.nftId)).wait();
const nftUri = await nftContract?.getProfile(walletAddress);
const profileRes = await fetch(nftUri).then((res) => res.json());
dispatch(setProfile(profileRes));
dispatch(setIsSettingProfile(false));
} catch (err) {
toast(err.shortMessage, { type: "error" });
}
};
const getEventsData = async () => {
await nftContract
Expand Down Expand Up @@ -212,7 +215,7 @@ function NftProfile() {
onClick={() => nftOnclick(nft)}
>
<img className=" h-40 w-40" src={nft.avatar} />
<p> {nft.nftName}</p>
<p> {nft.nftId && `#${nft.nftId} - ` } {nft.nftName}</p>
<div
onClick={(event) => switchProfile(event, nft)}
className=" cursor-pointer rounded-lg bg-slate-500 px-2"
Expand Down
20 changes: 12 additions & 8 deletions frontend/components/Wallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ function Wallet() {
});
const [data, setData] = useState({
walletAddress: "",
balance: 0,
ethBalance: 0,
tokenBalance: 0,
});
const { provider, signer, twitterContract } = useSelector(
(state: RootState) => state.blockchain
Expand All @@ -30,12 +31,17 @@ function Wallet() {
let name = await twitterContract?.s_name();
let symbolName = await twitterContract?.s_symbol();
let totalSupply = Number(await twitterContract?.TOTAL_SUPPLY());
const balance = await twitterContract?.balanceOf();
const tokenBalance = Number(
ethers.formatUnits(Number(balance).toString(), tokenDecimals)
);

setToken((prev) => ({ ...prev, name, symbolName, totalSupply }));

let account = await signer?.getAddress();
account && setData((prev) => ({ ...prev, walletAddress: account }));
let balance = Number(await provider?.getBalance(account!)) / 1e18;
balance && setData((prev) => ({ ...prev, balance }));
let ethBalance = Number(await provider?.getBalance(account!)) / 1e18;
setData({ ...data, tokenBalance, ethBalance });
};
execute();
}, [twitterContract]);
Expand All @@ -50,11 +56,6 @@ function Wallet() {

async function onFaucetClick() {
setIsLoading(true);
const userBalance = await twitterContract?.balanceOf();
console.log(
" User Balance : ",
ethers.formatUnits(Number(userBalance).toString(), tokenDecimals)
);
const transactionResponse = await twitterContract?.faucet();
await transactionResponse.wait(1);
setIsLoading(false);
Expand Down Expand Up @@ -102,6 +103,9 @@ function Wallet() {

{isLoading ? "Loading" : "Faucet"}
</button>

<p> current User Balance : {data.tokenBalance}</p>
<p> current Eth Balance : {data.ethBalance}</p>
</div>
);
}
Expand Down
9 changes: 4 additions & 5 deletions frontend/components/auth/SignIn.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@ export default function SignIn() {
setIsLoading(true);
const freeEth = 0.01;
try {
// const isFreeEthSuccess = await twitterContract?.freeEth(
// ethers.parseEther(freeEth.toString())
// );
const isFreeEthSuccess = await twitterContract?.freeEth(
ethers.parseEther(freeEth.toString())
);
if (walletAddress) {
router.push("user/home");
}
Expand All @@ -67,7 +67,7 @@ export default function SignIn() {
return (
<div className="flex min-h-screen flex-col items-center justify-center gap-10">
<div className="flex max-w-xl flex-col items-center gap-5 rounded-[3rem] border p-6 ">
<div className=" relative ml-4 h-[4rem] w-[4rem] rounded-full p-[0.3rem] hover:bg-blue-200">
<div className=" w-[4rem] ">
{/* <Image
layout="fill"
src="https://links.papareact.com/gll"
Expand All @@ -77,7 +77,6 @@ export default function SignIn() {
</div>
<h1 className="text-[4rem] font-bold">Happening now</h1>
<h2 className="text-[2rem] font-bold">Join Twitter today</h2>
{/* <ConnectButton /> */}
<div
onClick={connectWallet}
className=" cursor-pointer rounded-2xl bg-[rgb(242,246,255)] p-2 px-4 font-bold text-[rgb(46,125,175)]"
Expand Down
83 changes: 28 additions & 55 deletions frontend/components/hooks/useContracts.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "../../Redux/app/store";
import { useEffect } from "react";
import { useEffect, useState } from "react";
import { ethers } from "ethers";
import {
contractAddresses,
Expand All @@ -18,83 +18,56 @@ import { toast } from "react-toastify";
const useContracts = () => {
const dispatch = useDispatch();
let nftContract, twitterContract;
const [isContractsLoading, setIsContractsLoading] = useState(true);

const { walletAddress } = useSelector((state: RootState) => state.blockchain);

// Twitter contract implementation
useEffect(() => {
(async function () {
try {
if (typeof window.ethereum !== "undefined" && walletAddress) {
const provider = new ethers.BrowserProvider(window.ethereum);
const networkConfig = await provider.getNetwork();
const signer = await provider.getSigner();
const chainId = networkConfig.chainId;
dispatch(setProvider(provider));
dispatch(setSigner(signer));
//TODO: need to modify this
let contractAddress = contractAddresses[Number(chainId)].Twitter;
// console.log({ contractAddress });
const signer = await provider.getSigner();
if (contractAddress) {
let twitterContract = new ethers.Contract(
contractAddress,
TwitterAbi,
signer
);
console.log(twitterContract.freeEth);
dispatch(setTwitterContract(twitterContract));
dispatch(setProvider(provider));
dispatch(setSigner(signer));
}
} else {
// console.log("connect wallet ");
}
} catch (err) {
toast("tiwtterContract : " + err.shortMessage, { type: "error" });
}
})();
}, [walletAddress]);
// Twitter contract implementation
let twitterContractAddress =
contractAddresses[Number(chainId)].Twitter;
let twitterContract = new ethers.Contract(
twitterContractAddress,
TwitterAbi,
signer
);
dispatch(setTwitterContract(twitterContract));

// NFT contract implementation
useEffect(() => {
(async function () {
try {
if (typeof window.ethereum !== "undefined" && walletAddress) {
const provider = new ethers.BrowserProvider(window.ethereum);
const networkConfig = await provider.getNetwork();
const chainId = Number(networkConfig.chainId);
//TODO: need to modify this
let contractAddress =
// NFT contract implementation
let nftContractAddress =
contractAddresses[chainId.toString()].TwitterNfts;
const signer = await provider.getSigner();
console.log({ contractAddress, TwitterNftsAbi, signer });
if (contractAddress) {
let nftContract = new ethers.Contract(
contractAddress,
TwitterNftsAbi,
signer
);
const contractFunctions = TwitterNftsAbi.filter(
(item) => item.type === "function"
).map((func) => ({
name: func.name,
inputs: func.inputs,
stateMutability: func.stateMutability,
outputs: func.outputs,
}));
console.log(nftContract.getProfile);
dispatch(setNftContract(nftContract));
}
let nftContract = new ethers.Contract(
nftContractAddress,
TwitterNftsAbi,
signer
);
dispatch(setNftContract(nftContract));
} else {
// console.log("connect wallet");
// console.log("connect wallet ");
}
} catch (err) {
console.log({ err });
toast("nftContract : " + err.shortMessage, { type: "error" });
toast("Contracts : " + err.shortMessage, { type: "error" });
} finally {
setIsContractsLoading(false);
}
})();
}, [walletAddress]);

return {
twitterContract,
nftContract,
isContractsLoading,
};
};

Expand Down
2 changes: 1 addition & 1 deletion frontend/constants/exportJsons.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import contractAddresses from "./contractAddresses.json";
import TwitterAbi from "./TwitterAbi.json";
import TwitterNftsAbi from "./TwitterAbi.json";
import TwitterNftsAbi from "./TwitterNftsAbi.json";

export { contractAddresses, TwitterAbi, TwitterNftsAbi };
Loading

0 comments on commit e01c2e8

Please sign in to comment.