fix(2286): remove usage all votes (#2385)

* chore: remove instances of calling all user votes

* chore: remove console.log

* test: fix tests

* chore: fix test types
This commit is contained in:
Dexter Edwards 2022-12-13 13:53:00 +00:00 committed by GitHub
parent c14e57cfd5
commit 48e0cf0808
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 159 additions and 240 deletions

View File

@ -68,14 +68,12 @@ it('Proposal open - renders will fail state if the proposal will fail', async ()
__typename: 'ProposalVoteSide',
totalNumber: '0',
totalTokens: '0',
votes: null,
totalEquityLikeShareWeight: '0',
},
no: {
__typename: 'ProposalVoteSide',
totalNumber: '0',
totalTokens: '0',
votes: null,
totalEquityLikeShareWeight: '0',
},
},
@ -128,14 +126,12 @@ it('Proposal waiting for node vote - will pass - renders if the vote will pass
__typename: 'ProposalVoteSide',
totalNumber: '0',
totalTokens: '0',
votes: null,
totalEquityLikeShareWeight: '0',
},
no: {
__typename: 'ProposalVoteSide',
totalNumber: '0',
totalTokens: '0',
votes: null,
totalEquityLikeShareWeight: '0',
},
},
@ -225,14 +221,12 @@ it('Proposal failed - renders participation not met if participation is not met'
__typename: 'ProposalVoteSide',
totalNumber: '0',
totalTokens: '0',
votes: null,
totalEquityLikeShareWeight: '0',
},
no: {
__typename: 'ProposalVoteSide',
totalNumber: '0',
totalTokens: '0',
votes: null,
totalEquityLikeShareWeight: '0',
},
},
@ -258,14 +252,12 @@ it('Proposal failed - renders majority not met if majority is not met', async ()
__typename: 'ProposalVoteSide',
totalNumber: '0',
totalTokens: '0',
votes: null,
totalEquityLikeShareWeight: '0',
},
no: {
__typename: 'ProposalVoteSide',
totalNumber: '1',
totalTokens: '25242474195500835440000',
votes: null,
totalEquityLikeShareWeight: '0',
},
},

View File

