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

fix: domain navigation #1001

Merged
merged 5 commits into from
Jan 28, 2025
Merged

Conversation

blessingbytes
Copy link
Contributor

@blessingbytes blessingbytes commented Jan 26, 2025

close #944

Summary by CodeRabbit

  • New Features

    • Introduced a new component for displaying available identities.
    • Enhanced functionality for managing user identities, including fetching and displaying profile pictures.
  • Improvements

    • Streamlined the user interface by prioritizing the display of available identities.
    • Simplified the rendering logic for identity management, reducing complexity.

Copy link

vercel bot commented Jan 26, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
app-starknet-id ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jan 28, 2025 0:30am

Copy link

vercel bot commented Jan 26, 2025

@blessingbytes is attempting to deploy a commit to the LFG Labs Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Jan 26, 2025

Walkthrough

The pull request modifies the pages/identities/[tokenId].tsx, pages/identities.tsx, and introduces a new component in components/identities/availableIdentities.tsx. The changes streamline the TokenIdPage component by removing unnecessary imports and state variables, focusing on displaying available identities through the new AvailableIdentities component. The Identities component is updated to conditionally render the AvailableIdentities based on owned identities, enhancing the user interface. Overall, the changes simplify identity management and improve the layout for better user interaction.

Changes

File Change Summary
pages/identities/[tokenId].tsx - Removed imports and state variables related to identity management
- Simplified rendering logic to use AvailableIdentities component
pages/identities.tsx - Added import for AvailableIdentities
- Updated rendering logic to conditionally display AvailableIdentities
components/identities/availableIdentities.tsx - Introduced new AvailableIdentities component for managing and displaying user identities

Assessment against linked issues

Objective Addressed Explanation
Add left column with user's domain wallets The implementation of a left column for domain wallets is not present.
Centralize domain selection and details on single page Changes do not fully centralize domain selection and details as required.
Simplify domain navigation The changes streamline navigation by focusing on available identities.

Possibly related PRs

  • Refont my identities page, wallet without idendity #943 #987: The changes in pages/identities.tsx involve the introduction of the AvailableIdentities component, which is also a focus in the main PR, indicating a direct relationship in terms of component functionality and rendering logic.
  • 951 #1003: The changes in pages/identities.tsx regarding the removal of the ClickableAction component and its replacement with the AddButton are relevant as they reflect a shift in how identities are managed and displayed, aligning with the main PR's focus on simplifying the identity management logic.
  • Fix #946: Refont of identity card button  #1006: The refactoring of the ClickableAction component in this PR may relate to the changes in the main PR, as both involve updates to how identity-related actions are presented in the UI.

Suggested labels

🔥 Ready for review

Suggested reviewers

  • Marchand-Nicolas

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
pages/identities/[tokenId].tsx (3)

208-220: Add accessibility attributes to navigation buttons.

The identity navigation buttons should include proper ARIA labels for better accessibility.

   <button
+    aria-label={`Navigate to identity ${domain.id}`}
     className={`${
       domain.id === router.query.tokenId
         ? "text-[#402D28] hover:text-[#CDCCCC]"
         : " text-[#CDCCCC] hover:text-[#402D28]"
     }font-medium text-lg leading-5 cursor-pointer border-[#CDCCCC] border-b md:border-none md:py-0 py-6 md:my-3 block w-full`}
     key={index}
     onClick={() => router.push(`/identities/${domain.id}`)}
   >
     {domain.id}
   </button>

222-232: Add loading state for mint operation.

The "ADD IDENTITIES" button should show a loading state during the minting process to prevent multiple clicks.

   <button
     className="bottom-4 w-full justify-center text-center items-center font-quickZap font-normal flex gap-2"
+    disabled={minting}
     onClick={
       address
         ? () => mint()
         : () => setShowWalletConnectModal(true)
     }
   >
-    <FaPlus />
+    {minting ? (
+      <span className="animate-spin">↻</span>
+    ) : (
+      <FaPlus />
+    )}
     ADD IDENTITIES
   </button>

172-180: Remove or document commented code.

The commented-out code for fetching external domains should either be removed if it's no longer needed or documented with a TODO comment explaining why it's kept for future use.

-      // fetch(
-      //   `${
-      //     process.env.NEXT_PUBLIC_SERVER_LINK
-      //   }/addr_to_external_domains?addr=${hexToDecimal(address)}`
-      // )
-      //   .then((response) => response.json())
-      //   .then((data: ExternalDomains) => {
-      //     setExternalDomains(data.domains);
-      //   });
+      // TODO: External domains feature to be implemented in future sprint
+      // Keeping this code for reference
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d75bbf and aadcd72.

📒 Files selected for processing (1)
  • pages/identities/[tokenId].tsx (6 hunks)
🔇 Additional comments (3)
pages/identities/[tokenId].tsx (3)

9-13: LGTM! New imports are properly organized.

