Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
carina-akaia committed Jan 19, 2025
1 parent f2818ec commit 900a0b9
Show file tree
Hide file tree
Showing 31 changed files with 185 additions and 213 deletions.
2 changes: 2 additions & 0 deletions src/common/api/indexer/internal/client.generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1128,6 +1128,8 @@ export interface ListRegistration {
admin_notes?: string | null;
/** Registration id. */
readonly id: number;
/** List registered. */
readonly list_id: number;
registered_by: Account;
registrant: Account;
/**
Expand Down
47 changes: 47 additions & 0 deletions src/common/contexts/wallet-manager.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { createContext, useContext, useEffect, useMemo, useState } from "react";

import { WalletManager } from "@wpdas/naxios/dist/types/managers/wallet-manager";

import { nearClient } from "../api/near";

type WalletManagerContextState =
| { isReady: false }
| ({ isReady: true } & Omit<WalletManager, "changeWalletStatus" | "status">);

const initialWalletContextState: WalletManagerContextState = { isReady: false };

export const WalletManagerContext =
createContext<WalletManagerContextState>(initialWalletContextState);

export type WalletManagerContextProviderProps = {
children: React.ReactNode;
};

export const WalletManagerProvider: React.FC<WalletManagerContextProviderProps> = ({
children,
}) => {
const [isReady, setIsReady] = useState(false);

useEffect(() => {
nearClient.walletApi
.initNear()
.then(() => setIsReady(true))
.catch((error) => {
console.log(error);
setIsReady(false);
});
}, []);

const resolvedContext = useMemo(
() => (isReady ? { isReady, ...nearClient.walletApi } : initialWalletContextState),
[isReady],
);

return (
<WalletManagerContext.Provider value={resolvedContext}>
{children}
</WalletManagerContext.Provider>
);
};

export const useWalletManagerContext = () => useContext(WalletManagerContext);
Empty file removed src/common/contexts/wallet.ts
Empty file.
2 changes: 1 addition & 1 deletion src/entities/_shared/session/components/buttons.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { useCallback } from "react";
import { nearClient } from "@/common/api/near";
import { Button } from "@/common/ui/components";

export const AuthSignInButton: React.FC = () => {
export const SessionAuthButton: React.FC = () => {
const onClick = useCallback(() => {
nearClient.walletApi.signInModal();
}, []);
Expand Down
11 changes: 2 additions & 9 deletions src/entities/_shared/session/components/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ import { isClient } from "@wpdas/naxios";

import { walletApi } from "@/common/api/near/client";
import { SplashScreen } from "@/common/ui/components";
import { dispatch, resetStore } from "@/store";

import { useSessionReduxStore } from "../hooks/redux-store";
import { useWallet } from "../hooks/wallet";

type SessionProviderProps = {
Expand All @@ -15,7 +13,7 @@ type SessionProviderProps = {

export const SessionProvider = ({ children }: SessionProviderProps) => {
const [isReady, setReady] = useState(false);
const { isAuthenticated } = useSessionReduxStore();
const [isAuthenticated, setIsAuthenticated] = useState(false);
const { wallet } = useWallet();

// Check wallet
Expand All @@ -29,12 +27,7 @@ export const SessionProvider = ({ children }: SessionProviderProps) => {
const isSignedIn = walletApi.walletSelector.isSignedIn();

if (isSignedIn !== isAuthenticated) {
dispatch.session.setAuthData({ isAuthenticated: isSignedIn });

if (!isSignedIn) {
// Clean up states
resetStore();
}
setIsAuthenticated(isSignedIn);
}
}
}, [isAuthenticated, isReady, wallet]);
Expand Down
11 changes: 0 additions & 11 deletions src/entities/_shared/session/hooks/redux-store.ts

This file was deleted.

35 changes: 21 additions & 14 deletions src/entities/_shared/session/hooks/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,34 @@ import { useMemo } from "react";
import { prop } from "remeda";

import { PUBLIC_GOODS_REGISTRY_LIST_ID } from "@/common/constants";
import { useWalletManagerContext } from "@/common/contexts/wallet-manager";
import { RegistrationStatus, listsContractHooks } from "@/common/contracts/core/lists";
import { isAccountId } from "@/common/lib";
import { AccountId } from "@/common/types";
import { useGlobalStoreSelector } from "@/store";

import { useWallet } from "./wallet";
import { Session } from "../types";

// TODO: Subscribe to wallet events to keep isSignedIn synced
export const useSession = (): Session => {
const { isSignedIn, wallet } = useWallet();
const walletManagerContext = useWalletManagerContext();

const isSignedIn = useMemo(
() => (walletManagerContext.isReady ? walletManagerContext.walletSelector.isSignedIn() : false),
[walletManagerContext],
);

const walletAccountId = useMemo(
() => (walletManagerContext.isReady ? walletManagerContext.accountId : null),
[walletManagerContext],
);

const { actAsDao, accountId: lastActiveAccountId } = useGlobalStoreSelector(prop("nav"));
const asDao = actAsDao.toggle && Boolean(actAsDao.defaultAddress);

const accountId: AccountId | undefined = useMemo(
() => (asDao ? actAsDao.defaultAddress : (wallet?.accountId ?? lastActiveAccountId)),
[actAsDao.defaultAddress, asDao, lastActiveAccountId, wallet?.accountId],
() => (asDao ? actAsDao.defaultAddress : (walletAccountId ?? lastActiveAccountId)),
[actAsDao.defaultAddress, asDao, lastActiveAccountId, walletAccountId],
);

/**
Expand All @@ -27,16 +39,9 @@ export const useSession = (): Session => {
*/
const isAccountIdValid = useMemo(() => isAccountId(accountId), [accountId]);

const { isLoading: isRegistrationFlagLoading, data: isRegistered = false } =
listsContractHooks.useIsRegistered({
enabled: isAccountIdValid,
accountId: accountId ?? "noop",
listId: PUBLIC_GOODS_REGISTRY_LIST_ID,
});

const { isLoading: isRegistrationLoading, data: registration } =
listsContractHooks.useRegistration({
enabled: isRegistered,
enabled: isAccountIdValid,
accountId: accountId ?? "noop",
listId: PUBLIC_GOODS_REGISTRY_LIST_ID,
});
Expand All @@ -45,17 +50,19 @@ export const useSession = (): Session => {
return {
accountId,
isSignedIn: true,
isMetadataLoading: isRegistrationFlagLoading || isRegistrationLoading,
isMetadataLoading: isRegistrationLoading,
hasRegistrationSubmitted: registration !== undefined,
hasRegistrationApproved: registration?.status === RegistrationStatus.Approved,
registrationStatus: registration?.status,
};
} else {
return {
accountId: undefined,
registrationStatus: undefined,
isSignedIn: false,
isMetadataLoading: false,
hasRegistrationSubmitted: false,
hasRegistrationApproved: false,
registrationStatus: undefined,
};
}
};
6 changes: 0 additions & 6 deletions src/entities/_shared/session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,5 @@ export * from "./types";
export * from "./components/buttons";
export * from "./components/providers";

