Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use right signer #3531

Merged
merged 3 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions packages/grant-explorer/src/features/common/Auth.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,31 @@ import { Outlet } from "react-router-dom";
import {
useAccount,
usePublicClient,
useWalletClient,
} from "wagmi";

import { Spinner } from "./Spinner";
import { ConnectButton } from "@rainbow-me/rainbowkit";
import { getEthersSigner } from "../../app/wagmi";
import { JsonRpcSigner } from "@ethersproject/providers";
import { useState, useEffect } from "react";

/**
* Component for protecting child routes that require web3 wallet instance.
* It prompts a user to connect wallet if no web3 instance is found.
*/
export default function Auth() {
const { chain, address, isConnected, isConnecting } = useAccount();
const { data: signer } = useWalletClient();
const [signer, setSigner] = useState<JsonRpcSigner>();

const { address, chain, isConnected, isConnecting, connector } = useAccount();

useEffect(() => {
const init = async () => {
const s = await getEthersSigner(connector!, chain!.id);
setSigner(s);
};
if (isConnected && chain && connector?.getAccounts) init();
}, [chain, isConnected, connector]);

const provider = usePublicClient();

const data = {
Expand Down
10 changes: 1 addition & 9 deletions packages/round-manager/src/features/common/Auth.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { Outlet, useOutletContext } from "react-router-dom";
import { Outlet } from "react-router-dom";
import { useAccount, usePublicClient, useWalletClient } from "wagmi";
import { Web3Instance } from "../api/types";
import { Spinner } from "./Spinner";
import { ReactComponent as LandingBanner } from "../../assets/landing/banner.svg";
import { ReactComponent as LandingLogo } from "../../assets/landing/logo.svg";
Expand Down Expand Up @@ -59,10 +58,3 @@ export default function Auth() {
<Outlet context={data} />
);
}

/**
* Wrapper hook to expose wallet auth information to other components
*/
export function useWallet() {
return useOutletContext<Web3Instance>();
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import { success } from "common/src/allo/common";
import { MemoryRouter } from "react-router-dom";
import { zeroAddress } from "viem";
import { errorModalDelayMs } from "../../../constants";
import { useWallet } from "../../common/Auth";
import CreateProgramPage from "../CreateProgramPage";
import wagmi, { Config, UseAccountReturnType } from "wagmi";

Expand Down Expand Up @@ -51,10 +50,7 @@ jest.mock("wagmi", () => ({

describe("<CreateProgramPage />", () => {
beforeEach(() => {
(useWallet as jest.Mock).mockReturnValue({
chain: {},
address: zeroAddress,
});

});

it("shows program chain tooltip", async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
wrapWithRoundContext,
} from "../../../test-utils";
import { Program, ProgressStatus } from "../../api/types";
import { useWallet } from "../../common/Auth";
import ViewProgram from "../ViewProgramPage";

const programId = faker.datatype.number().toString();
Expand Down Expand Up @@ -72,11 +71,6 @@ describe("<ViewProgram />", () => {
],
});

(useWallet as jest.Mock).mockReturnValue({
chain: {},
address: stubProgram.operatorWallets[0],
provider: { getNetwork: () => Promise.resolve({ chainId: "0x0" }) },
});
});

it("should display NotFoundPage when no program is found", () => {
Expand Down Expand Up @@ -144,11 +138,6 @@ describe("<ViewProgram />", () => {
];

const stubProgram = makeProgramData({ id: programId, operatorWallets });
(useWallet as jest.Mock).mockReturnValue({
chain: {},
address: stubProgram.operatorWallets[0],
provider: { getNetwork: () => Promise.resolve({ chainId: "0x0" }) },
});

render(
wrapWithReadProgramContext(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import ProgressModal from "../common/ProgressModal";
import { InformationCircleIcon } from "@heroicons/react/solid";
import ReactTooltip from "react-tooltip";
import ErrorModal from "../common/ErrorModal";
import { useWallet } from "../common/Auth";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
Expand Down
19 changes: 13 additions & 6 deletions packages/round-manager/src/features/round/FundContract.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ import {
import { assertAddress } from "common/src/address";
import { formatUnits, zeroAddress } from "viem";
import { Erc20__factory } from "../../types/generated/typechain";
import { useWallet } from "../common/Auth";
import { getAlloAddress } from "common/src/allo/backends/allo-v2";
import { JsonRpcSigner } from "@ethersproject/providers";
import { getEthersSigner } from "../../app/wagmi";

// fixme: move this to its own hook
export function useContractAmountFunded(args: {
Expand Down Expand Up @@ -142,10 +143,10 @@ export default function FundContract(props: {
round: Round | undefined;
roundId: string | undefined;
}) {
const { address, chain } = useAccount();
const navigate = useNavigate();
const { signer } = useWallet();

const { address, chainId, isConnected, connector } = useAccount();
const [signer, setSigner] = useState<JsonRpcSigner>();
const [amountToFund, setAmountToFund] = useState("");
const [insufficientBalance, setInsufficientBalance] = useState(false);
const [openConfirmationModal, setOpenConfirmationModal] = useState(false);
Expand All @@ -156,7 +157,13 @@ export default function FundContract(props: {
>();
const [transactionReplaced, setTransactionReplaced] = useState(false);

const chainId = chain?.id ?? 5;
useEffect(() => {
const init = async () => {
const s = await getEthersSigner(connector!, chainId!);
setSigner(s);
};
if (isConnected && chainId && connector?.getAccounts) init();
}, [chainId, isConnected, connector]);

const allo = useAllo();

Expand Down Expand Up @@ -522,7 +529,7 @@ export default function FundContract(props: {
onClick={() =>
window.open(
getTxExplorerForContract(
chainId,
chainId!,
props.roundId as string
),
"_blank"
Expand Down Expand Up @@ -670,7 +677,7 @@ export default function FundContract(props: {

const alloVersion = props.round?.tags?.includes("allo-v2") ? "v2" : "v1";
const roundAddress =
alloVersion === "v1" ? props.round?.id : getAlloAddress(chainId);
alloVersion === "v1" ? props.round?.id : getAlloAddress(chainId!);

if (
matchingFundPayoutToken?.address !== undefined &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,16 @@ import {
typeToText,
} from "../api/utils";
import AddQuestionModal from "../common/AddQuestionModal";
import { useWallet } from "../common/Auth";
import BaseSwitch from "../common/BaseSwitch";
import ErrorModal from "../common/ErrorModal";
import { FormStepper as FS } from "../common/FormStepper";
import { FormContext } from "../common/FormWizard";
import { InputIcon } from "../common/InputIcon";
import PreviewQuestionModal from "../common/PreviewQuestionModal";
import ProgressModal from "../common/ProgressModal";
import { JsonRpcSigner } from "@ethersproject/providers";
import { useAccount } from "wagmi";
import { getEthersSigner } from "../../app/wagmi";

export const getInitialQuestionsQF = (chainId: number): SchemaQuestion[] => [
{
Expand Down Expand Up @@ -162,11 +164,20 @@ export function RoundApplicationForm(props: {
stepper: typeof FS;
configuration?: { roundCategory?: RoundCategory };
}) {
const [signer, setSigner] = useState<JsonRpcSigner>();
const [openProgressModal, setOpenProgressModal] = useState(false);
const [openPreviewModal, setOpenPreviewModal] = useState(false);
const [openAddQuestionModal, setOpenAddQuestionModal] = useState(false);
const [toEdit, setToEdit] = useState<EditQuestion | undefined>();
const { signer: walletSigner, chain } = useWallet();
const { chainId, isConnected, connector } = useAccount();

useEffect(() => {
const init = async () => {
const s = await getEthersSigner(connector!, chainId!);
setSigner(s);
};
if (isConnected && chainId && connector?.getAccounts) init();
}, [chainId, isConnected, connector]);

const { currentStep, setCurrentStep, stepsCount, formData } =
useContext(FormContext);
Expand All @@ -187,8 +198,8 @@ export function RoundApplicationForm(props: {
const defaultQuestions: ApplicationMetadata["questions"] = questionsArg
? questionsArg
: roundCategory === RoundCategory.QuadraticFunding
? getInitialQuestionsQF(chain.id)
: getInitialQuestionsDirect(chain.id);
? getInitialQuestionsQF(chainId!)
: getInitialQuestionsDirect(chainId!);

const { control, handleSubmit } = useForm<Round>({
defaultValues: {
Expand Down Expand Up @@ -308,7 +319,7 @@ export function RoundApplicationForm(props: {
roundOperators: round.operatorWallets.map(getAddress),
},
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
walletSigner: walletSigner!,
walletSigner: signer!,
});
} catch (error) {
datadogLogs.logger.error(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
ROUND_PAYOUT_DIRECT_OLD as ROUND_PAYOUT_DIRECT,
} from "common";

import { useWallet } from "../../common/Auth";
import { Connector, useAccount, useDisconnect } from "wagmi";
import { BigNumber, ethers } from "ethers";
import { Erc20__factory } from "../../../types/generated/typechain";
Expand All @@ -36,32 +35,6 @@ jest.mock("@rainbow-me/rainbowkit", () => ({
}));

const mockAddress = ethers.constants.AddressZero;
const mockWallet = {
provider: {
network: {
chainId: 1,
},
},
address: mockAddress,
signer: {
getChainId: () => {
/* do nothing */
},
},
chain: {
name: "abc",
id: 1,
},
};
const mockNetwork = {
chain: {
blockExplorers: {
default: {
url: "https://mock-blockexplorer.com",
},
},
},
};

const correctAnswerBlocks = [
{
Expand All @@ -81,10 +54,6 @@ const correctAnswerBlocks = [
},
];

jest.mock("../../../features/common/Auth", () => ({
useWallet: () => mockWallet,
}));

jest.mock("wagmi", () => ({
...jest.requireActual("wagmi"),
useSwitchChain: () => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { faker } from "@faker-js/faker";
import { RoundDetailForm } from "../RoundDetailForm";
import ApplicationEligibilityForm from "../ApplicationEligibilityForm";
import { RoundApplicationForm } from "../RoundApplicationForm";
import { useWallet } from "../../common/Auth";
import * as FormWizardImport from "../../common/FormWizard";
import { fireEvent, screen } from "@testing-library/react";
import QuadraticFundingForm from "../QuadraticFundingForm";
Expand Down Expand Up @@ -35,11 +34,7 @@ jest.mock("react-router-dom", () => ({

describe("<CreateRoundPage />", () => {
beforeEach(() => {
(useWallet as jest.Mock).mockReturnValue({
chain: {},
address: "0x0",
provider: { getNetwork: () => ({ chainId: "0x0" }) },
});

});

it("sends program to form wizard", () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { fireEvent, screen } from "@testing-library/react";
import { renderWrapped } from "../../../test-utils";
import { NATIVE, getPayoutTokens } from "common";

import { useWallet } from "../../common/Auth";
import { FormStepper } from "../../common/FormStepper";
import QuadraticFundingForm from "../QuadraticFundingForm";

Expand All @@ -22,12 +21,6 @@ jest.mock("../../../constants", () => ({
errorModalDelayMs: 0, // NB: use smaller delay for faster tests
}));

beforeEach(() => {
(useWallet as jest.Mock).mockReturnValue({
chain: { id: 10 },
});
});

describe("<QuadraticFundingForm />", () => {
beforeEach(() => {
renderWrapped(<QuadraticFundingForm stepper={FormStepper} />);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {
ApplicationMetadata,
ProgressStatus,
} from "../../api/types";
import { useWallet } from "../../common/Auth";
import { FormStepper } from "../../common/FormStepper";
import { FormContext } from "../../common/FormWizard";
import {
Expand Down Expand Up @@ -75,19 +74,6 @@ const randomMetadata = {

describe("<RoundApplicationForm />", () => {
beforeEach(() => {
(useWallet as jest.Mock).mockReturnValue({
chain: { name: "my blockchain" },
provider: {
getNetwork: () =>
Promise.resolve({
chainId: 5,
}),
},
signer: {
getChainId: () => 5,
},
address: "0x0",
});
(saveToIPFS as jest.Mock).mockResolvedValue("some ipfs hash");
});

Expand Down Expand Up @@ -207,20 +193,6 @@ describe("<RoundApplicationForm />", () => {
});

describe("Application Form Builder", () => {
beforeEach(() => {
(useWallet as jest.Mock).mockReturnValue({
chain: { name: "my blockchain" },
provider: {
getNetwork: () => ({
chainId: 0,
}),
},
signer: {
getChainId: () => 0,
},
address: "0x0",
});
});

it("displays the four default questions", () => {
renderWithContext(
Expand Down Expand Up @@ -626,20 +598,6 @@ describe("Application Form Builder", () => {
});
});
describe("Project Socials", () => {
beforeEach(() => {
(useWallet as jest.Mock).mockReturnValue({
chain: { name: "my blockchain" },
provider: {
getNetwork: () => ({
chainId: 0,
}),
},
signer: {
getChainId: () => 0,
},
address: "0x0",
});
});

it("displays the Project Socials", () => {
renderWithContext(
Expand Down
Loading
Loading