Skip to content

Commit

Permalink
always get new session when performing login
Browse files Browse the repository at this point in the history
add verified check to ThreadCard

fix type

fix delete reaction contract controllers

clean up unused code

fix reaction deletion, standardize on deleting reactions by comment_msg_id and thread_msg_id

lint fixes

clean up msg_id passing

fix

fix lint
  • Loading branch information
raykyri committed Aug 17, 2024
1 parent 4ce4889 commit b78552e
Show file tree
Hide file tree
Showing 18 changed files with 118 additions and 76 deletions.
24 changes: 8 additions & 16 deletions libs/shared/src/canvas/runtime/contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,14 +130,10 @@ export const contract = {
updated_at: timestamp,
});
},
async unreactThread(db, { thread_id }, { did, timestamp }) {
await db.set('thread_reactions', {
id: `${thread_id}/${did}`,
author: did,
thread_id,
value: null,
updated_at: timestamp,
});
async unreactThread(db, { thread_id }, { did }) {
const r = await db.get('thread_reactions', `${thread_id}/${did}`);
if (!r || !r.id) throw new Error('reaction does not exist');
await db.delete('thread_reactions', `${thread_id}/${did}`);
},
async reactComment(db, { comment_id, value }, { did, timestamp }) {
if (value !== 'like' && value !== 'dislike') {
Expand All @@ -151,14 +147,10 @@ export const contract = {
updated_at: timestamp,
});
},
async unreactComment(db, { comment_id }, { did, timestamp }) {
await db.set('comment_reactions', {
id: `${comment_id}/${did}`,
author: did,
comment_id,
value: null,
updated_at: timestamp,
});
async unreactComment(db, { comment_id }, { did }) {
const r = await db.get('comment_reactions', `${comment_id}/${did}`);
if (!r || !r.id) throw new Error('reaction does not exist');
await db.delete('comment_reactions', `${comment_id}/${did}`);
},
},
} satisfies Contract;
10 changes: 5 additions & 5 deletions libs/shared/src/canvas/verify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,18 +101,18 @@ export const verifyComment = async (
export const verifyDeleteComment = async (
canvasSignedData: CanvasSignedData,
fields: {
comment_msg_id: string;
comment_id: string;
},
) => {
const { comment_msg_id } = fields;
const { comment_id } = fields;

await verify(canvasSignedData);

const { actionMessage } = canvasSignedData;
assertMatches(actionMessage.payload.name, 'deleteComment', 'comment', 'call');
assertMatches(
actionMessage.payload.args.commentId,
comment_msg_id,
comment_id,
'comment',
'msgid',
);
Expand Down Expand Up @@ -158,7 +158,7 @@ export const verifyThread = async (
export const verifyDeleteThread = async (
canvasSignedData: CanvasSignedData,
fields: {
thread_msg_id: string;
thread_id: string;
},
) => {
await verify(canvasSignedData);
Expand All @@ -167,7 +167,7 @@ export const verifyDeleteThread = async (
assertMatches(actionMessage.payload.name, 'deleteThread', 'thread', 'call');
assertMatches(
actionMessage.payload.args.thread_id,
fields.thread_msg_id,
fields.thread_id,
'thread',
'id',
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -455,7 +455,7 @@ export async function handleSocialLoginCallback({
magicAddress = metadata.publicAddress;
} else {
const { utils } = await import('ethers');
if (metadata.publicAddress === undefined) {
if (metadata.publicAddress === null) {
throw new Error('Expected magic to return publicAddress');
}
magicAddress = utils.getAddress(metadata.publicAddress);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ class MetamaskWebWalletController implements IWebWallet<string> {
if (switchError.code === 4902) {
const wsRpcUrl = app.chain?.meta?.node.url ?? '';
const rpcUrl =
app.chain?.meta?.node.altWalletUrl ?? wsRpcUrl
(app.chain?.meta?.node.altWalletUrl ?? wsRpcUrl)
? new URL(wsRpcUrl).host
: '';

Expand Down
23 changes: 10 additions & 13 deletions packages/commonwealth/client/scripts/controllers/server/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
import axios from 'axios';
import app from 'state';
import { SERVER_URL } from 'state/api/config';
import { fetchCachedConfiguration } from 'state/api/configuration';
import Account from '../../models/Account';
import IWebWallet from '../../models/IWebWallet';

Expand Down Expand Up @@ -69,8 +68,15 @@ export const getMagicCosmosSessionSigner = (
export async function getSessionFromWallet(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
wallet: IWebWallet<any>,
{ newSession }: { newSession: boolean } = { newSession: false },
) {
const sessionSigner = await wallet.getSessionSigner();

if (newSession) {
const { payload } = await sessionSigner.newSession(CANVAS_TOPIC);
return payload;
}

const session = await sessionSigner.getSession(CANVAS_TOPIC);
if (session) {
return session.payload;
Expand Down Expand Up @@ -109,15 +115,8 @@ async function sign(
if (signer.match(did)) {
let lookupDid = did;

const [
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_did,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_pkh,
chainBaseFromAddress,
chainIdFromAddress,
walletAddress,
] = did.split(':');
const [, , chainBaseFromAddress, chainIdFromAddress, walletAddress] =
did.split(':');

// if using polkadot, we need to convert the address so that it has the prefix 42
if (chainBaseFromAddress === 'polkadot') {
Expand All @@ -130,11 +129,9 @@ async function sign(
}

const savedSessionMessage = await signer.getSession(CANVAS_TOPIC, {
did, // TODO: lookupDid?
did,
});

const config = fetchCachedConfiguration();

if (!savedSessionMessage) {
throw new SessionKeyError({
name: 'Authentication Error',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import useFetchCommentsQuery from './fetchComments';
interface DeleteCommentProps {
address: string;
communityId: string;
canvasMsgId: string;
commentMsgId: string;
commentId: number;
existingNumberOfComments: number;
}
Expand All @@ -22,21 +22,22 @@ const deleteComment = async ({
address,
communityId,
commentId,
canvasMsgId,
commentMsgId,
}: DeleteCommentProps) => {
const canvasSignedData = await signDeleteComment(
userStore.getState().activeAccount?.address || '',
{
comment_id: canvasMsgId,
comment_id: commentMsgId,
},
);

await axios.delete(`${SERVER_URL}/comments/${commentId}`, {
data: {
jwt: userStore.getState().jwt,
author_community_id: communityId,
address: address,
community_id: communityId,
author_community_id: communityId,
jwt: userStore.getState().jwt,
...toCanvasSignedDataApiArgs(canvasSignedData),
},
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@ import { userStore } from '../../ui/user';
import useFetchCommentsQuery from './fetchComments';

interface DeleteReactionProps {
communityId: string;
address: string;
reactionMsgId: string;
communityId: string;
commentMsgId: string;
reactionId: number;
}

const deleteReaction = async ({
communityId,
address,
reactionMsgId,
communityId,
commentMsgId,
reactionId,
}: DeleteReactionProps) => {
const canvasSignedData = await signDeleteCommentReaction(address, {
comment_id: reactionMsgId,
comment_id: commentMsgId,
});

return await axios
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,22 +9,22 @@ import { userStore } from '../../ui/user';
import { updateThreadInAllCaches } from './helpers/cache';

interface UseDeleteThreadReactionMutationProps {
communityId: string;
address: string;
threadId: number;
communityId: string;
threadMsgId: string;
threadId: number;
}

interface DeleteReactionProps extends UseDeleteThreadReactionMutationProps {
reactionId: number;
}

const deleteReaction = async ({
communityId,
address,
communityId,
threadMsgId,
reactionId,
threadId,
threadMsgId,
}: DeleteReactionProps) => {
const canvasSignedData = await signDeleteThreadReaction(address, {
thread_id: threadMsgId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export const CommentReactionButton = ({
deleteCommentReaction({
communityId: app.activeChainId(),
address: user.activeAccount?.address,
reactionMsgId: foundReaction.canvasMsgId,
commentMsgId: comment.canvasMsgId,
reactionId: foundReaction.id,
}).catch((err) => {
if (err instanceof SessionKeyError) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import {
chainBaseToCanvasChainId,
getSessionSigners,
} from '@hicommonwealth/shared';
import { useFetchConfigurationQuery } from 'state/api/configuration';

import { useCommunityStake } from '../CommunityStake';

Expand Down Expand Up @@ -85,7 +84,6 @@ const useUserMenuItems = ({
});

const userData = useUserStore();
const { data: configurationData } = useFetchConfigurationQuery();

const navigate = useCommonNavigate();
const { stakeEnabled } = useCommunityStake();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ const useAuthentication = (props: UseAuthenticationProps) => {
}

try {
const session = await getSessionFromWallet(wallet);
const session = await getSessionFromWallet(wallet, { newSession: true });
const chainIdentifier = app.chain?.id || wallet.defaultNetwork;

const validationBlockInfo = await getWalletRecentBlock(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import {
import clsx from 'clsx';
import { useFlag } from 'hooks/useFlag';
import type Comment from 'models/Comment';
import { useFetchConfigurationQuery } from 'state/api/configuration';
import useUserStore from 'state/ui/user';
import { CommentReactionButton } from 'views/components/ReactionButton/CommentReactionButton';
import { PopoverMenu } from 'views/components/component_kit/CWPopoverMenu';
Expand Down Expand Up @@ -120,15 +119,20 @@ export const CommentCard = ({
const [, setOnReaction] = useState<boolean>(false);
const [isUpvoteDrawerOpen, setIsUpvoteDrawerOpen] = useState<boolean>(false);

const { data: config } = useFetchConfigurationQuery();

useEffect(() => {
const canvasSignedData: CanvasSignedData = deserializeCanvas(
comment.canvasSignedData,
);
verify(canvasSignedData).then(() => {
setVerifiedCanvasSignedData(canvasSignedData);
});
try {
const canvasSignedData: CanvasSignedData = deserializeCanvas(
comment.canvasSignedData,
);
if (!canvasSignedData) return;
verify(canvasSignedData)
.then(() => {
setVerifiedCanvasSignedData(canvasSignedData);
})
.catch(() => null);
} catch (error) {
// ignore errors or missing data
}
}, [comment.canvasSignedData]);

const handleReaction = () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ export const CommentTree = ({
try {
await deleteComment({
commentId: comment.id,
canvasMsgId: comment.canvasMsgId,
commentMsgId: comment.canvasMsgId,
communityId: app.activeChainId(),
address: user.activeAccount?.address || '',
existingNumberOfComments: thread.numberOfComments,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
@import '../../../../../../styles/shared';

.ThreadOptions {
display: flex;
flex-direction: column;
Expand All @@ -9,4 +11,10 @@
flex-wrap: wrap;
gap: 1px;
}

.verification-icon {
color: $neutral-500;
margin-top: 2px;
margin-right: 6px;
}
}
Loading

0 comments on commit b78552e

Please sign in to comment.