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 chain node from topics + Fix ERC20 voting #9561

Merged
merged 17 commits into from
Oct 18, 2024
Merged
1 change: 0 additions & 1 deletion libs/model/src/community/CreateTopic.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ export function CreateTopic(): Command<
options = {
...options,
weighted_voting: payload.weighted_voting,
chain_node_id: payload.chain_node_id || undefined,
token_address: payload.token_address || undefined,
token_symbol: payload.token_symbol || undefined,
vote_weight_multiplier: payload.vote_weight_multiplier || undefined,
Expand Down
3 changes: 1 addition & 2 deletions libs/model/src/models/associations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ export const buildAssociations = (db: DB) => {

db.ChainNode.withMany(db.Community)
.withMany(db.EvmEventSource)
.withOne(db.LastProcessedEvmBlock)
.withMany(db.Topic);
.withOne(db.LastProcessedEvmBlock);

db.ContractAbi.withMany(db.EvmEventSource, { foreignKey: 'abi_id' });

Expand Down
11 changes: 0 additions & 11 deletions libs/model/src/models/topic.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { Topic } from '@hicommonwealth/schemas';
import Sequelize from 'sequelize';
import { z } from 'zod';
import { ChainNodeAttributes } from './chain_node';
import type { CommunityAttributes } from './community';
import type { ThreadAttributes } from './thread';
import type { ModelInstance } from './types';
Expand All @@ -10,7 +9,6 @@ export type TopicAttributes = z.infer<typeof Topic> & {
// associations
community?: CommunityAttributes;
threads?: ThreadAttributes[] | TopicAttributes['id'][];
ChainNode?: ChainNodeAttributes;
};
export type TopicInstance = ModelInstance<TopicAttributes>;

Expand Down Expand Up @@ -50,15 +48,6 @@ export default (
},
telegram: { type: Sequelize.STRING, allowNull: true },
weighted_voting: { type: Sequelize.STRING, allowNull: true },
chain_node_id: {
type: Sequelize.INTEGER,
allowNull: true,
references: {
model: 'ChainNodes',
key: 'id',
},
onUpdate: 'CASCADE',
},
token_address: { type: Sequelize.STRING, allowNull: true },
token_symbol: { type: Sequelize.STRING, allowNull: true },
vote_weight_multiplier: { type: Sequelize.INTEGER, allowNull: true },
Expand Down
32 changes: 13 additions & 19 deletions libs/model/src/services/stakeHelper.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { InvalidState } from '@hicommonwealth/core';
import { TopicWeightedVoting } from '@hicommonwealth/schemas';
import { BalanceSourceType, commonProtocol } from '@hicommonwealth/shared';
import { BigNumber } from 'ethers';
import { BigNumber, utils } from 'ethers';
import { tokenBalanceCache } from '.';
import { config } from '../config';
import { models } from '../database';
Expand Down Expand Up @@ -38,25 +38,21 @@ export async function getVotingWeight(
},
],
},
{
model: models.ChainNode,
required: false,
},
],
});

mustExist('Topic', topic);

const { community } = topic;

mustExist('Community', community);

const chain_node = community.ChainNode;