The added imports from @starknet-react/core and other utilities align well with the new wallet connection and transaction functionality.

Also applies to: 23-27


52-62: LGTM! Transaction setup is properly memoized.

The contract address is correctly accessed from environment variables and the callData is properly memoized.


47-50: 🛠️ Refactor suggestion

Consider using a more robust method for generating random token IDs.

Using Math.random() for token ID generation could potentially lead to collisions. Consider using a more cryptographically secure random number generator or implementing a proper token ID allocation strategy.

-  const randomTokenId: number = Math.floor(Math.random() * 1000000000000);
+  const randomTokenId: number = BigInt(
+    "0x" + crypto.getRandomValues(new Uint8Array(8)).reduce((s, b) => s + b.toString(16).padStart(2, '0'), '')
+  ).toString();

pages/identities/[tokenId].tsx Outdated Show resolved Hide resolved
Copy link
Collaborator

@Marchand-Nicolas Marchand-Nicolas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well done, it looks good and it works well! There are a few changes to do
In the list, show the domain if available instead of the id
Screenshot 2025-01-27 at 10 01 45 AM

Instead of showing the identity list in https://app-starknet-g48puevic-lfglabs.vercel.app/identities you should show your new menu, with the first identity selected by default
Screenshot 2025-01-27 at 10 03 46 AM

On figma the shadow is not the same, and you forgot the small border

image

There is more padding on figma
image

@Marchand-Nicolas Marchand-Nicolas added the ❌ Change request Change requested from reviewer label Jan 27, 2025
@blessingbytes
Copy link
Contributor Author

@Marchand-Nicolas, please how can i get the domain name for each mint domain, currently am able to get only the id of the mint domain,
Is there a specific function or a doc i can use to get the domain name

@Marchand-Nicolas
Copy link
Collaborator

@Marchand-Nicolas, please how can i get the domain name for each mint domain, currently am able to get only the id of the mint domain, Is there a specific function or a doc i can use to get the domain name

Hello, I answered on telegram :)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
pages/identities/[tokenId].tsx (1)

196-208: Add loading state for owned identities list.

The list of owned identities lacks a loading state, which could lead to a jarring user experience while data is being fetched.

+  const [isLoadingIdentities, setIsLoadingIdentities] = useState(true);

   useEffect(() => {
     if (address) {
+      setIsLoadingIdentities(true);
       fetch(...)
         .then((data) => {
           setOwnedIdentities(data.full_ids);
+          setIsLoadingIdentities(false);
         })
         .catch((error) => {
           console.error('Failed to fetch owned identities:', error);
           setOwnedIdentities([]);
+          setIsLoadingIdentities(false);
         });
     }
   }, [address, router.asPath]);

   // In the JSX
   <div className="h-[280px] md:h-[480px] overflow-y-auto">
+    {isLoadingIdentities ? (
+      <div className="text-center py-4">Loading...</div>
+    ) : (
       {ownedIdentities.map((domain, index) => (
         // ... existing code
       ))}
+    )}
   </div>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between aadcd72 and 346cfbc.

📒 Files selected for processing (2)
  • pages/identities.tsx (1 hunks)
  • pages/identities/[tokenId].tsx (6 hunks)
🔇 Additional comments (2)
pages/identities/[tokenId].tsx (2)

172-178: Improve error handling in wallet connection.

The wallet connection has the same issues as previously identified:

  1. Using @ts-ignore is not recommended
  2. localStorage access should be wrapped in try-catch

267-272: LGTM: WalletConnect integration looks good.

The WalletConnect component is properly integrated with the necessary props.