@ -1,6 +1,7 @@
import { BrowserRouter as Router } from 'react-router-dom';
import { AppStateProvider } from '../../../../contexts/app-state/app-state-provider';
import { VegaWalletContext } from '@vegaprotocol/wallet';
import type { MockedResponse } from '@apollo/client/testing';
import { MockedProvider } from '@apollo/client/testing';
import { render, screen } from '@testing-library/react';
import { format } from 'date-fns';
@ -27,14 +28,48 @@ import {
nextWeek,
} from '../../test-helpers/mocks';
import type { ProposalQuery } from '../../proposal/__generated__/Proposal';
import { UserVoteDocument } from '../vote-details/__generated__/Vote';
import faker from 'faker';
const createUserVoteQueryMock = (
proposalId: string | undefined | null,
value: VoteValue
) => ({
request: {
query: UserVoteDocument,
variables: {
partyId: mockPubkey.publicKey,
},
},
result: {
data: {
party: {
votesConnection: {
edges: [
{
node: {
proposalId,
vote: {
value,
datetime: faker.date.past().toISOString(),
},
},
},
],
},
},
},
},
});
const renderComponent = (
proposal: ProposalQuery['proposal'],
mock = networkParamsQueryMock
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mocks: MockedResponse<any>[] = [networkParamsQueryMock]
) =>
render(
<Router>
<MockedProvider mocks={[mock]}>
<MockedProvider mocks={mocks}>
<AppStateProvider>
<VegaWalletContext.Provider value={mockWalletContext}>
<ProposalsListItemDetails proposal={proposal} />
@ -146,76 +181,38 @@ describe('Proposals list item details', () => {
);
});
it('Renders proposal state: Open - user voted for', () => {
renderComponent(
generateProposal({
state: ProposalState.STATE_OPEN,
votes: {
__typename: 'ProposalVotes',
yes: {
votes: [
{
__typename: 'Vote',
value: VoteValue.VALUE_YES,
datetime: lastWeek.toString(),
party: {
__typename: 'Party',
id: mockPubkey.publicKey,
stakingSummary: {
__typename: 'StakingSummary',
currentStakeAvailable: '1000',
},
},
},
],
},
no: generateNoVotes(0),
},
terms: {
closingDatetime: nextWeek.toString(),
},
})
);
it('Renders proposal state: Open - user voted for', async () => {
const proposal = generateProposal({
state: ProposalState.STATE_OPEN,
terms: {
closingDatetime: nextWeek.toString(),
},
});
renderComponent(proposal, [
networkParamsQueryMock,
createUserVoteQueryMock(proposal?.id, VoteValue.VALUE_YES),
]);
screen.debug();
expect(screen.getByTestId('proposal-status')).toHaveTextContent('Open');
expect(screen.getByTestId('vote-details')).toHaveTextContent(
'You voted For'
);
expect(await screen.findByText('You voted')).toBeInTheDocument();
expect(await screen.findByText('For')).toBeInTheDocument();
});
it('Renders proposal state: Open - user voted against', () => {
renderComponent(
generateProposal({
state: ProposalState.STATE_OPEN,
votes: {
__typename: 'ProposalVotes',
no: {
votes: [
{
__typename: 'Vote',
value: VoteValue.VALUE_NO,
datetime: lastWeek.toString(),
party: {
__typename: 'Party',
id: mockPubkey.publicKey,
stakingSummary: {
__typename: 'StakingSummary',
currentStakeAvailable: '1000',
},
},
},
],
},
yes: generateYesVotes(0),
},
terms: {
closingDatetime: nextWeek.toString(),
},
})
);
it('Renders proposal state: Open - user voted against', async () => {
const proposal = generateProposal({
state: ProposalState.STATE_OPEN,
terms: {
closingDatetime: nextWeek.toString(),
},
});
renderComponent(proposal, [
networkParamsQueryMock,
createUserVoteQueryMock(proposal?.id, VoteValue.VALUE_NO),
]);
expect(screen.getByTestId('proposal-status')).toHaveTextContent('Open');
expect(screen.getByTestId('vote-details')).toHaveTextContent(
'You voted Against'
);
expect(await screen.findByText('You voted')).toBeInTheDocument();
expect(await screen.findByText('Against')).toBeInTheDocument();
});
it('Renders proposal state: Open - participation not reached', () => {

View File

@ -46,12 +46,7 @@ export const ProposalsListItemDetails = ({
proposal,
});
const { t } = useTranslation();
const { voteState } = useUserVote(
proposal?.id ?? '',
proposal?.votes.yes.votes ?? null,
proposal?.votes.no.votes ?? null
);
const { voteState } = useUserVote(proposal?.id);
let proposalStatus: ReactNode;
let voteDetails: ReactNode;
let voteStatus: ReactNode;

View File

@ -0,0 +1,15 @@
query UserVote($partyId: ID!) {
party(id: $partyId) {
votesConnection {
edges {
node {
proposalId
vote {
value
datetime
}
}
}
}
}
}

View File

@ -0,0 +1,58 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type UserVoteQueryVariables = Types.Exact<{
partyId: Types.Scalars['ID'];
}>;
export type UserVoteQuery = { __typename?: 'Query', party?: { __typename?: 'Party', votesConnection?: { __typename?: 'ProposalVoteConnection', edges?: Array<{ __typename?: 'ProposalVoteEdge', node: { __typename?: 'ProposalVote', proposalId: string, vote: { __typename?: 'Vote', value: Types.VoteValue, datetime: any } } }> | null } | null } | null };
export const UserVoteDocument = gql`
query UserVote($partyId: ID!) {
party(id: $partyId) {
votesConnection {
edges {
node {
proposalId
vote {
value
datetime
}
}
}
}
}
}
`;
/**
* __useUserVoteQuery__
*
* To run a query within a React component, call `useUserVoteQuery` and pass it any options that fit your needs.
* When your component renders, `useUserVoteQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useUserVoteQuery({
* variables: {
* partyId: // value for 'partyId'
* },
* });
*/
export function useUserVoteQuery(baseOptions: Apollo.QueryHookOptions<UserVoteQuery, UserVoteQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<UserVoteQuery, UserVoteQueryVariables>(UserVoteDocument, options);
}
export function useUserVoteLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<UserVoteQuery, UserVoteQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<UserVoteQuery, UserVoteQueryVariables>(UserVoteDocument, options);
}
export type UserVoteQueryHookResult = ReturnType<typeof useUserVoteQuery>;
export type UserVoteLazyQueryHookResult = ReturnType<typeof useUserVoteLazyQuery>;
export type UserVoteQueryResult = Apollo.QueryResult<UserVoteQuery, UserVoteQueryVariables>;

View File

@ -1,51 +0,0 @@
import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type VoteButtonsQueryVariables = Types.Exact<{
partyId: Types.Scalars['ID'];
}>;
export type VoteButtonsQuery = { __typename?: 'Query', party?: { __typename?: 'Party', id: string, stakingSummary: { __typename?: 'StakingSummary', currentStakeAvailable: string } } | null };
export const VoteButtonsDocument = gql`
query VoteButtons($partyId: ID!) {
party(id: $partyId) {
id
stakingSummary {
currentStakeAvailable
}
}
}
`;
/**
* __useVoteButtonsQuery__
*
* To run a query within a React component, call `useVoteButtonsQuery` and pass it any options that fit your needs.
* When your component renders, `useVoteButtonsQuery` returns an object from Apollo Client that contains loading, error, and data properties
* you can use to render your UI.
*
* @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
*
* @example
* const { data, loading, error } = useVoteButtonsQuery({
* variables: {
* partyId: // value for 'partyId'
* },
* });
*/
export function useVoteButtonsQuery(baseOptions: Apollo.QueryHookOptions<VoteButtonsQuery, VoteButtonsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useQuery<VoteButtonsQuery, VoteButtonsQueryVariables>(VoteButtonsDocument, options);
}
export function useVoteButtonsLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<VoteButtonsQuery, VoteButtonsQueryVariables>) {
const options = {...defaultOptions, ...baseOptions}
return Apollo.useLazyQuery<VoteButtonsQuery, VoteButtonsQueryVariables>(VoteButtonsDocument, options);
}
export type VoteButtonsQueryHookResult = ReturnType<typeof useVoteButtonsQuery>;
export type VoteButtonsLazyQueryHookResult = ReturnType<typeof useVoteButtonsLazyQuery>;
export type VoteButtonsQueryResult = Apollo.QueryResult<VoteButtonsQuery, VoteButtonsQueryVariables>;

View File

@ -2,7 +2,9 @@ import { captureMessage } from '@sentry/minimal';
import { useVegaWallet } from '@vegaprotocol/wallet';
import { VoteValue } from '@vegaprotocol/types';
import { useEffect, useMemo, useState } from 'react';
import { useEffect, useState } from 'react';
import { useUserVoteQuery } from './__generated__/Vote';
import { removePaginationWrapper } from '@vegaprotocol/react-helpers';
export enum VoteState {
NotCast = 'NotCast',
@ -37,28 +39,21 @@ export function getUserVote(pubkey: string, yesVotes?: Votes, noVotes?: Votes) {
* Finds the status of a users given vote in a given proposal and provides
* a function to send a vote transaction to your wallet
*/
export function useUserVote(
proposalId: string | null,
yesVotes: Votes | null,
noVotes: Votes | null
) {
export function useUserVote(proposalId: string | null | undefined) {
const { pubKey } = useVegaWallet();
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const [timeout, setTimeoutValue] = useState<any>(null);
const yes = useMemo(() => yesVotes || [], [yesVotes]);
const no = useMemo(() => noVotes || [], [noVotes]);
const [voteState, setVoteState] = useState<VoteState | null>(
VoteState.NotCast
);
const { data } = useUserVoteQuery({
variables: { partyId: pubKey || '' },
skip: !pubKey || !proposalId,
});
// Find the users vote everytime yes or no votes change
const userVote = useMemo(() => {
if (pubKey) {
return getUserVote(pubKey, yes, no);
}
return null;
}, [pubKey, yes, no]);
const userVote = removePaginationWrapper(
data?.party?.votesConnection?.edges
).find(({ proposalId: pId }) => proposalId === pId);
// If user vote changes update the vote state
useEffect(() => {
@ -66,7 +61,9 @@ export function useUserVote(
setVoteState(VoteState.NotCast);
} else {
setVoteState(
userVote.value === VoteValue.VALUE_YES ? VoteState.Yes : VoteState.No
userVote.vote.value === VoteValue.VALUE_YES
? VoteState.Yes
: VoteState.No
);
}
}, [userVote]);
@ -90,6 +87,6 @@ export function useUserVote(
return {
voteState,
userVote,
voteDatetime: userVote ? new Date(userVote.datetime) : null,
voteDatetime: userVote ? new Date(userVote.vote.datetime) : null,
};
}

View File

@ -15,7 +15,7 @@ import { DATE_FORMAT_LONG } from '../../../../lib/date-formats';
import { VoteState } from './use-user-vote';
import { ProposalMinRequirements, ProposalUserAction } from '../shared';
import { VoteTransactionDialog } from './vote-transaction-dialog';
import { useVoteButtonsQuery } from './__generated___/Stake';
import { useVoteButtonsQuery } from './__generated__/Stake';
interface VoteButtonsContainerProps {
voteState: VoteState | null;

View File

@ -43,11 +43,7 @@ export const VoteDetails = ({
} = useVoteInformation({ proposal });
const { t } = useTranslation();
const { voteState, voteDatetime } = useUserVote(
proposal?.id ?? '',
proposal?.votes.yes.votes ?? null,
proposal?.votes.no.votes ?? null
);
const { voteState, voteDatetime } = useUserVote(proposal?.id);
const defaultDecimals = 2;
const daysLeft = t('daysLeft', {
daysLeft: formatDistanceToNow(new Date(proposal?.terms.closingDatetime)),

View File

@ -288,31 +288,11 @@ query Proposal($proposalId: ID!) {
totalTokens
totalNumber
totalEquityLikeShareWeight
votes {
value
party {
id
stakingSummary {
currentStakeAvailable
}
}
datetime
}
}
no {
totalTokens
totalNumber
totalEquityLikeShareWeight
votes {
value
party {
id
stakingSummary {
currentStakeAvailable
}
}
datetime
}
}
}
}

File diff suppressed because one or more lines are too long

View File

@ -70,31 +70,11 @@ fragment ProposalFields on Proposal {
totalTokens
totalNumber
totalEquityLikeShareWeight
votes {
value
party {
id
stakingSummary {
currentStakeAvailable
}
}
datetime
}
}
no {
totalTokens
totalNumber
totalEquityLikeShareWeight
votes {
value
party {
id
stakingSummary {
currentStakeAvailable
}
}
datetime
}
}
}
}

View File

@ -3,12 +3,12 @@ import * as Types from '@vegaprotocol/types';
import { gql } from '@apollo/client';
import * as Apollo from '@apollo/client';
const defaultOptions = {} as const;
export type ProposalFieldsFragment = { __typename?: 'Proposal', id?: string | null, reference: string, state: Types.ProposalState, datetime: any, rejectionReason?: Types.ProposalRejectionReason | null, errorDetails?: string | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string }, party: { __typename?: 'Party', id: string }, terms: { __typename?: 'ProposalTerms', closingDatetime: any, enactmentDatetime?: any | null, change: { __typename: 'NewAsset', name: string, symbol: string, decimals: number, quantum: string, source: { __typename?: 'BuiltinAsset', maxFaucetAmountMint: string } | { __typename?: 'ERC20', contractAddress: string, withdrawThreshold: string, lifetimeLimit: string } } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket', instrument: { __typename?: 'InstrumentConfiguration', name: string, code: string, futureProduct?: { __typename?: 'FutureProduct', settlementAsset: { __typename?: 'Asset', symbol: string } } | null } } | { __typename?: 'UpdateAsset', quantum: string, assetId: string, source: { __typename?: 'UpdateERC20', lifetimeLimit: string, withdrawThreshold: string } } | { __typename?: 'UpdateMarket', marketId: string } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } }, votes: { __typename?: 'ProposalVotes', yes: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string, votes?: Array<{ __typename?: 'Vote', value: Types.VoteValue, datetime: any, party: { __typename?: 'Party', id: string, stakingSummary: { __typename?: 'StakingSummary', currentStakeAvailable: string } } }> | null }, no: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string, votes?: Array<{ __typename?: 'Vote', value: Types.VoteValue, datetime: any, party: { __typename?: 'Party', id: string, stakingSummary: { __typename?: 'StakingSummary', currentStakeAvailable: string } } }> | null } } };
export type ProposalFieldsFragment = { __typename?: 'Proposal', id?: string | null, reference: string, state: Types.ProposalState, datetime: any, rejectionReason?: Types.ProposalRejectionReason | null, errorDetails?: string | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string }, party: { __typename?: 'Party', id: string }, terms: { __typename?: 'ProposalTerms', closingDatetime: any, enactmentDatetime?: any | null, change: { __typename: 'NewAsset', name: string, symbol: string, decimals: number, quantum: string, source: { __typename?: 'BuiltinAsset', maxFaucetAmountMint: string } | { __typename?: 'ERC20', contractAddress: string, withdrawThreshold: string, lifetimeLimit: string } } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket', instrument: { __typename?: 'InstrumentConfiguration', name: string, code: string, futureProduct?: { __typename?: 'FutureProduct', settlementAsset: { __typename?: 'Asset', symbol: string } } | null } } | { __typename?: 'UpdateAsset', quantum: string, assetId: string, source: { __typename?: 'UpdateERC20', lifetimeLimit: string, withdrawThreshold: string } } | { __typename?: 'UpdateMarket', marketId: string } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } }, votes: { __typename?: 'ProposalVotes', yes: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string }, no: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string } } };
export type ProposalsQueryVariables = Types.Exact<{ [key: string]: never; }>;
export type ProposalsQuery = { __typename?: 'Query', proposalsConnection?: { __typename?: 'ProposalsConnection', edges?: Array<{ __typename?: 'ProposalEdge', node: { __typename?: 'Proposal', id?: string | null, reference: string, state: Types.ProposalState, datetime: any, rejectionReason?: Types.ProposalRejectionReason | null, errorDetails?: string | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string }, party: { __typename?: 'Party', id: string }, terms: { __typename?: 'ProposalTerms', closingDatetime: any, enactmentDatetime?: any | null, change: { __typename: 'NewAsset', name: string, symbol: string, decimals: number, quantum: string, source: { __typename?: 'BuiltinAsset', maxFaucetAmountMint: string } | { __typename?: 'ERC20', contractAddress: string, withdrawThreshold: string, lifetimeLimit: string } } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket', instrument: { __typename?: 'InstrumentConfiguration', name: string, code: string, futureProduct?: { __typename?: 'FutureProduct', settlementAsset: { __typename?: 'Asset', symbol: string } } | null } } | { __typename?: 'UpdateAsset', quantum: string, assetId: string, source: { __typename?: 'UpdateERC20', lifetimeLimit: string, withdrawThreshold: string } } | { __typename?: 'UpdateMarket', marketId: string } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } }, votes: { __typename?: 'ProposalVotes', yes: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string, votes?: Array<{ __typename?: 'Vote', value: Types.VoteValue, datetime: any, party: { __typename?: 'Party', id: string, stakingSummary: { __typename?: 'StakingSummary', currentStakeAvailable: string } } }> | null }, no: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string, votes?: Array<{ __typename?: 'Vote', value: Types.VoteValue, datetime: any, party: { __typename?: 'Party', id: string, stakingSummary: { __typename?: 'StakingSummary', currentStakeAvailable: string } } }> | null } } } } | null> | null } | null };
export type ProposalsQuery = { __typename?: 'Query', proposalsConnection?: { __typename?: 'ProposalsConnection', edges?: Array<{ __typename?: 'ProposalEdge', node: { __typename?: 'Proposal', id?: string | null, reference: string, state: Types.ProposalState, datetime: any, rejectionReason?: Types.ProposalRejectionReason | null, errorDetails?: string | null, rationale: { __typename?: 'ProposalRationale', title: string, description: string }, party: { __typename?: 'Party', id: string }, terms: { __typename?: 'ProposalTerms', closingDatetime: any, enactmentDatetime?: any | null, change: { __typename: 'NewAsset', name: string, symbol: string, decimals: number, quantum: string, source: { __typename?: 'BuiltinAsset', maxFaucetAmountMint: string } | { __typename?: 'ERC20', contractAddress: string, withdrawThreshold: string, lifetimeLimit: string } } | { __typename?: 'NewFreeform' } | { __typename?: 'NewMarket', instrument: { __typename?: 'InstrumentConfiguration', name: string, code: string, futureProduct?: { __typename?: 'FutureProduct', settlementAsset: { __typename?: 'Asset', symbol: string } } | null } } | { __typename?: 'UpdateAsset', quantum: string, assetId: string, source: { __typename?: 'UpdateERC20', lifetimeLimit: string, withdrawThreshold: string } } | { __typename?: 'UpdateMarket', marketId: string } | { __typename?: 'UpdateNetworkParameter', networkParameter: { __typename?: 'NetworkParameter', key: string, value: string } } }, votes: { __typename?: 'ProposalVotes', yes: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string }, no: { __typename?: 'ProposalVoteSide', totalTokens: string, totalNumber: string, totalEquityLikeShareWeight: string } } } } | null> | null } | null };
export const ProposalFieldsFragmentDoc = gql`
fragment ProposalFields on Proposal {
@ -83,31 +83,11 @@ export const ProposalFieldsFragmentDoc = gql`
totalTokens
totalNumber
totalEquityLikeShareWeight
votes {
value
party {
id
stakingSummary {
currentStakeAvailable
}
}
datetime
}
}
no {
totalTokens
totalNumber
totalEquityLikeShareWeight
votes {
value
party {
id
stakingSummary {
currentStakeAvailable
}
}
datetime
}
}
}
}