Skip to content

Commit

Permalink
fix: PR feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolasbrugneaux committed Dec 19, 2024
1 parent 6df3373 commit 61b9025
Show file tree
Hide file tree
Showing 6 changed files with 112 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,56 @@

exports[`fetchThresholds > fetches the constitution threshholds properly #2 1`] = `
[
0.6,
0.5,
0.5,
0.5,
0.9,
0.9,
0.9,
0.9,
0.5,
0.8,
0.9,
0.5,
0.9,
0.9,
0.9,
0.8,
0.9,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.9,
0.9,
0.5,
0.5,
0.5,
0.5,
0.8,
0.9,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
0.5,
]
`;

Expand Down Expand Up @@ -60,16 +109,3 @@ exports[`fetchThresholds > fetches the constitution threshholds properly #2 2`]
0.5,
]
`;

exports[`useParticipationParameters > fetches the params from the governance contract 1`] = `
{
"data": {
"baseline": 0.06,
"baselineFloor": 0.05,
"baselineQuorumFactor": 0.5,
"baselineUpdateFactor": 0.2,
},
"error": undefined,
"isLoading": undefined,
}
`;
12 changes: 6 additions & 6 deletions src/features/governance/hooks/useGovernanceProposals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
VoteType,
} from 'src/features/governance/types';
import { logger } from 'src/utils/logger';
import getRuntimeBlockNumber from 'src/utils/runtimeBlockNumber';
import getRuntimeBlock from 'src/utils/runtimeBlock';
import { PublicClient, encodeEventTopics } from 'viem';
import { usePublicClient } from 'wagmi';

Expand Down Expand Up @@ -74,7 +74,7 @@ type VoteTotalsRaw = [bigint, bigint, bigint];
export async function fetchGovernanceProposals(publicClient: PublicClient): Promise<Proposal[]> {
// Get queued and dequeued proposals
const [queued, dequeued] = await publicClient.multicall({
blockNumber: getRuntimeBlockNumber(),
...getRuntimeBlock(),
contracts: [
{
address: Addresses.Governance,
Expand Down Expand Up @@ -104,7 +104,7 @@ export async function fetchGovernanceProposals(publicClient: PublicClient): Prom
if (!allIdsAndUpvotes.length) return [];

const properties = await publicClient.multicall({
blockNumber: getRuntimeBlockNumber(),
...getRuntimeBlock(),
contracts: allIdsAndUpvotes.map(
(p) =>
({
Expand All @@ -117,7 +117,7 @@ export async function fetchGovernanceProposals(publicClient: PublicClient): Prom
});

const stages = await publicClient.multicall({
blockNumber: getRuntimeBlockNumber(),
...getRuntimeBlock(),
contracts: allIdsAndUpvotes.map(
(p) =>
({
Expand All @@ -130,7 +130,7 @@ export async function fetchGovernanceProposals(publicClient: PublicClient): Prom
});

const votes = await publicClient.multicall({
blockNumber: getRuntimeBlockNumber(),
...getRuntimeBlock(),
contracts: allIdsAndUpvotes.map(
(p) =>
({
Expand Down Expand Up @@ -231,7 +231,7 @@ export function mergeProposalsWithMetadata(
if (metadataIndex >= 0) {
// Remove the metadata element
const metadata = sortedMetadata.splice(metadataIndex, 1)[0];
// For some reason for re-submitted proposals that eventually, the
// For some reason for re-submitted proposals that eventually pass, the
// expired failed proposal on chain is still expired, use the metadata
// and trust `executedIds` events
if (metadata.id && executedIds.includes(metadata.id)) {
Expand Down
49 changes: 42 additions & 7 deletions src/features/governance/hooks/useProposalQuorum.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import '@testing-library/jest-dom';
import { waitFor } from '@testing-library/react';
import BigNumber from 'bignumber.js';
import { afterEach, beforeEach } from 'node:test';
import { toFixidity } from 'src/utils/numbers';
import { describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { publicArchiveClient, renderHook } from '../../../test/anvil/utils';
import {
extractFunctionSignature,
Expand All @@ -17,6 +16,9 @@ beforeEach(() => {
...(await importActual()),
usePublicClient: () => publicArchiveClient,
useReadContract: vi.fn(() => ({
// Mocks the following:
// abi: governanceABI,
// functionName: 'getParticipationParameters',
data: [
60000000000000000000000n, // baseline
50000000000000000000000n, // baselineFloor
Expand All @@ -39,19 +41,26 @@ describe('extractFunctionSignature', () => {
});

describe('fetchThresholds', () => {
it('fetches the constitution threshholds properly #2', async () => {
// Check for data sanity at known blocks for known proposals
// in this case the proposal#195 at block 0x1bb55ea
it('fetches the constitution threshholds properly #1', async () => {
// Proposal for Creation of Celo Governance Guild's execution block - 1
process.env.NEXT_PUBLIC_FORK_BLOCK_NUMBER = '0x1bb55ea';
const expectedNumberOfTxs = 1n;
const proposalId = 195;
const spy = vi.spyOn(publicArchiveClient, 'multicall');
await expect(
fetchThresholds(publicArchiveClient, proposalId, expectedNumberOfTxs),
).resolves.toMatchSnapshot();
await expect(fetchThresholds(publicArchiveClient, proposalId, expectedNumberOfTxs)).resolves
.toMatchInlineSnapshot(`
[
0.6,
]
`);
expect(spy.mock.results[0].value).resolves.toHaveLength(Number(expectedNumberOfTxs));
expect(spy.mock.calls.length).toBe(2);
});

// Check for data sanity at known blocks for known proposals
// in this case the proposal#16 at block 0x1baa98c
it('fetches the constitution threshholds properly #2', async () => {
// Enabling MENTO Governance's proposal block
process.env.NEXT_PUBLIC_FORK_BLOCK_NUMBER = '0x1baa98c';
Expand All @@ -70,11 +79,37 @@ describe('useParticipationParameters', () => {
it('fetches the params from the governance contract', async () => {
const { result } = renderHook(() => useParticipationParameters());
await waitFor(() => expect(result.current.isLoading).not.toBe(true));
expect(result.current).toMatchSnapshot();
expect(result.current).toMatchInlineSnapshot(`
{
"data": {
"baseline": 0.06,
"baselineFloor": 0.05,
"baselineQuorumFactor": 0.5,
"baselineUpdateFactor": 0.2,
},
"error": undefined,
"isLoading": undefined,
}
`);
});
});

describe('useProposalQuorum', () => {
/*
This test makes sure the calculation is correct
following these two solidity functions:
- https://github.com/celo-org/celo-monorepo/blob/master/packages/protocol/contracts/governance/Governance.sol#L1567
- https://github.com/celo-org/celo-monorepo/blob/master/packages/protocol/contracts/governance/Proposals.sol#L195-L211
Let:
- baseline and baselineQuorumFactor are part of the `getParticipationParameters` results
- quorumVotes = proposal.networkWeight * baseline * baselineQuorumFactor
- thresholds = the array of `getConstitutionContract` results corresponding of each transaction of a proposal
- maxThreshold = the highest thresholds in the above array
The quorum to "beat" should be:
- maxThreshold * quorumVotes where
*/
it('maths properly', async () => {
// Enabling MENTO Governance's proposal block
process.env.NEXT_PUBLIC_FORK_BLOCK_NUMBER = '0x1baa98c';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { Addresses } from 'src/config/contracts';
import { MergedProposalData } from 'src/features/governance/hooks/useGovernanceProposals';
import { Proposal } from 'src/features/governance/types';
import { fromFixidity } from 'src/utils/numbers';
import getRuntimeBlockNumber from 'src/utils/runtimeBlockNumber';
import { PublicClient } from 'viem';
import getRuntimeBlock from 'src/utils/runtimeBlock';
import { fromHex, PublicClient, toHex } from 'viem';
import { usePublicClient, useReadContract } from 'wagmi';

interface ParticipationParameters {
Expand Down Expand Up @@ -49,7 +49,7 @@ export function useParticipationParameters(): {
error: Error | null;
} {
const { data, isLoading, error } = useReadContract({
blockNumber: getRuntimeBlockNumber(),
...getRuntimeBlock(),
address: Addresses.Governance,
abi: governanceABI,
functionName: 'getParticipationParameters',
Expand Down Expand Up @@ -109,7 +109,7 @@ export async function fetchThresholds(
} as const;

const results = await publicClient?.multicall({
blockNumber: getRuntimeBlockNumber(),
...getRuntimeBlock(),
allowFailure: false,
contracts: txIds.map((txId: number) => ({
...getProposalTransactionContract,
Expand All @@ -130,7 +130,7 @@ export async function fetchThresholds(
} as const;

const thresholds = await publicClient?.multicall({
blockNumber: getRuntimeBlockNumber(),
...getRuntimeBlock(),
allowFailure: false,
contracts: results.map(([_value, destination, data]) => {
const functionId = extractFunctionSignature(data);
Expand All @@ -155,6 +155,7 @@ export async function fetchThresholds(
* https://github.com/celo-org/celo-monorepo/blob/master/packages/protocol/contracts/common/ExtractFunctionSignature.sol#L9
*/
export function extractFunctionSignature(input: `0x${string}`): `0x${string}` {
const data = Buffer.from(input.replace('0x', ''), 'hex');
return `0x${data.subarray(0, 4).toString('hex')}`;
if (!input.startsWith('0x')) input = `0x${input}`;
const data = fromHex(input, { to: 'bytes' });
return toHex(data.subarray(0, 4));
}
6 changes: 6 additions & 0 deletions src/utils/runtimeBlock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default function getRuntimeBlock(): { blockNumber: bigint } | { blockTag: 'latest' } {
if (process.env.NODE_ENV !== 'production' && process.env.NEXT_PUBLIC_FORK_BLOCK_NUMBER) {
return { blockNumber: BigInt(process.env.NEXT_PUBLIC_FORK_BLOCK_NUMBER) };
}
return { blockTag: 'latest' };
}
8 changes: 0 additions & 8 deletions src/utils/runtimeBlockNumber.ts

This file was deleted.

0 comments on commit 61b9025

Please sign in to comment.