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

Remove rest of spock (WIP) #900

Merged
merged 17 commits into from
Sep 26, 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
5 changes: 3 additions & 2 deletions modules/address/components/AddressDelegatedTo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ const CollapsableRow = ({ delegate, network, bpi, totalDelegated }: CollapsableR
const { address, lockAmount, events } = delegate;
const sortedEvents = events.sort((prev, next) => (prev.blockTimestamp > next.blockTimestamp ? -1 : 1));

const hasExpiration = !!delegate.expirationDate;
const formattedDate = formatDateWithTime(delegate.expirationDate);
const dateText = delegate.isExpired
? `This contract expired ${formattedDate}`
Expand Down Expand Up @@ -125,11 +126,11 @@ const CollapsableRow = ({ delegate, network, bpi, totalDelegated }: CollapsableR
)}
</Flex>
</Box>
<Box as="td" sx={{ verticalAlign: 'top', pt: 2, display: bpi > 1 ? 'table-cell' : 'none' }}>
{hasExpiration && <Box as="td" sx={{ verticalAlign: 'top', pt: 2, display: bpi > 1 ? 'table-cell' : 'none' }}>
<Text variant="caps" sx={{ color: 'inherit' }}>
<DateWithHover label={dateText} date={delegate.expirationDate} />
</Text>
</Box>
</Box>}
<Box as="td" sx={{ textAlign: 'end', verticalAlign: 'top', width: '100%', pt: 2 }}>
<Box sx={{ height: '32px' }}>
<Flex
Expand Down
8 changes: 5 additions & 3 deletions modules/delegates/api/fetchChainDelegates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export async function fetchChainDelegates(
network: SupportedNetworks
): Promise<DelegateContractInformation[]> {
const chainId = networkNameToChainId(network);
const data = await gqlRequest({
const data = await gqlRequest({
chainId,
useSubgraph: true,
query: allDelegates
Expand All @@ -29,7 +29,9 @@ export async function fetchChainDelegates(
blockTimestamp: d.blockTimestamp,
address: d.ownerAddress,
voteDelegateAddress: d.id,
mkrDelegated: formatValue(BigNumber.from(d.totalDelegated), 'wad', 18, false)
}
mkrDelegated: formatValue(BigNumber.from(d.totalDelegated), 'wad', 18, false),
version: d.version,
lastVoteDate: d.voter?.lastVotedTimestamp ? Number(d.voter.lastVotedTimestamp) : null
};
});
}
12 changes: 7 additions & 5 deletions modules/delegates/api/fetchDelegatedTo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ export async function fetchDelegatedTo(
const delegatesData = await gqlRequest({
chainId,
useSubgraph: true,
query: allDelegates });
query: allDelegates
});
const delegates = delegatesData.delegates;