//! For backward compatibility only
// TODO: Rewire all the consumer code through `useSession` hook instead
export * from "./hooks/redux-store";

export * from "./hooks/session";
export * from "./hooks/wallet";

export { sessionModel } from "./model";
31 changes: 0 additions & 31 deletions src/entities/_shared/session/model.ts

This file was deleted.

2 changes: 2 additions & 0 deletions src/entities/_shared/session/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ export type Session =
registrationStatus?: RegistrationStatus;
isSignedIn: true;
isMetadataLoading: boolean;
hasRegistrationSubmitted: boolean;
hasRegistrationApproved: boolean;
}
| {
accountId: undefined;
registrationStatus: undefined;
isSignedIn: false;
isMetadataLoading: false;
hasRegistrationSubmitted: false;
hasRegistrationApproved: false;
};
4 changes: 2 additions & 2 deletions src/entities/_shared/token/components/TokenSelector.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,11 @@ import { useSession } from "@/entities/_shared/session";
import { useToken, useTokenAllowlist } from "../hooks";

const TokenSelectorOption: React.FC<ByTokenId> = ({ tokenId }) => {
const authenticatedUser = useSession();
const viewer = useSession();

const { data: token } = useToken({
tokenId,
balanceCheckAccountId: authenticatedUser?.accountId,
balanceCheckAccountId: viewer?.accountId,
});

switch (tokenId) {
Expand Down
6 changes: 3 additions & 3 deletions src/entities/post/components/PostEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,11 @@ import { useAccountSocialProfile } from "@/entities/_shared/account";
import { useSession } from "@/entities/_shared/session";

export const PostEditor = ({ accountId }: { accountId: AccountId }) => {
const authenticatedUser = useSession();
const viewer = useSession();

const { avatarSrc } = useAccountSocialProfile({
enabled: authenticatedUser.isSignedIn,
accountId: authenticatedUser.accountId as AccountId,
enabled: viewer.isSignedIn,
accountId: viewer.accountId as AccountId,
});

const [postText, setPostText] = useState("");
Expand Down
8 changes: 4 additions & 4 deletions src/entities/pot/components/ChallengeModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,16 @@ export const ChallengeModal: React.FC<ChallengeModalProps> = ({
potId,
potDetail,
}) => {
const authenticatedUser = useSession();
const viewer = useSession();
const { data: potPayoutChallenges } = potContractHooks.usePayoutChallenges({ potId });

const activeChallenge = useMemo(() => {
if (authenticatedUser.isSignedIn) {
if (viewer.isSignedIn) {
return (potPayoutChallenges ?? []).find(
({ challenger_id }) => authenticatedUser.accountId === challenger_id,
({ challenger_id }) => viewer.accountId === challenger_id,
);
} else return undefined;
}, [authenticatedUser.isSignedIn, authenticatedUser.accountId, potPayoutChallenges]);
}, [viewer.isSignedIn, viewer.accountId, potPayoutChallenges]);

// Form settings
const { form, errors, onSubmit, inProgress } = useChallengeForm({ potDetail });
Expand Down
6 changes: 3 additions & 3 deletions src/entities/voting-round/components/CandidateTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const VotingRoundCandidateTable: React.FC<VotingRoundCandidateTableProps>
}) => {
const { height: windowHeight } = useWindowSize();
const { toast } = useToast();
const authenticatedUser = useSession();
const viewer = useSession();
const selectedEntries = useSet<AccountId>();

const { data: isVotingPeriodOngoing } = votingContractHooks.useIsVotingPeriod({
Expand All @@ -39,9 +39,9 @@ export const VotingRoundCandidateTable: React.FC<VotingRoundCandidateTableProps>
});

const { data: remainingUserVotingCapacity } = votingContractHooks.useVoterRemainingCapacity({
enabled: electionId !== 0 && authenticatedUser.accountId !== undefined,
enabled: electionId !== 0 && viewer.accountId !== undefined,
electionId,
accountId: authenticatedUser.accountId as AccountId,
accountId: viewer.accountId as AccountId,
});

const handleEntrySelect = useCallback(
Expand Down
21 changes: 10 additions & 11 deletions src/entities/voting-round/hooks/candidates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,17 @@ export interface VotingRoundCandidateLookup extends ByElectionId {}

export const useVotingRoundCandidateLookup = ({ electionId }: VotingRoundCandidateLookup) => {
const [searchTerm, setSearchTerm] = useState<string>("");
const authenticatedUser = useSession();
const viewer = useSession();

const { data, ...candidatesQueryResult } = votingContractHooks.useElectionCandidates({
enabled: electionId !== 0,
electionId,
});

const { data: userVotes } = votingContractHooks.useVotingRoundVoterVotes({
enabled: electionId !== 0 && isAccountId(authenticatedUser.accountId),
enabled: electionId !== 0 && isAccountId(viewer.accountId),
electionId,
accountId: authenticatedUser.accountId as AccountId,
accountId: viewer.accountId as AccountId,
});

return useMemo(() => {
Expand Down Expand Up @@ -67,7 +67,7 @@ export const useVotingRoundCandidateEntry = ({
accountId,
}: ByElectionId & ByAccountId) => {
const { toast } = useToast();
const authenticatedUser = useSession();
const viewer = useSession();

const { data: isVotingPeriodOngoing = false } = votingContractHooks.useIsVotingPeriod({
enabled: electionId !== 0,
Expand All @@ -76,9 +76,9 @@ export const useVotingRoundCandidateEntry = ({

const { data: remainingUserVotingCapacity, isLoading: isRemainingUserVotingCapacityLoading } =
votingContractHooks.useVoterRemainingCapacity({
enabled: electionId !== 0 && isAccountId(authenticatedUser.accountId),
enabled: electionId !== 0 && isAccountId(viewer.accountId),
electionId,
accountId: authenticatedUser.accountId as AccountId,
accountId: viewer.accountId as AccountId,
});

const {
Expand All @@ -101,23 +101,22 @@ export const useVotingRoundCandidateEntry = ({

const hasUserVotes = useMemo(
() =>
votes?.find(({ voter: voterAccountId }) => voterAccountId === authenticatedUser.accountId) !==
undefined,
votes?.find(({ voter: voterAccountId }) => voterAccountId === viewer.accountId) !== undefined,

[votes, authenticatedUser.accountId],
[votes, viewer.accountId],
);

const canReceiveVotes = useMemo(
() =>
electionId !== 0 &&
authenticatedUser.isSignedIn &&
viewer.isSignedIn &&
(votes === undefined
? false
: isVotingPeriodOngoing && !hasUserVotes && remainingUserVotingCapacity !== 0),

[
electionId,
authenticatedUser.isSignedIn,
viewer.isSignedIn,
votes,
isVotingPeriodOngoing,
hasUserVotes,
Expand Down
Loading

0 comments on commit 900a0b9

Please sign in to comment.