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 resolve safe transaction receipt for voting #842

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
4 changes: 3 additions & 1 deletion src/app/api/common/votes/getVotes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { doInSpan } from "@/app/lib/logging";
import { findVotes } from "@/lib/prismaUtils";
import { TENANT_NAMESPACES } from "@/lib/constants";
import { Block } from "ethers";
import { isAddress, getAddress } from "viem";

const getVotesForDelegate = ({
addressOrENSName,
Expand Down Expand Up @@ -481,10 +482,11 @@ async function getVotesForProposalAndDelegate({
address: string;
}) {
const { namespace, contracts, ui } = Tenant.current();
const checkSummedAddress = isAddress(address) ? getAddress(address) : address;
const votes = await findVotes({
namespace,
proposalId,
voter: address.toLowerCase(),
voter: checkSummedAddress,
});

const latestBlock = ui.toggle("use-l1-block-number")?.enabled
Expand Down
11 changes: 6 additions & 5 deletions src/hooks/useAdvancedVoting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,9 @@ import { useCallback, useState } from "react";
import { useAccount, useWriteContract } from "wagmi";
import { track } from "@vercel/analytics";
import Tenant from "@/lib/tenant/tenant";
import { waitForTransactionReceipt } from "wagmi/actions";
import { config } from "@/app/Web3Provider";
import { trackEvent } from "@/lib/analytics";
import { ANALYTICS_EVENT_NAMES } from "@/lib/types.d";
import { wrappedWaitForTransactionReceipt } from "@/lib/utils";

const useAdvancedVoting = ({
proposalId,
Expand All @@ -25,7 +24,7 @@ const useAdvancedVoting = ({
params?: `0x${string}`;
missingVote: MissingVote;
}) => {
const { contracts, slug } = Tenant.current();
const { contracts } = Tenant.current();
const { address } = useAccount();
const { writeContractAsync: advancedVote, isError: _advancedVoteError } =
useWriteContract();
Expand Down Expand Up @@ -70,8 +69,9 @@ const useAdvancedVoting = ({
chainId: contracts.governor.chain.id,
});
try {
const { status } = await waitForTransactionReceipt(config, {
const { status } = await wrappedWaitForTransactionReceipt({
hash: directTx,
address: address as `0x${string}`,
});
if (status === "success") {
await trackEvent({
Expand Down Expand Up @@ -113,8 +113,9 @@ const useAdvancedVoting = ({
chainId: contracts.alligator?.chain.id,
});
try {
const { status } = await waitForTransactionReceipt(config, {
const { status } = await wrappedWaitForTransactionReceipt({
hash: advancedTx,
address: address as `0x${string}`,
});
if (status === "success") {
await trackEvent({
Expand Down
12 changes: 5 additions & 7 deletions src/hooks/useStandardVoting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ import { MissingVote } from "@/lib/voteUtils";
import { useCallback, useState } from "react";
import { useWriteContract } from "wagmi";
import Tenant from "@/lib/tenant/tenant";
import { waitForTransactionReceipt } from "wagmi/actions";
import { config } from "@/app/Web3Provider";
import { trackEvent } from "@/lib/analytics";
import { useAccount } from "wagmi";
import { ANALYTICS_EVENT_NAMES } from "@/lib/types.d";
import { wrappedWaitForTransactionReceipt } from "@/lib/utils";

const useStandardVoting = ({
proposalId,
Expand All @@ -21,7 +20,7 @@ const useStandardVoting = ({
params?: `0x${string}`;
missingVote: MissingVote;
}) => {
const { contracts, slug } = Tenant.current();
const { contracts } = Tenant.current();
const { address } = useAccount();
const { writeContractAsync: standardVote, isError: _standardVoteError } =
useWriteContract();
Expand All @@ -33,9 +32,7 @@ const useStandardVoting = ({
const [standardTxHash, setStandardTxHash] = useState<string | undefined>(
undefined
);
const [advancedTxHash, setAdvancedTxHash] = useState<string | undefined>(
undefined
);
const [advancedTxHash] = useState<string | undefined>(undefined);

const write = useCallback(() => {
const _standardVote = async () => {
Expand All @@ -50,8 +47,9 @@ const useStandardVoting = ({
chainId: contracts.governor.chain.id,
});
try {
const { status } = await waitForTransactionReceipt(config, {
const { status } = await wrappedWaitForTransactionReceipt({
hash: directTx,
address: address as `0x${string}`,
});

if (status === "success") {
Expand Down
224 changes: 224 additions & 0 deletions src/lib/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
import { describe, it, expect, vi, beforeEach, afterAll } from "vitest";
import { resolveSafeTx, wrappedWaitForTransactionReceipt } from "../utils";
import { mainnet } from "viem/chains";
import { getPublicClient } from "../viem";

vi.mock("next/font/google", () => ({
Inter: () => ({
style: { fontFamily: "Inter" },
}),
Rajdhani: () => ({
style: { fontFamily: "Rajdhani" },
}),
Chivo_Mono: () => ({
style: { fontFamily: "ChivoMono" },
}),
}));

vi.mock(import("react"), async (importOriginal) => {
const actual = await importOriginal();
return {
...actual,
cache: (fn: any) => fn,
};
});

vi.mock("server-only", () => ({
default: {},
}));

vi.mock("../tenant/tenant", () => ({
default: {
current: () => ({
namespace: "ens",
contracts: {
token: {
chain: {
id: 1,
},
},
},
ui: {
toggle: vi.fn(),
},
}),
},
}));

vi.mock("viem", async (importOriginal) => {
const actual = await importOriginal();
return {
...(actual as any),
createPublicClient: vi.fn(),
http: vi.fn(),
};
});

vi.mock("../viem", () => ({
getPublicClient: vi.fn(),
}));

const originalFetch = global.fetch;
vi.stubGlobal("fetch", vi.fn());

describe("Safe Transaction Utils", () => {
beforeEach(() => {
vi.resetAllMocks();
global.fetch = vi.fn();
});

afterAll(() => {
global.fetch = originalFetch;
});

describe("resolveSafeTx", () => {
it("should return transaction hash when safe transaction is successful", async () => {
const mockResponse = {
isSuccessful: true,
transactionHash: "0xsuccesshash" as `0x${string}`,
};

(global.fetch as any).mockResolvedValueOnce({
status: 200,
json: () => Promise.resolve(mockResponse),
});

const result = await resolveSafeTx(
mainnet.id,
"0xsafetxhash" as `0x${string}`
);

expect(result).toBe("0xsuccesshash");
expect(global.fetch).toHaveBeenCalledWith(
"https://safe-transaction-mainnet.safe.global/api/v1/multisig-transactions/0xsafetxhash"
);
});

it("should return undefined when safe transaction is not successful", async () => {
const mockResponse = {
isSuccessful: false,
};

(global.fetch as any).mockResolvedValueOnce({
status: 200,
json: () => Promise.resolve(mockResponse),
});

const result = await resolveSafeTx(
mainnet.id,
"0xsafetxhash" as `0x${string}`
);

expect(result).toBeUndefined();
});

it("should return original hash when transaction is not found (404)", async () => {
(global.fetch as any).mockResolvedValueOnce({
status: 404,
json: () => Promise.resolve({}),
});

const safeTxHash = "0xsafetxhash" as `0x${string}`;
const result = await resolveSafeTx(mainnet.id, safeTxHash);

expect(result).toBe(safeTxHash);
});
});

describe("wrappedWaitForTransactionReceipt", () => {
beforeEach(() => {
vi.resetAllMocks();
});

it("should handle regular (non-safe) transactions", async () => {
const mockPublicClient = {
chain: { id: 1 },
transport: {
request: vi.fn(({ method }) => {
if (method === "eth_getCode") {
return Promise.resolve("0x");
}
return Promise.resolve(null);
}),
},
getCode: vi.fn().mockResolvedValue("0x"),
waitForTransactionReceipt: vi
.fn()
.mockResolvedValue({ status: "success" }),
};

(getPublicClient as any).mockReturnValue(mockPublicClient);

const params = {
hash: "0xtxhash" as `0x${string}`,
address: "0xaddress" as `0x${string}`,
};

const result = await wrappedWaitForTransactionReceipt(params);

expect(mockPublicClient.waitForTransactionReceipt).toHaveBeenCalledWith(
params
);
expect(result).toEqual({ status: "success" });
});

it("should handle safe transactions", async () => {
const mockPublicClient = {
chain: { id: 1 },
transport: {
request: vi.fn(({ method }) => {
if (method === "eth_getCode") {
return Promise.resolve("0xcontractcode");
}
return Promise.resolve(null);
}),
},
getCode: vi.fn().mockResolvedValue("0xcontractcode"),
waitForTransactionReceipt: vi
.fn()
.mockResolvedValue({ status: "success" }),
};

(getPublicClient as any).mockReturnValue(mockPublicClient);

const mockResolvedTx = "0xresolvedtx" as `0x${string}`;
(global.fetch as any).mockResolvedValueOnce({
status: 200,
json: () =>
Promise.resolve({
isSuccessful: true,
transactionHash: mockResolvedTx,
}),
});

const params = {
hash: "0xsafetxhash" as `0x${string}`,
address: "0xaddress" as `0x${string}`,
};

const result = await wrappedWaitForTransactionReceipt(params);

expect(mockPublicClient.waitForTransactionReceipt).toHaveBeenCalledWith({
hash: mockResolvedTx,
});
expect(result).toEqual({ status: "success" });
});

it("should throw error when public client has no chain", async () => {
const mockPublicClient = {
chain: null,
};

(getPublicClient as any).mockReturnValue(mockPublicClient);

const params = {
hash: "0xtxhash" as `0x${string}`,
address: "0xaddress" as `0x${string}`,
};

await expect(wrappedWaitForTransactionReceipt(params)).rejects.toThrow(
"no chain on public client"
);
});
});
});
Loading
Loading