Skip to content

Commit

Permalink
feat: chat from profile
Browse files Browse the repository at this point in the history
  • Loading branch information
HadiKhai committed Dec 5, 2024
1 parent e7d8870 commit fb31ee7
Show file tree
Hide file tree
Showing 17 changed files with 591 additions and 350 deletions.
15 changes: 15 additions & 0 deletions packages/@justaname.id/react/src/lib/helpers/validateEns.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { normalize } from 'viem/ens';

export const validateEns = (name: string | undefined): string | undefined => {
if (typeof name !== 'string' || name.trim() === '') {
return;
}

try {
const normalized = normalize(name);

return normalized;
} catch (error) {
return;
}
};
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ export const buildPrimaryNameBatchKey = (chainId: ChainId | undefined) => [
chainId,
];

export type PrimaryNameRecord = Record<string | Address, string | null>;
export type PrimaryNameRecord = Record<string | string, string | null>;

export interface UsePrimaryNameBatchParams {
addresses?: Address[];
addresses?: string[];
chainId?: ChainId;
enabled?: boolean;
}
Expand Down Expand Up @@ -143,7 +143,7 @@ export const usePrimaryNameBatch = (
),
queryFn: () =>
getPrimaryNameBatch({
addresses: params?.addresses,
addresses: params?.addresses as Address[],
}),
enabled:
Boolean(params?.addresses) && Boolean(ensClient) && Boolean(_enabled),
Expand Down
59 changes: 47 additions & 12 deletions packages/@justaname.id/react/src/lib/hooks/records/useRecords.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ import { useMemo } from 'react';
import { Records } from '../../types';
import { defaultOptions } from '../../query';
import { RecordsTaskQueue } from './records-task-queue';
import { checkEnsValid } from '../../helpers/checkEnsValid';
import { useEnsPublicClient } from '../client/useEnsPublicClient';
import { useOffchainResolvers } from '../offchainResolver';
import { getRecords as getEnsRecords } from '@ensdomains/ensjs/public';
import { checkEnsValid } from '../../helpers/checkEnsValid';
import { validateEns } from '../../helpers/validateEns';

