Skip to content

Commit

Permalink
feat-282 handling chain switch
Browse files Browse the repository at this point in the history
  • Loading branch information
adrianvrj committed Nov 29, 2024
1 parent f74f934 commit 900aa3a
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 57 deletions.
46 changes: 26 additions & 20 deletions frontend/gostarkme-web/components/modules/Fund/FundDonate.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@
import { calculatePorcentage } from "@/app/utils";
import ProgressBar from "@/components/ui/ProgressBar";
import { provider } from "@/constants";
import { strkAbi } from "@/contracts/abis/strk";
import { addrSTRK } from "@/contracts/addresses";
import {
networkAtom,
networkEnvironmentAtom,
walletStarknetkitLatestAtom,
} from "@/state/connectedWallet";
import { useAtomValue } from "jotai";
Expand All @@ -28,10 +25,15 @@ const FundDonate = ({ currentBalance, goal, addr, icon }: FundDonateProps) => {
const [isLoading, setIsLoading] = useState<boolean>(false);
const [localBalance, setLocalBalance] = useState<number>(currentBalance);
const wallet = useAtomValue(walletStarknetkitLatestAtom);
const network = useAtomValue(networkAtom);
const networkEnvironment = useAtomValue(networkEnvironmentAtom);
const [network, setNetwork] = useState(wallet?.chainId);
const networkEnvironment = process.env.NEXT_PUBLIC_CHAIN_ID;
const progress = calculatePorcentage(localBalance, goal);

const handleNetwork = (chainId?: string, accounts?: string[]) => {
setNetwork(wallet?.chainId);
};
wallet?.on('networkChanged', handleNetwork);

const handleAmountChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value === "" ? "" : Number(e.target.value);
setAmount(value);
Expand All @@ -40,22 +42,22 @@ const FundDonate = ({ currentBalance, goal, addr, icon }: FundDonateProps) => {

const waitForTransaction = async (hash: string) => {
try {
await provider.waitForTransaction(hash);
return true;
await provider.waitForTransaction(hash);
return true;
} catch (error) {
console.error("Error waiting for transaction:", error);
return false;
console.error("Error waiting for transaction:", error);
return false;
}
};

const handleDonateClick = async (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();

if (amount === "") {
setError("This field is required.");
return;
}

if (typeof amount === "number" && amount < 0) {
setError("The amount cannot be negative.");
return;
Expand Down Expand Up @@ -85,11 +87,11 @@ const FundDonate = ({ currentBalance, goal, addr, icon }: FundDonateProps) => {

if (tx) {
const isConfirmed = await waitForTransaction(tx.transaction_hash);

if (isConfirmed) {
if (typeof amount === 'number') {
setLocalBalance(prev => Number(prev) + amount);
}
}
setAmount("");
setError("Transaction successful!");
setTimeout(() => {
Expand Down Expand Up @@ -126,26 +128,30 @@ const FundDonate = ({ currentBalance, goal, addr, icon }: FundDonateProps) => {
/>
</div>
{error && (
<p className={`text-center mb-4 ${
error === "Transaction successful!" ? "text-green-500" : "text-red-500"
}`}>
<p className={`text-center mb-4 ${error === "Transaction successful!" ? "text-green-500" : "text-red-500"
}`}>
{error}
</p>
)}
<div className="text-center">
<button
disabled={!network}
disabled={network !== networkEnvironment || !wallet}
onClick={handleDonateClick}
className={`self-center bg-darkblue text-white py-2 px-6 md:py-3 md:px-10 rounded-md
text-xs md:text-sm shadow-xl hover:bg-starkorange active:bg-darkblue ease-in-out
duration-500 active:duration-0 shadow-gray-400 ${!network ? "opacity-50 cursor-not-allowed" : ""}`}
duration-500 active:duration-0 shadow-gray-400 ${network !== networkEnvironment ? "opacity-50 cursor-not-allowed" : ""}`}
>
Donate
</button>
{wallet && !network && (
{wallet && network !== networkEnvironment && (
<p className="text-sm text-gray-500 mt-2">
Your wallet is currently connected to the wrong network. Please
switch to {networkEnvironment[1]} to continue.
switch to {networkEnvironment} to continue.
</p>
)}
{!wallet && (
<p className="text-sm text-gray-500 mt-2">
Please connect your wallet to donate.
</p>
)}
</div>
Expand Down
63 changes: 33 additions & 30 deletions frontend/gostarkme-web/components/modules/Fund/FundVote.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@ import { Button } from "@/components/ui/Button";
import ProgressBar from "@/components/ui/ProgressBar";
import { fundAbi } from "@/contracts/abis/fund";
import {
networkAtom,
networkEnvironmentAtom,
walletStarknetkitLatestAtom,
} from "@/state/connectedWallet";
import { latestTxAtom } from "@/state/latestTx";
import { useAtomValue, useSetAtom } from "jotai";
import { Contract, InvokeFunctionResponse } from "starknet";
import { Contract } from "starknet";
import { useRouter } from "next/navigation";
import {useState, useEffect} from "react";
import { useState, useEffect } from "react";

interface FundVoteProps {
upVotes: number,
Expand All @@ -21,38 +19,43 @@ interface FundVoteProps {
getDetails: () => void,
}

export const FundVote = ({ upVotes, upVotesNeeded, addr, setLoading}: FundVoteProps) => {
export const FundVote = ({ upVotes, upVotesNeeded, addr, setLoading }: FundVoteProps) => {

const wallet = useAtomValue(walletStarknetkitLatestAtom);
const network = useAtomValue(networkAtom);
const networkEnvironment = useAtomValue(networkEnvironmentAtom);
const [network, setNetwork] = useState(wallet?.chainId);
const networkEnvironment = process.env.NEXT_PUBLIC_CHAIN_ID;

const progress = calculatePorcentage(upVotes, upVotesNeeded);

const setLatestTx = useSetAtom(latestTxAtom);

const router = useRouter();

const [isChecking, setIsChecking] = useState(true);
const [voteStatus, setVoteStatus] = useState(false);
const [isChecking, setIsChecking] = useState(true);
const [voteStatus, setVoteStatus] = useState(false);
const [isVoting, setIsVoting] = useState(false);

const handleNetwork = (chainId?: string, accounts?: string[]) => {
setNetwork(wallet?.chainId);
};
wallet?.on('networkChanged', handleNetwork);

useEffect(() => {
const checkVoteStatus = async () => {
if (!wallet?.account) {
setIsChecking(false);
setIsChecking(false);
return;
}

setIsChecking(true);
try {
const fundContract = new Contract(fundAbi, addr, wallet.account);

try {
await fundContract.estimate('receiveVote');
setVoteStatus(false);
} catch (error: any) {
if (error?.toString().includes('User already voted')) {
if (error?.toString().includes('User already voted')) {
setVoteStatus(true);
}
}
Expand All @@ -65,7 +68,7 @@ export const FundVote = ({ upVotes, upVotesNeeded, addr, setLoading}: FundVotePr

checkVoteStatus();
}, [wallet?.account, addr]);

const handleVote = async () => {
if (!wallet?.account) return;
setLoading(true);
Expand Down Expand Up @@ -97,19 +100,19 @@ export const FundVote = ({ upVotes, upVotesNeeded, addr, setLoading}: FundVotePr
</div>
{isChecking ? ( //if isChecking is true render a button that checks the vote status
<div className="text-center">
<Button
label="Checking vote status..."
onClick={() => {}}
<Button
label="Checking vote status..."
onClick={() => { }}
className="opacity-50 cursor-not-allowed"
disabled={true}
/>
</div>
) : wallet ? ( // Check if a wallet is connected by evaluating 'wallet' condition
voteStatus ? ( //if voteStatus is true button is disabled
<div className="text-center">
<Button
label="Vote"
onClick={() => {}}
<div className="text-center">
<Button
label="Vote"
onClick={() => { }}
className="opacity-50 cursor-not-allowed"
disabled={true}
/>
Expand All @@ -120,30 +123,30 @@ export const FundVote = ({ upVotes, upVotesNeeded, addr, setLoading}: FundVotePr
<Button
label={isVoting ? "Voting..." : "Vote"}
onClick={handleVote}
disabled={isVoting || !network}
disabled={isVoting || network !== networkEnvironment}
className={
isVoting || !network ? "opacity-50 cursor-not-allowed" : ""
isVoting || network !== networkEnvironment ? "opacity-50 cursor-not-allowed" : ""
}
/>
{/* // If the wallet is connected, and voteStatus is false render a button that allows voting */}
{!network && (
{network !== networkEnvironment && (
<p className="text-sm text-gray-500 mt-2">
Your wallet is currently connected to the wrong network. Please
switch to {networkEnvironment[1]} to continue.
switch to {networkEnvironment} to continue.
</p>
)}
</div>
)
) : ( // If the wallet is not connected, render a disabled vote button with instructions
<div className="text-center">
<Button
label="Vote"
onClick={() => {}}
<div className="text-center">
<Button
label="Vote"
onClick={() => { }}
className="opacity-50 cursor-not-allowed"
disabled={true}
/>
<p className="text-sm text-gray-500 mt-2">
Connect your wallet to vote
Connect your wallet to vote
</p>
</div>
)}
Expand Down
5 changes: 1 addition & 4 deletions frontend/gostarkme-web/components/ui/ConnectWalletButton.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
"use client";
import { ARGENT_WEBWALLET_URL, CHAIN_ID, provider } from "@/constants";
import { networkAtom, walletStarknetkitLatestAtom } from "@/state/connectedWallet";
import { walletStarknetkitLatestAtom } from "@/state/connectedWallet";
import { useAtom, useSetAtom } from "jotai";
import { connect, disconnect } from "starknetkit";

export default function WalletConnector() {
const [wallet, setWallet] = useAtom(walletStarknetkitLatestAtom)
const setNetworkAtom = useSetAtom(networkAtom)

const handleConnect = async (event:any) => {
try {
Expand All @@ -22,8 +21,6 @@ export default function WalletConnector() {
},
})

wallet && setNetworkAtom(wallet?.chainId === process.env.NEXT_PUBLIC_NETWORK)

setWallet(wallet)
} catch (e) {
console.error(e)
Expand Down
3 changes: 0 additions & 3 deletions frontend/gostarkme-web/state/connectedWallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,3 @@ import { StarknetWindowObject } from "starknetkit";
export const walletStarknetkitLatestAtom = atomWithReset<
StarknetWindowObject | null | undefined
>(undefined);

export const networkAtom = atom(false);
export const networkEnvironmentAtom = atom(["Mainnet", "Sepolia", "Devnet"]);

0 comments on commit 900aa3a

Please sign in to comment.