const res: MKRDelegatedToDAIResponse[] = data.delegationHistories.map(x => {
Expand Down Expand Up @@ -68,11 +69,12 @@ export async function fetchDelegatedTo(
const delegatingToWalletAddress = delegatingTo?.delegate?.toLowerCase();
// Get the expiration date of the delegate

const expirationDate = add(new Date(delegatingTo?.blockTimestamp * 1000), { years: 1 });
const expirationDate = add(new Date(Number(delegatingTo?.blockTimestamp) * 1000), { years: 1 });

const hasExpiration = delegatingTo?.version === '1';

//only v1 delegate contracts expire
const isAboutToExpire = delegatingTo.version === "1" && isAboutToExpireCheck(expirationDate);
const isExpired = delegatingTo.version === "1" && isExpiredCheck(expirationDate);
const isAboutToExpire = hasExpiration && isAboutToExpireCheck(expirationDate);
const isExpired = hasExpiration && isExpiredCheck(expirationDate);

// If it has a new owner address, check if it has renewed the contract
const newOwnerAddress = getNewOwnerFromPrevious(delegatingToWalletAddress as string, network);
Expand Down
84 changes: 42 additions & 42 deletions modules/delegates/api/fetchDelegates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,13 @@ import { ZERO_SLATE_HASH } from 'modules/executive/helpers/zeroSlateHash';
import { getSlateAddresses } from 'modules/executive/helpers/getSlateAddresses';
import { formatDelegationHistory } from 'modules/delegates/helpers/formatDelegationHistory';
import { CMSProposal } from 'modules/executive/types';
import { fetchLastPollVote } from 'modules/polling/api/fetchLastPollvote';
import { isAboutToExpireCheck } from 'modules/migration/helpers/expirationChecks';
import { getNewOwnerFromPrevious, getPreviousOwnerFromNew } from 'modules/migration/delegateAddressLinks';
import { allDelegatesCacheKey } from 'modules/cache/constants/cache-keys';
import { cacheGet, cacheSet } from 'modules/cache/cache';
import { TEN_MINUTES_IN_MS } from 'modules/app/constants/time';
import { gqlRequest } from 'modules/gql/gqlRequest';
import { delegatesQuery } from 'modules/gql/queries/delegates';
import { delegatesQuery } from 'modules/gql/queries/subgraph/delegates';
import { fetchDelegatesExecSupport } from './fetchDelegatesExecSupport';
import { fetchDelegateAddresses } from './fetchDelegateAddresses';
import getDelegatesCounts from '../helpers/getDelegatesCounts';
Expand All @@ -56,9 +55,13 @@ function mergeDelegateInfo({
previousOnChainDelegate?: DelegateContractInformation;
newOnChainDelegate?: DelegateContractInformation;
}): Delegate {
// check if contract is expired to assing the status
const expirationDate = add(new Date(onChainDelegate.blockTimestamp), { years: 1 });
const isExpired = isBefore(new Date(expirationDate), new Date());
// check if contract is expired to assess the status
const hasExpiration = onChainDelegate.version === '1';
const expirationDate = hasExpiration
? add(new Date(Number(onChainDelegate.blockTimestamp) * 1000), { years: 1 })
: null;

const isExpired = !!expirationDate && isBefore(new Date(expirationDate), new Date());

return {
voteDelegateAddress: onChainDelegate.voteDelegateAddress,
Expand All @@ -76,7 +79,7 @@ function mergeDelegateInfo({
picture: githubDelegate?.picture || '',
id: onChainDelegate.voteDelegateAddress,
externalUrl: githubDelegate?.externalUrl,
lastVoteDate: null,
lastVoteDate: onChainDelegate.lastVoteDate,
communication: githubDelegate?.communication,
combinedParticipation: githubDelegate?.combinedParticipation,
pollParticipation: githubDelegate?.pollParticipation,
Expand Down Expand Up @@ -241,8 +244,6 @@ export async function fetchDelegates(
delegateContractAddress.toLowerCase() === delegate.voteDelegateAddress.toLowerCase()
);

const lastVote = await fetchLastPollVote(delegate.voteDelegateAddress, currentNetwork);

return {
...delegate,
// Trim the description when fetching all the delegates
Expand All @@ -256,7 +257,7 @@ export async function fetchDelegates(
proposalBlurb: '...'
}
: undefined,
lastVoteDate: lastVote ? lastVote.blockTimestamp : null,
lastVoteDate: delegate.lastVoteDate ? delegate.lastVoteDate : null,
mkrLockedDelegate
};
})
Expand All @@ -268,7 +269,7 @@ export async function fetchDelegates(
const aSupport = a.mkrDelegated ? a.mkrDelegated : 0;
return new BigNumberJS(aSupport).gt(new BigNumberJS(bSupport)) ? -1 : 1;
} else if (sortBy === 'date') {
return a.expirationDate > b.expirationDate ? -1 : 1;
return a.blockTimestamp > b.blockTimestamp ? -1 : 1;
} else if (sortBy === 'delegators') {
const delegationHistoryA = formatDelegationHistory(a.mkrLockedDelegate);
const delegationHistoryB = formatDelegationHistory(b.mkrLockedDelegate);
Expand Down Expand Up @@ -444,7 +445,7 @@ export async function fetchDelegatesPaginated({
orderDirection,
seed,
delegateType,
searchTerm,
searchTerm
}: DelegatesValidatedQueryParams): Promise<DelegatesPaginatedAPIResponse> {
const chainId = networkNameToChainId(network);

Expand Down Expand Up @@ -473,13 +474,12 @@ export async function fetchDelegatesPaginated({
}
]
};
(searchTerm) &&
delegatesQueryFilter.and.push({ voteDelegate: { in: filteredDelegateAddresses } });
searchTerm && delegatesQueryFilter.and.push({ voteDelegate: { in: filteredDelegateAddresses } });
}

const delegatesQueryVariables = {
first: pageSize,
offset: (page - 1) * pageSize,
skip: (page - 1) * pageSize,
includeExpired,
orderBy,
orderDirection,
Expand All @@ -492,24 +492,23 @@ export async function fetchDelegatesPaginated({
delegatesQueryVariables['seed'] = seed;
}

const [githubExecutives, delegatesExecSupport, delegatesQueryRes, delegationMetrics] =
await Promise.all([
getGithubExecutives(network),
fetchDelegatesExecSupport(network),
gqlRequest<any>({
chainId,
query: delegatesQuery,
variables: delegatesQueryVariables
}),
fetchDelegationMetrics(network)
]);

const [githubExecutives, delegatesExecSupport, delegatesQueryRes, delegationMetrics] = await Promise.all([
getGithubExecutives(network),
fetchDelegatesExecSupport(network),
gqlRequest<any>({
chainId,
query: delegatesQuery,
useSubgraph: true,
variables: delegatesQueryVariables
}),
fetchDelegationMetrics(network)
]);
const delegatesData = {
paginationInfo: {
totalCount: delegatesQueryRes.delegates.totalCount,
page,
numPages: Math.ceil(delegatesQueryRes.delegates.totalCount / pageSize),
hasNextPage: delegatesQueryRes.delegates.pageInfo.hasNextPage
hasNextPage: true //TODO: update
},
stats: {
total: totalDelegatesCount,
Expand All @@ -518,48 +517,49 @@ export async function fetchDelegatesPaginated({
totalMKRDelegated: delegationMetrics.totalMkrDelegated || 0,
totalDelegators: delegationMetrics.delegatorCount || 0
},
delegates: delegatesQueryRes.delegates.nodes.map(delegate => {
const allDelegatesEntry = allDelegatesWithNamesAndLinks.find(
del => del.voteDelegate === delegate.voteDelegate
);
delegates: delegatesQueryRes.delegates.map(delegate => {
const allDelegatesEntry = allDelegatesWithNamesAndLinks.find(del => del.voteDelegate === delegate.id);

const githubDelegate = githubDelegates?.find(ghDelegate => ghDelegate.name === allDelegatesEntry?.name);

const votedProposals = delegatesExecSupport.data?.find(
del => del.voteDelegate === delegate.voteDelegate
del => del.voteDelegate === delegate.id
)?.votedProposals;
const execSupported = githubExecutives.find(proposal =>
votedProposals?.find(vp => vp.toLowerCase() === proposal?.address?.toLowerCase())
);

const creationDate = new Date(delegate.blockTimestamp * 1000);
const expirationDate =
delegate.version == '1' ? add(new Date(Number(delegate.blockTimestamp) * 1000), { years: 1 }) : null;
return {
name: githubDelegate?.name || 'Shadow Delegate',
voteDelegateAddress: delegate.voteDelegate,
address: delegate.delegate,
voteDelegateAddress: delegate.id,
address: delegate.ownerAddress,
status: delegate.expired
? DelegateStatusEnum.expired
: githubDelegate
? DelegateStatusEnum.aligned
: DelegateStatusEnum.shadow,
creationDate: new Date(delegate.creationDate),
expirationDate: new Date(delegate.expirationDate),
expired: delegate.expired,
creationDate,
expirationDate,
expired: expirationDate && expirationDate < new Date(),
isAboutToExpire: isAboutToExpireCheck(new Date(delegate.expirationDate)),
picture: githubDelegate?.picture,
communication: githubDelegate?.communication,
combinedParticipation: githubDelegate?.combinedParticipation,
pollParticipation: githubDelegate?.pollParticipation,
executiveParticipation: githubDelegate?.executiveParticipation,
cuMember: githubDelegate?.cuMember,
mkrDelegated: delegate.totalMkr,
delegatorCount: delegate.delegatorCount,
lastVoteDate: delegate.lastVoted && new Date(delegate.lastVoted),
mkrDelegated: delegate.totalDelegated,
delegatorCount: delegate.delegators,
lastVoteDate:
delegate.voter.lastVotedTimestamp && new Date(Number(delegate.voter.lastVotedTimestamp) * 1000),
proposalsSupported: votedProposals?.length || 0,
execSupported: execSupported && { title: execSupported.title, address: execSupported.address },
previous: allDelegatesEntry?.previous,
next: allDelegatesEntry?.next
};
}) as DelegatePaginated[],
}) as DelegatePaginated[]
};

return delegatesData;
Expand Down
2 changes: 1 addition & 1 deletion modules/delegates/api/fetchDelegatesPageData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export async function fetchDelegatesPageData(
const pageSize = 30;
const page = queryParams?.page || 1;
const includeExpired = queryParams?.includeExpired || false;
const orderBy = queryParams?.orderBy || DelegateOrderByEnum.RANDOM;
const orderBy = queryParams?.orderBy || DelegateOrderByEnum.MKR; //TODO: change to random?
const orderDirection = queryParams?.orderDirection || OrderDirectionEnum.DESC;
const seed = queryParams?.seed || null;
const delegateType = queryParams?.delegateType || DelegateTypeEnum.ALL;
Expand Down
2 changes: 1 addition & 1 deletion modules/delegates/components/DelegateOverviewCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ export const DelegateOverviewCard = memo(
sx={{ fontSize: [3, 5], textAlign: ['left', 'right'] }}
data-testid="total-mkr-delegated"
>
{formatValue(parseEther(delegate.mkrDelegated))}
{formatValue(BigNumber.from(delegate.mkrDelegated), 'wad')}
</Text>
<Text
as="p"
Expand Down
14 changes: 7 additions & 7 deletions modules/delegates/components/DelegatedByAddress.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,13 @@ type CollapsableRowProps = {
totalDelegated: BigNumber;
};

const formatTotalDelegated = (num: BigNumber, denom: BigNumber): string => {
const formatTotalDelegated = (num: BigNumberJS, denom: BigNumber): string => {
try {
// Use bignumber.js to do division because ethers BigNumber does not support decimals
const numB = new BigNumberJS(num.toString());
const denomB = new BigNumberJS(denom.toString());

const weight = numB.div(denomB).times(100);
return formatValue(parseUnits(weight.toString()));
const weight = num.div(denomB).times(100);
return formatValue(parseUnits(weight.toString()), 'wad');
} catch (e) {
return '0';
}
Expand Down Expand Up @@ -86,7 +85,8 @@ const CollapsableRow = ({ delegator, network, bpi, totalDelegated }: Collapsable
</Flex>
<Box as="td" sx={{ verticalAlign: 'top', pt: 2 }}>
<Text sx={{ fontSize: [1, 3] }}>
{`${formatValue(parseUnits(lockAmount))}${bpi > 0 ? ' MKR' : ''}`}
{/*TODO why does the lock amount have decimal places? They all end in .0 */}
{`${formatValue(BigNumber.from(lockAmount.split('.')[0]), 'wad')}${bpi > 0 ? ' MKR' : ''}`}
</Text>
{expanded && (
<Flex sx={{ flexDirection: 'column' }}>
Expand All @@ -107,7 +107,7 @@ const CollapsableRow = ({ delegator, network, bpi, totalDelegated }: Collapsable
)}
<Text key={blockTimestamp} variant="smallCaps" sx={{ pl: 2 }}>
{`${formatValue(
parseUnits(lockAmount.indexOf('-') === 0 ? lockAmount.substring(1) : lockAmount)
BigNumber.from(lockAmount.indexOf('-') === 0 ? lockAmount.substring(1) : lockAmount), 'wad'
)}${bpi > 0 ? ' MKR' : ''}`}
</Text>
</Flex>
Expand All @@ -119,7 +119,7 @@ const CollapsableRow = ({ delegator, network, bpi, totalDelegated }: Collapsable
<Box as="td" sx={{ verticalAlign: 'top', pt: 2 }}>
{totalDelegated ? (
<Text sx={{ fontSize: [1, 3] }}>{`${formatTotalDelegated(
parseUnits(lockAmount),
new BigNumberJS(lockAmount),
totalDelegated
)}%`}</Text>
) : (
Expand Down
12 changes: 6 additions & 6 deletions modules/delegates/delegates.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ export enum DelegateTypeEnum {
}

export enum DelegateOrderByEnum {
DATE = 'DATE',
MKR = 'MKR',
DELEGATORS = 'DELEGATORS',
RANDOM = 'RANDOM'
DATE = 'blockTimestamp',
MKR = 'totalDelegated',
DELEGATORS = 'delegators',
RANDOM = ''
}

export enum OrderDirectionEnum {
ASC = 'ASC',
DESC = 'DESC'
ASC = 'asc',
DESC = 'desc'
}
9 changes: 6 additions & 3 deletions modules/delegates/hooks/useDelegateContractExpirationDate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@ export const useDelegateContractExpirationDate = (): VoteDelegateAddressResponse
const { data: expirationData, error } = useSWR(
voteDelegateContract ? `${voteDelegateContract}/expiration-date` : null,
async () => {
const expiration = await voteDelegateContract?.expiration();

return expiration ? new Date(expiration?.toNumber() * 1000) : null;
try {
const expiration = await voteDelegateContract?.expiration();
return expiration ? new Date(expiration?.toNumber() * 1000) : null;
} catch (err) {
return null;
}
}
);
return {
Expand Down
4 changes: 3 additions & 1 deletion modules/delegates/types/delegate.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ export type DelegateContractInformation = {
mkrDelegated: string;
proposalsSupported: number;
mkrLockedDelegate: MKRLockedDelegateAPIResponse[];
version: string;
lastVoteDate: number | null;
};

export type Delegate = {
Expand All @@ -42,7 +44,7 @@ export type Delegate = {
lastVoteDate: number | null;
expired: boolean;
isAboutToExpire: boolean;
expirationDate: Date;
expirationDate: Date | null;
externalUrl?: string;
combinedParticipation?: string;
pollParticipation?: string;
Expand Down
2 changes: 1 addition & 1 deletion modules/gql/gql.constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const TENDERLY_SPOCK_URL = 'https://pollingdb2-tenderly-staging.makerdao.
const usePrivateSubgraph = process.env.USE_PRIVATE_SUBGRAPH === 'true';
const permission = usePrivateSubgraph ? 'private' : 'public';
export const TENDERLY_SUBGRAPH_URL = `https://query-subgraph-staging.sky.money/${permission}/subgraphs/name/jetstreamgg/subgraph-testnet`;
export const MAINNET_SUBGRAPH_URL = `https://query-subgraph-staging.sky.money/${permission}/private/subgraphs/name/jetstreamgg/subgraph-testnet`;
export const MAINNET_SUBGRAPH_URL = `https://query-subgraph-staging.sky.money/${permission}/subgraphs/name/jetstreamgg/subgraph-mainnet`;

export enum QueryFilterNames {
Active = 'active',
Expand Down
Loading
Loading