if (topic.weighted_voting === TopicWeightedVoting.Stake) {
mustExist('Chain Node Eth Chain Id', chain_node?.eth_chain_id);
mustExist('Community Namespace Address', community.namespace_address);

const stake = topic.community?.CommunityStakes?.at(0);
mustExist('Community Stake', stake);
const chain_node = community.ChainNode;
mustExist('Chain Node Eth Chain Id', chain_node?.eth_chain_id);

const stakeBalances = await contractHelpers.getNamespaceBalance(
community.namespace_address,
Expand All @@ -70,24 +66,22 @@ export async function getVotingWeight(

return commonProtocol.calculateVoteWeight(stakeBalance, stake.vote_weight);
} else if (topic.weighted_voting === TopicWeightedVoting.ERC20) {
const {
ChainNode: chain_node,
token_address,
vote_weight_multiplier,
} = topic;
mustExist('Topic Chain Node Eth Chain Id', chain_node?.eth_chain_id);
mustExist('Chain Node Eth Chain Id', chain_node?.eth_chain_id);

const balances = await tokenBalanceCache.getBalances({
balanceSourceType: BalanceSourceType.ERC20,
addresses: [address],
sourceOptions: {
evmChainId: chain_node?.eth_chain_id,
contractAddress: token_address!,
evmChainId: chain_node.eth_chain_id,
contractAddress: topic.token_address!,
},
cacheRefresh: true,
});
const balance = balances[address];
return commonProtocol.calculateVoteWeight(balance, vote_weight_multiplier!);
const balance = utils.formatUnits(balances[address], 18);
return commonProtocol.calculateVoteWeight(
balance,
topic.vote_weight_multiplier!,
);
}

// no weighted voting
Expand Down
2 changes: 1 addition & 1 deletion libs/model/src/thread/CreateThreadReaction.command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function CreateThreadReaction(): Command<
address_id: address.id!,
thread_id: thread.id,
reaction: payload.reaction,
calculated_voting_weight,
calculated_voting_weight: calculated_voting_weight?.toString(),
canvas_msg_id: payload.canvas_msg_id,
canvas_signed_data: payload.canvas_signed_data,
},
Expand Down
2 changes: 1 addition & 1 deletion libs/schemas/src/entities/comment.schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export const Comment = z.object({
.nullish(),

reaction_count: PG_INT,
reaction_weights_sum: PG_INT.optional(),
reaction_weights_sum: z.string().nullish(),

search: z.union([z.string(), z.record(z.any())]),

Expand Down
2 changes: 1 addition & 1 deletion libs/schemas/src/entities/reaction.schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export const Reaction = z.object({
thread_id: PG_INT.nullish(),
comment_id: PG_INT.nullish(),
proposal_id: z.number().nullish(),
calculated_voting_weight: PG_INT.nullish(),
calculated_voting_weight: z.string().nullish(),
canvas_signed_data: z.any().nullish(),
canvas_msg_id: z.string().max(255).nullish(),
created_at: z.coerce.date().optional(),
Expand Down
2 changes: 1 addition & 1 deletion libs/schemas/src/entities/thread.schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export const Thread = z.object({

//counts
reaction_count: PG_INT.optional(),
reaction_weights_sum: PG_INT.optional(),
reaction_weights_sum: z.string().nullish(),
comment_count: PG_INT.optional().optional(),

activity_rank_date: z.coerce.date().nullish(),
Expand Down
10 changes: 4 additions & 6 deletions libs/schemas/src/entities/topic.schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,6 @@ export const Topic = z.object({
group_ids: z.array(PG_INT).default([]),
default_offchain_template_backup: z.string().nullish(),
weighted_voting: z.nativeEnum(TopicWeightedVoting).nullish(),
chain_node_id: PG_INT.nullish().describe(
'token chain node ID, used for ERC20 topics',
),
token_address: z
.string()
.nullish()
Expand All @@ -50,9 +47,10 @@ export const Topic = z.object({
.string()
.nullish()
.describe('token symbol, used for ERC20 topics'),
vote_weight_multiplier: PG_INT.nullish().describe(
'vote weight multiplier, used for ERC20 topics',
),
vote_weight_multiplier: z
.number()
.nullish()
.describe('vote weight multiplier, used for ERC20 topics'),

created_at: z.coerce.date().optional(),
updated_at: z.coerce.date().optional(),
Expand Down
3 changes: 2 additions & 1 deletion libs/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@
"@canvas-js/interfaces": "^0.10.10",
"@canvas-js/signatures": "^0.10.10",
"@cosmjs/encoding": "0.32.3",
"@ethersproject/bignumber": "^5.7.0",
"@ipld/dag-json": "^10.2.0",
"@polkadot/util": "12.6.2",
"@libp2p/peer-id-factory": "^4.2.4",
"@polkadot/util": "12.6.2",
"moment": "^2.23.0",
"safe-stable-stringify": "^2.4.2"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/commonwealth/client/scripts/models/Reaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class Reaction {

public readonly profile: UserProfile;

public calculatedVotingWeight: number;
public calculatedVotingWeight: string;
// TODO: Do thread/comment/proposal ids ever appear as strings?

constructor({
Expand Down
6 changes: 3 additions & 3 deletions packages/commonwealth/client/scripts/models/Thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ export class Thread implements IUniqueId {
public associatedReactions: AssociatedReaction[];
public associatedContests?: AssociatedContest[];
public recentComments?: Comment<IUniqueId>[];
public reactionWeightsSum: number;
public reactionWeightsSum: string;
public links: Link[];
public readonly discord_meta: any;
public readonly latestActivity: Moment;
Expand Down Expand Up @@ -353,7 +353,7 @@ export class Thread implements IUniqueId {
reactionType?: any[]; // TODO: fix type
reactionTimestamps?: string[];
reactionWeights?: number[];
reaction_weights_sum: number;
reaction_weights_sum: string;
ThreadVersionHistories: ThreadVersionHistory[];
Address: any; // TODO: fix type
discord_meta?: any;
Expand Down Expand Up @@ -457,7 +457,7 @@ export class Thread implements IUniqueId {
parent_id: null,
reactions: [],
CommentVersionHistories: [],
reaction_weights_sum: 0,
reaction_weights_sum: '0',
canvas_signed_data: null,
canvas_msg_id: null,
}),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export function formatActivityResponse(response: AxiosResponse<any, any>) {
version_history: null,
last_commented_on: '',
address_last_active: '',
reaction_weights_sum: 0,
reaction_weights_sum: '0',
}),
);
}
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import BigNumber from 'bignumber.js';
import { buildCreateCommentReactionInput } from 'client/scripts/state/api/comments/createReaction';
import { buildDeleteCommentReactionInput } from 'client/scripts/state/api/comments/deleteReaction';
import { useAuthModalStore } from 'client/scripts/state/ui/modals';
Expand Down Expand Up @@ -52,8 +53,8 @@ export const CommentReactionButton = ({
(x) => x?.author === activeAddress,
);
const reactionWeightsSum = comment.reactions.reduce(
(acc, curr) => acc + (curr.calculatedVotingWeight || 1),
0,
(acc, curr) => BigNumber.sum(acc, curr.calculatedVotingWeight || 1),
BigNumber(0),
);

const handleVoteClick = async (e) => {
Expand Down Expand Up @@ -117,7 +118,7 @@ export const CommentReactionButton = ({
isOpen={isAuthModalOpen}
/>
<CWUpvoteSmall
voteCount={reactionWeightsSum}
voteCount={reactionWeightsSum.toString()}
disabled={!user.activeAccount || disabled}
selected={hasReacted}
onClick={handleVoteClick}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import CWPopover, {
} from 'views/components/component_kit/new_designs/CWPopover';

interface CWUpvoteSmallProps {
voteCount: number;
voteCount: string;
disabled: boolean;
selected: boolean;
onClick: (e: React.MouseEvent<HTMLDivElement>) => void;
Expand Down Expand Up @@ -41,13 +41,13 @@ const CWUpvoteSmall = ({
onMouseEnter={popoverProps.handleInteraction}
onMouseLeave={popoverProps.handleInteraction}
>
{voteCount > 0 && !disabled ? (
{voteCount && !disabled ? (
<>
<CWThreadAction
action="upvote"
isThreadArchived={isThreadArchived}
selected={selected}
label={String(voteCount)}
label={voteCount}
disabled={disabled}
onClick={handleClick}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import { ArrowFatUp } from '@phosphor-icons/react';
import React, { FC } from 'react';

import { formatNumberShort } from 'adapters/currency';
import { formatBigNumberShort } from 'adapters/currency';
import { CWText } from '../cw_text';
import { getClasses } from '../helpers';

import 'components/component_kit/new_designs/cw_upvote.scss';
import { BigNumber } from 'ethers';
import { AnchorType } from 'views/components/component_kit/new_designs/CWPopover';
import { ComponentType } from '../types';

type CWUpvoteProps = {
voteCount: number;
voteCount: string;
active?: boolean;
disabled?: boolean;
onClick?: (e) => void;
Expand Down Expand Up @@ -47,7 +48,7 @@ export const CWUpvote: FC<CWUpvoteProps> = ({
weight={active ? 'fill' : 'regular'}
/>
<CWText className={getClasses({ ...getParameters() })} type="caption">
{formatNumberShort(voteCount)}
{formatBigNumberShort(BigNumber.from(voteCount))}
</CWText>
</button>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ function mapThread(thread: z.infer<typeof ActivityThread>): Thread {
userId: thread.user_id,
last_edited: thread.updated_at ?? '',
last_commented_on: '',
reaction_weights_sum: 0,
reaction_weights_sum: '0',
address_last_active: '',
ContestActions: [],
numberOfComments: thread.number_of_comments,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,23 @@
<CWText type="h5">Small</CWText>
<div className="flex-row">
<CWUpvoteSmall
voteCount={87}
voteCount={'87'}

Check warning on line 19 in packages/commonwealth/client/scripts/views/pages/ComponentsShowcase/components/Upvotes.showcase.tsx

View workflow job for this annotation

GitHub Actions / Code Quality Recommendations (20)

Curly braces are unnecessary here
disabled={false}
selected={false}
// @ts-expect-error <StrictNullChecks/>
onClick={undefined}
popoverContent={<div>Upvoters List</div>}
/>
<CWUpvoteSmall
voteCount={8887}
voteCount={'8887'}

Check warning on line 27 in packages/commonwealth/client/scripts/views/pages/ComponentsShowcase/components/Upvotes.showcase.tsx

View workflow job for this annotation

GitHub Actions / Code Quality Recommendations (20)

Curly braces are unnecessary here
disabled={false}
selected={true}
// @ts-expect-error <StrictNullChecks/>
onClick={undefined}
popoverContent={<div>Upvoters List</div>}
/>
<CWUpvoteSmall
voteCount={99999}
voteCount={'99999'}

Check warning on line 35 in packages/commonwealth/client/scripts/views/pages/ComponentsShowcase/components/Upvotes.showcase.tsx

View workflow job for this annotation

GitHub Actions / Code Quality Recommendations (20)

Curly braces are unnecessary here
disabled={true}
selected={false}
// @ts-expect-error <StrictNullChecks/>
Expand Down
Loading
Loading