pages/identities.tsx Outdated Show resolved Hide resolved
Comment on lines 52 to 62
const callData = useMemo(() => {
return {
contractAddress: process.env.NEXT_PUBLIC_IDENTITY_CONTRACT as string,
entrypoint: "mint",
calldata: [randomTokenId.toString()],
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const { sendAsync: execute } = useSendTransaction({
calls: [callData],
});
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Add error handling for transaction execution.

The mint function lacks error handling, which could lead to unhandled promise rejections.

-  function mint() {
-    execute();
+  async function mint() {
+    try {
+      await execute();
+    } catch (error) {
+      console.error('Failed to execute mint transaction:', error);
+      // Consider showing an error notification to the user
+    }
   }

Committable suggestion skipped: line range outside the PR's diff.

pages/identities/[tokenId].tsx Outdated Show resolved Hide resolved
Copy link
Collaborator

@Marchand-Nicolas Marchand-Nicolas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just little tweaks and we're good! The domain fetching works well, good job!

@@ -95,6 +95,12 @@ const Identities: NextPage = () => {
execute();
}

useEffect(()=>{
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instead of redirecting the user, wrap your code from pages/identities/[tokenId].tsx in a component you can reuse in both files

@@ -16,6 +20,11 @@ import { formatHexString } from "../../utils/stringService";
import { getDomainData } from "@/utils/cacheDomainData";
import { useSearchParams } from "next/navigation";
import IdentityActionsSkeleton from "@/components/identities/skeletons/identityActionsSkeleton";
import { hexToDecimal } from "@/utils/feltService";
import AddButton from "@/components/UI/AddButtonIdentities";
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can remove this import, it is not used

Copy link
Collaborator

@Marchand-Nicolas Marchand-Nicolas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oops miss click sorry I mean't to request these changes @blessingbytes

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (3)
components/identities/availableIdentities.tsx (3)

158-168: ⚠️ Potential issue

Improve error handling in fetch operation.

The fetch operation for owned identities lacks proper error handling.


170-176: ⚠️ Potential issue

Improve error handling in wallet connection.

The wallet connection code needs proper typing and error handling for localStorage access.


152-154: ⚠️ Potential issue

Add error handling for transaction execution.

The mint function needs proper error handling.

🧹 Nitpick comments (7)
components/identities/availableIdentities.tsx (5)

1-25: Consider adding a Props interface for better type safety.

Define an explicit interface for the component's props to improve maintainability and type safety.

+interface AvailableIdentitiesProps {
+  tokenId: string;
+}
+
-const AvailableIdentities = ({ tokenId }: { tokenId: string }) => {
+const AvailableIdentities = ({ tokenId }: AvailableIdentitiesProps) => {

Also applies to: 26-27


29-29: Remove commented code.

Remove the commented line as it's no longer needed.

-  //const tokenId: string = router.query.tokenId as string;

44-45: Add type definition for FullId and move random ID generation to a utility function.

The FullId type is not defined, and the random token ID generation logic could be extracted for better maintainability.

+interface FullId {
+  id: string;
+  domain?: string;
+}
+
+const generateRandomTokenId = (): number => Math.floor(Math.random() * 1000000000000);
+
 const [ownedIdentities, setOwnedIdentities] = useState<FullId[]>([]);
-const randomTokenId: number = Math.floor(Math.random() * 1000000000000);
+const randomTokenId: number = generateRandomTokenId();

137-150: Consider making polling intervals configurable.

The refresh intervals (1s for minting and 30s for regular updates) should be configurable constants.

+const MINTING_POLL_INTERVAL = 1000; // 1 second
+const REGULAR_POLL_INTERVAL = 30000; // 30 seconds
+
 useEffect(() => {
   if (minting && tokenId && !identity) {
-    const interval = setInterval(() => refreshData(), 1000);
+    const interval = setInterval(() => refreshData(), MINTING_POLL_INTERVAL);
     return () => clearInterval(interval);
   }
 }, [minting, tokenId, identity, refreshData]);

 useEffect(() => {
   if (tokenId) {
     refreshData();
-    const timer = setInterval(() => refreshData(), 30e3);
+    const timer = setInterval(() => refreshData(), REGULAR_POLL_INTERVAL);
     return () => clearInterval(timer);
   }
 }, [tokenId, refreshData]);

183-245: Consider extracting complex UI logic into separate components.

The nested conditional rendering and complex class name logic could be simplified by extracting them into separate components.

Consider creating:

  1. IdentityList component for the list of owned identities
  2. MintButton component for the add identities button
  3. Moving inline styles to CSS modules

This would improve readability and maintainability.

pages/identities/[tokenId].tsx (2)

15-15: Replace window.history.back() with router navigation.

Using window.history.back() can lead to unexpected behavior. Consider using Next.js router for consistent navigation.

-<BackButton onClick={() => window.history.back()} />
+<BackButton onClick={() => router.back()} />

8-21: Consider adding error boundaries.

The component should handle potential errors from the AvailableIdentities component gracefully.

+import ErrorBoundary from '@/components/ErrorBoundary';

 const TokenIdPage: NextPage = () => {
   const router = useRouter();
   const tokenId: string = router.query.tokenId as string;
   return (
     <div className={homeStyles.wrapperScreen}>
       <div className="mt-24">
         <div className="ml-8 mb-5">
           <BackButton onClick={() => router.back()} />
         </div>
+        <ErrorBoundary fallback={<div>Something went wrong</div>}>
           <AvailableIdentities tokenId={tokenId} />
+        </ErrorBoundary>
       </div>
     </div>
   );
 };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 346cfbc and a71c12b.

📒 Files selected for processing (3)
  • components/identities/availableIdentities.tsx (1 hunks)
  • pages/identities.tsx (3 hunks)
  • pages/identities/[tokenId].tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pages/identities.tsx

Copy link
Collaborator

@Marchand-Nicolas Marchand-Nicolas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lgtm! Good job

@Marchand-Nicolas Marchand-Nicolas merged commit e73430f into lfglabs-dev:testnet Jan 28, 2025
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
❌ Change request Change requested from reviewer
Projects
None yet
Development

Successfully merging this pull request may close these issues.

New Domain navigation/ Add left column
2 participants