Skip to content

Commit

Permalink
feat: update queries, add logout function, full flow for wagmi
Browse files Browse the repository at this point in the history
  • Loading branch information
simodrws committed May 9, 2023
1 parent b8f8452 commit cec2e23
Show file tree
Hide file tree
Showing 12 changed files with 471 additions and 124 deletions.
1 change: 1 addition & 0 deletions src/components/masa-interface/masa-interface.tsx
Expand Up @@ -139,6 +139,7 @@ export const MasaInterface = ({
isConnected,
openConnectModal,
closeModal,
useRainbowKit,
]);

const isModal = useMemo(() => {
Expand Down
Expand Up @@ -9,8 +9,8 @@ export const InterfaceAuthenticate = (): JSX.Element => {
handleLogin,
walletAddress,
isLoading,
setModalOpen,
openConnectModal,
// setModalOpen,
// openConnectModal,
isLoggedIn,
useRainbowKit,
connect,
Expand All @@ -20,7 +20,7 @@ export const InterfaceAuthenticate = (): JSX.Element => {
const switchWallet = useCallback(() => {
console.log({ disconnect });
disconnect();
}, [disconnect, setModalOpen, openConnectModal, isConnected, isLoggedIn]);
}, [disconnect]);

useEffect(() => {
if (isConnected && !isLoggedIn) {
Expand Down
116 changes: 116 additions & 0 deletions src/provider/hooks.ts
@@ -0,0 +1,116 @@
import { useDisconnect } from 'wagmi';
import { queryClient } from './masa-query-client';
import { useAsyncFn } from 'react-use';
import { DependencyList } from 'react';
import {
getIdentityQueryKey,
getSessionDataQueryKey,
getSessionQueryKey,
getWalletQueryKey,
} from './modules';
import { Masa } from '@masa-finance/masa-sdk';
import { Signer } from 'ethers';

const QUERIES = [
'identity',
'wallet',
'session',
'sessionData',
// 'credit-scores',
// 'green',
// 'soulnames',
];

export type QueryKeyRetrievalInput = {
masa?: Masa;
signer?: Signer;
walletAddress?: string;
};

export const getQueryKeys = () => ({
identity: ({ masa, signer, walletAddress }: QueryKeyRetrievalInput) =>
getIdentityQueryKey({ masa, signer, walletAddress }),
session: ({ masa, signer, walletAddress }: QueryKeyRetrievalInput) =>
getSessionQueryKey({ masa, signer, walletAddress }),
sessionData: ({ masa, signer, walletAddress }: QueryKeyRetrievalInput) =>
getSessionDataQueryKey({ masa, signer, walletAddress }),
wallet: ({ masa, signer, walletAddress }: QueryKeyRetrievalInput) =>
getWalletQueryKey({ masa, signer, walletAddress }),
});

export const invalidateAllQueries = async ({
masa,
signer,
walletAddress,
}: QueryKeyRetrievalInput) => {
console.log('invalidate all queries start');
const res = await Promise.all(
QUERIES.map((query: string) =>
queryClient.getQueriesData(
getQueryKeys()[query]({
masa,
signer,
walletAddress,
})
)
)
);

console.log(
'res inv queries',
res.map((r) => r[0])

Check warning on line 61 in src/provider/hooks.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node

Expected r to have a type annotation
);

const resTwo = await Promise.all(
QUERIES.map(async (query: string) =>
queryClient.invalidateQueries(
getQueryKeys()[query]({
masa,
signer,
walletAddress,
})
)
)
);
console.log('res after invalidation', resTwo);
};

export const useLogout = (
options: {
masa?: Masa;
signer?: Signer;
walletAddress?: string;
onLogoutStart?: () => void;
onLogoutFinish?: () => void;
},
deps?: DependencyList
) => {
const { onLogoutStart, onLogoutFinish, masa, walletAddress, signer } =
options;
const { disconnectAsync } = useDisconnect();

const [{ value: hasLoggedOut, loading: isLoggingOut, error }, logout] =
useAsyncFn(async () => {
try {
onLogoutStart?.();
await masa?.session.sessionLogout();
console.log('before query');
await invalidateAllQueries({ masa, signer, walletAddress });
console.log('after query');
await disconnectAsync();
return true;
} catch (error: unknown) {
console.error(error);
return false;
} finally {
onLogoutFinish?.();
}
}, [disconnectAsync, onLogoutStart, onLogoutFinish, masa, ...(deps ?? [])]);

return {
hasLoggedOut,
isLoggingOut,
logout,
error,
};
};
12 changes: 11 additions & 1 deletion src/provider/masa-context-provider.tsx
Expand Up @@ -24,6 +24,7 @@ import { useRainbowKit } from './use-rainbowkit';
import { useWagmi } from './modules/wagmi';
import { useNetworkSwitch } from './use-network-switch';
import { MasaNetworks } from './configured-rainbowkit-provider/utils';
import { useLogout } from './hooks';

export { SoulNameErrorCodes };

Expand Down Expand Up @@ -83,7 +84,7 @@ export const MasaContextProvider = ({
});

// network
const { switchNetwork, currentNetwork } = useNetwork(signer);
const { switchNetwork, currentNetwork } = useNetwork({provider: signer, useRainbowKitWalletConnect });
const { switchNetwork: switchNetworkNew, currentNetwork: currentNetworkNew } =
useNetworkSwitch();

Expand Down Expand Up @@ -171,6 +172,14 @@ export const MasaContextProvider = ({
isGreensLoading,
wagmiLoading,
]);

const { logout } = useLogout({
onLogoutStart: () => console.log('starting logout'),
onLogoutFinish: () => console.log('finished logout'),
walletAddress,
masa: masaInstance,
signer,
});
// const providerWagmi = useProvider();

// useEffect(() => {
Expand Down Expand Up @@ -280,6 +289,7 @@ export const MasaContextProvider = ({

// masa-react global connect
connect,
logout,

// general config
scope,
Expand Down
2 changes: 1 addition & 1 deletion src/provider/masa-shape.ts
Expand Up @@ -26,7 +26,7 @@ export interface MasaShape {

// global connect
connect?: (options?: { scope?: string[]; callback?: () => void }) => void;

logout?: () => Promise<boolean>;
// general config
scope?: string[];
areScopesFullfiled?: boolean;
Expand Down
100 changes: 75 additions & 25 deletions src/provider/modules/identity/identity.ts
Expand Up @@ -4,25 +4,24 @@ import { queryClient } from '../../masa-query-client';
import { Masa, NetworkName, PaymentMethod } from '@masa-finance/masa-sdk';
import { BigNumber } from 'ethers';

export const useIdentity = (
masa?: Masa,
walletAddress?: string
): {
identity?: {
identityId?: BigNumber;
address?: string;
};
handlePurchaseIdentity: () => Promise<boolean>;
handlePurchaseIdentityWithSoulname: (
paymentMethod: PaymentMethod,
soulname: string,
registrationPeriod: number
) => Promise<boolean>;
status: string;
isIdentityLoading: boolean;
reloadIdentity: () => void;
error: unknown;
} => {
export const getIdentityQueryKey = ({
walletAddress,
masa,
}: {
walletAddress?: string;
masa?: Masa;
signer?: any; // unused here

Check warning on line 13 in src/provider/modules/identity/identity.ts

View workflow job for this annotation

GitHub Actions / Build, lint, and test on Node

Unexpected any. Specify a different type
}) => {
return ['identity', walletAddress, masa?.config.networkName];
};

export const useIdentityQuery = ({
masa,
walletAddress,
}: {
masa?: Masa;
walletAddress?: string;
}) => {
const queryKey: (string | NetworkName | undefined)[] = useMemo(() => {
return ['identity', walletAddress, masa?.config.networkName];
}, [walletAddress, masa]);
Expand All @@ -38,7 +37,7 @@ export const useIdentity = (
queryKey,
() => masa?.identity.load(walletAddress),
{
enabled: !!masa && !!walletAddress,
enabled: false, // !!masa && !!walletAddress,
retry: false,
onSuccess: (identity?: { identityId?: BigNumber; address?: string }) => {
if (masa?.config.verbose) {
Expand All @@ -48,12 +47,63 @@ export const useIdentity = (
}
);

const invalidateIdentity = useCallback(
async () => await queryClient.invalidateQueries(['identity']),
[]
);

const invalidateSoulnames = useCallback(
async () => await queryClient.invalidateQueries(['soulnames']),
[]
);

return {
identity,
status,
isLoading,
isFetching,
reloadIdentity,
error,
invalidateIdentity,
invalidateSoulnames,
};
};

export const useIdentity = (
masa?: Masa,
walletAddress?: string
): {
identity?: {
identityId?: BigNumber;
address?: string;
};
handlePurchaseIdentity: () => Promise<boolean>;
handlePurchaseIdentityWithSoulname: (
paymentMethod: PaymentMethod,
soulname: string,
registrationPeriod: number
) => Promise<boolean>;
status: string;
isIdentityLoading: boolean;
reloadIdentity: () => void;
error: unknown;
} => {
const {
identity,
status,
isLoading,
isFetching,
reloadIdentity,
error,
invalidateIdentity,
invalidateSoulnames,
} = useIdentityQuery({ masa, walletAddress });
const handlePurchaseIdentity = useCallback(async (): Promise<boolean> => {
const result = await masa?.identity.create();
await queryClient.invalidateQueries(['identity']);
await invalidateIdentity();

return !!result?.success;
}, [masa]);
}, [masa, invalidateIdentity]);

const handlePurchaseIdentityWithSoulname = useCallback(
async (
Expand All @@ -66,12 +116,12 @@ export const useIdentity = (
soulname,
registrationPeriod
);
await queryClient.invalidateQueries(['identity']);
await queryClient.invalidateQueries(['soulnames']);
await invalidateIdentity();
await invalidateSoulnames();

return !!result?.success;
},
[masa]
[masa, invalidateIdentity, invalidateSoulnames]
);

return {
Expand Down

0 comments on commit cec2e23

Please sign in to comment.