export const buildRecordsBySubnameKey = (
subname: string,
Expand Down Expand Up @@ -72,6 +73,7 @@ export const useRecords = (params?: UseRecordsParams): UseRecordsResult => {
() => params?.chainId || chainId,
[params?.chainId, chainId]
);
const _ens = useMemo(() => validateEns(params?.ens), [params?.ens]);
const { offchainResolvers } = useOffchainResolvers();
const { ensClient } = useEnsPublicClient({
chainId: _chainId,
Expand All @@ -86,12 +88,19 @@ export const useRecords = (params?: UseRecordsParams): UseRecordsResult => {
const getRecords = async (
_params: SubnameRecordsRoute['params']
): Promise<Records> => {
const __ens = validateEns(_params.ens);

if (!__ens) {
throw new Error('Invalid ENS name');
}

const result = await justaname.subnames.getRecords({
ens: _params.ens,
ens: __ens,
providerUrl: _params.providerUrl,
chainId: _params.chainId,
});

console.log(__ens, result);
checkEnsValid(result);

const sanitized = sanitizeRecords(result);
Expand All @@ -109,8 +118,14 @@ export const useRecords = (params?: UseRecordsParams): UseRecordsResult => {
throw new Error('Public client not found');
}

const __ens = validateEns(_params.ens) || _ens;

if (!__ens) {
throw new Error('Invalid ENS name');
}

const result = await getEnsRecords(ensClient, {
name: _params.ens,
name: __ens,
coins: Object.keys(coinTypeMap),
texts: [
...generalKeys,
Expand All @@ -126,7 +141,7 @@ export const useRecords = (params?: UseRecordsParams): UseRecordsResult => {
);

const record = {
ens: _params.ens,
ens: __ens,
isJAN: result.resolverAddress === offchainResolver?.resolverAddress,
records: {
...result,
Expand All @@ -137,6 +152,7 @@ export const useRecords = (params?: UseRecordsParams): UseRecordsResult => {
},
};

console.log(__ens, record);
checkEnsValid(record);

const sanitized = sanitizeRecords(record);
Expand All @@ -152,11 +168,15 @@ export const useRecords = (params?: UseRecordsParams): UseRecordsResult => {
forceUpdate = false
): Promise<Records> => {
const __chainId = _params?.chainId || _chainId;
const __ens = validateEns(_params?.ens) || _ens;
if (!__ens) {
throw new Error('Invalid ENS name');
}
// const __standard = _params?.standard || params?.standard;
const __standard = false;
if (!forceUpdate) {
const cachedRecords = queryClient.getQueryData(
buildRecordsBySubnameKey(_params?.ens, __chainId, __standard)
buildRecordsBySubnameKey(__ens, __chainId, __standard)
) as Records;
if (cachedRecords) {
return cachedRecords;
Expand All @@ -176,13 +196,16 @@ export const useRecords = (params?: UseRecordsParams): UseRecordsResult => {
let records: Records;
try {
records = await getRecords({
ens: _params.ens,
ens: __ens,
chainId: __chainId,
providerUrl: __providerUrl,
});
} catch (error) {
if (error instanceof Error && error.message.includes('NotFound')) {
throw error;
}
records = await getStandardRecords({
ens: _params.ens,
ens: __ens,
chainId: __chainId,
providerUrl: __providerUrl,
});
Expand All @@ -195,7 +218,7 @@ export const useRecords = (params?: UseRecordsParams): UseRecordsResult => {

// if (__standard) {
// records = await getStandardRecords({
// ens: _params.ens,
// ens: __ens,
// chainId: __chainId,
// providerUrl: __providerUrl,
// });
Expand All @@ -208,29 +231,41 @@ export const useRecords = (params?: UseRecordsParams): UseRecordsResult => {
// }

queryClient.setQueryData(
buildRecordsBySubnameKey(_params.ens, __chainId, __standard),
buildRecordsBySubnameKey(__ens, __chainId, __standard),
records
);
return records;
};

const query = useQuery({
...defaultOptions,
retry: (failureCount, error) => {
console.log(error);
if (error instanceof Error) {
if (
error.message.includes('NotFound') ||
error.message.includes('ETH address not found')
) {
return false;
}
}
return failureCount < 3;
},
queryKey: buildRecordsBySubnameKey(
params?.ens || '',
_ens || '',
_chainId
// params?.standard
),
queryFn: () =>
getRecordsInternal(
{
ens: params?.ens || '',
ens: _ens || '',
chainId: _chainId,
},
true
),
enabled:
Boolean(params?.ens) &&
Boolean(_ens) &&
Boolean(_chainId) &&
Boolean(_providerUrl) &&
Boolean(_enabled),
Expand Down
1 change: 1 addition & 0 deletions packages/@justaname.id/sdk/src/lib/api/axiosController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export const controlledAxiosPromise = <T extends NonNullable<unknown>>(
return res.data.result.data as T;
})
.catch((err: AxiosError<BaseResponse<null>>) => {
console.error(err);
if (err?.response) {
if (err?.response?.data?.result) {
if (err?.response?.data?.result?.error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -350,6 +350,7 @@ export const ProfileDialog: FC<ProfileDialogProps> = ({
contentStyle={{
width: '100%',
height: '100%',
pointerEvents: 'auto',
}}
fullScreen={minimized}
header={
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ export interface JustWeb3ContextProps {
) => Promise<void>;
handleJustWeb3Config: (config: JustWeb3ProviderConfig) => void;
handleOpenEnsProfile: (ens: string, chainId?: ChainId) => void;
handleCloseEnsProfile: () => void;
isSignInOpen: boolean;
config: JustWeb3ProviderConfig;
plugins: JustaPlugin[];
Expand All @@ -58,6 +59,7 @@ export const JustWeb3Context = createContext<JustWeb3ContextProps>({
handleOpenSignInDialog: () => {},
handleUpdateRecords: async () => {},
handleOpenEnsProfile: () => {},
handleCloseEnsProfile: () => {},
handleJustWeb3Config: () => {},
config: {},
plugins: [],
Expand Down Expand Up @@ -129,6 +131,10 @@ export const JustWeb3Provider: FC<JustWeb3ProviderProps> = ({
setEnsOpen({ ens, chainId });
};

const handleCloseEnsProfile = () => {
setEnsOpen(null);
};

useEffect(() => {
if (!updateRecord && updateRecordPromiseResolveRef.current) {
updateRecordPromiseResolveRef.current();
Expand Down Expand Up @@ -212,6 +218,7 @@ export const JustWeb3Provider: FC<JustWeb3ProviderProps> = ({
handleUpdateRecords: handleUpdateRecords,
handleJustWeb3Config,
handleOpenEnsProfile,
handleCloseEnsProfile,
}}
>
<MAppsProvider
Expand Down Expand Up @@ -279,6 +286,7 @@ export interface useJustWeb3 {
refreshEnsAuth: () => void;
connectedEns: UseEnsAuthReturn['connectedEns'];
openEnsProfile: (ens: string, chainId?: ChainId) => void;
closeEnsProfile: () => void;
updateRecords: (
records: Omit<UseSubnameUpdateFunctionParams, 'ens'> & { ens?: string }
) => Promise<void>;
Expand All @@ -305,7 +313,8 @@ export const useJustWeb3 = (): useJustWeb3 => {
} = useEnsAuth({
local: !context.config.enableAuth,
});
const { handleUpdateRecords, handleOpenEnsProfile } = context;
const { handleUpdateRecords, handleOpenEnsProfile, handleCloseEnsProfile } =
context;
const handleUpdateRecordsInternal = async (
records: Omit<UseSubnameUpdateFunctionParams, 'ens'> & {
ens?: string;
Expand Down Expand Up @@ -362,6 +371,7 @@ export const useJustWeb3 = (): useJustWeb3 => {
connectedEns,
refreshEnsAuth,
openEnsProfile: handleOpenEnsProfile,
closeEnsProfile: handleCloseEnsProfile,
chainId: justanameContext?.chainId,
};
};
Expand Down
14 changes: 6 additions & 8 deletions packages/@justweb3/xmtp-plugin/.storybook/preview.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import './polyfills';

import { scan } from 'react-scan'; // import this BEFORE react

if (typeof window !== 'undefined') {
scan({
enabled: true,
log: true, // logs render info to console (default: false)
});
}
// if (typeof window !== 'undefined') {
// scan({
// enabled: true,
// log: true, // logs render info to console (default: false)
// });
// }

export const decorators = [(Story) => <Story />];
Loading

0 comments on commit fb31ee7

Please sign in to comment.