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

feat: verify solidity contract via contract code #1220

Merged
merged 7 commits into from
Feb 10, 2025

Conversation

evilpeach
Copy link
Collaborator

@evilpeach evilpeach commented Feb 6, 2025

Summary by CodeRabbit

  • New Features

    • Expanded EVM contract verification options, now supporting multiple methods for Solidity and Vyper.
    • Introduced new modals providing real-time feedback during verification (loading, success, and failure).
    • Added enhanced UI elements including tooltips, search functionality in contract details, and an onboarding widget.
    • Added EVM contract details including constructor arguments, method shortcuts, and code preview.
    • Implemented EVM gas refund logic and interaction forms for contracts.
    • Added support for fetching EVM verification configurations from an API.
  • Improvements

    • Enhanced error message display to wrap long texts.
    • Streamlined UI by conditionally rendering verification sections based on contract status.
    • Improved the EVM contract verification process with support for multiple verification methods.
  • Bug Fixes

    • Resolved issues with contract address validation and overall verification process feedback.

@evilpeach evilpeach requested a review from Poafs1 February 6, 2025 04:08
Copy link

vercel bot commented Feb 6, 2025

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

Name Status Preview Comments Updated (UTC)
celatone-frontend-staging ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 10, 2025 6:29am
6 Skipped Deployments
Name Status Preview Comments Updated (UTC)
celatone-frontend-main ⬜️ Ignored (Inspect) Visit Preview Feb 10, 2025 6:29am
initia-celatone-frontend ⬜️ Ignored (Inspect) Visit Preview Feb 10, 2025 6:29am
neutron-celatone-frontend ⬜️ Ignored (Inspect) Visit Preview Feb 10, 2025 6:29am
osmosis-celatone-frontend ⬜️ Ignored (Inspect) Visit Preview Feb 10, 2025 6:29am
sei-celatone-frontend ⬜️ Ignored (Inspect) Visit Preview Feb 10, 2025 6:29am
terra-celatone-frontend ⬜️ Ignored (Inspect) Visit Preview Feb 10, 2025 6:29am

Copy link

coderabbitai bot commented Feb 6, 2025

Walkthrough

The pull request introduces extensive updates to the EVM contract verification system. It adds numerous new features and UI enhancements, including updated changelog documentation, refined error-display behavior, conditional rendering based on verification status, and several new modal components for handling failure, loading, and success states. Type definitions and default configurations have been revised, and new API functions and hooks have been added to support various verification methods, including support for Solidity and Vyper.

Changes

File(s) Change Summary
CHANGELOG.md Added entries for new features, improvements, and bug fixes across various EVM contract verification functionalities (e.g., contract code verification, library contracts, method shortcuts, tooltips, interaction forms, etc.).
src/lib/components/modal/evm-verify-status/EvmVerifyProcess.tsx Added wordBreak="break-word" to improve error message formatting.
src/lib/pages/evm-contract-details/components/evm-contract-details-contract-info/index.tsx Implemented conditional rendering of EvmVerifySection based on the contract’s verified status.
src/lib/pages/evm-contract-details/components/evm-contract-details-overview/OverviewVerifiedInfo.tsx Updated the optimization label rendering with a conditional check for the optimizer field (showing runs, “No”, or “N/A”).
src/lib/pages/evm-contract-verify/components/EvmContractVerifyForms.tsx,
src/lib/pages/evm-contract-verify/components/EvmContractVerifyOptions.tsx
Renamed VerifyOptions to EvmVerifyOptions in switch-case statements and radio inputs for verification options.
src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/* Added new modal components: EvmContractVerifyFailedModal, EvmContractVerifyLoadingModal, EvmContractVerifyModalBody, and EvmContractVerifySuccessModal to manage verification UI states.
src/lib/pages/evm-contract-verify/index.tsx Refactored submission logic with additional checks, integrated useCelatoneApp, and updated type references to manage how modals are displayed based on verification methods.
src/lib/pages/evm-contract-verify/helpers.ts Modified default form values: updated runs from number to string and changed licenseType default from an empty string to undefined.
src/lib/pages/evm-contract-verify/types.ts Enhanced type definitions by renaming VerifyOptions to EvmVerifyOptions, introducing OptimizerConfig, and updating licenseType and option type schemas.
src/lib/services/types/verification/evm.ts Adjusted the zEvmVerifyInfo schema: made optimizer optional and provided a default value for settings.
src/lib/services/verification/evm/api.ts Introduced new functions submitEvmVerify and submitEvmVerifyFlatten along with related types to handle structured EVM verification submissions.
src/lib/services/verification/evm/index.ts Added a new mutation hook useSubmitEvmVerify using useMutation to streamline verification request submissions.
src/lib/services/verification/evm/utils.ts Added getVerifierUrl to construct API endpoints based on the provided EvmVerifyOptions, ensuring the correct verifier URL is used.
src/lib/pages/evm-contract-verify/components/ContractLibraries.tsx Renamed variable in contract library fields mapping for clarity and updated input names to ensure correct form handling.

Sequence Diagram(s)

sequenceDiagram
  participant U as User
  participant P as EVM Verification Page
  participant H as useSubmitEvmVerify Hook
  participant API as Verification API

  U->>P: Submit verification request
  P->>H: Call submitEvmVerify
  H->>API: Send verification data (option, language, licenseType, etc.)
  API-->>H: Return verification response
  H-->>P: Update verification state
  alt Verification error
    P->>Modal: Display Failure Modal (EvmContractVerifyFailedModal)
  else Request in progress
    P->>Modal: Display Loading Modal (EvmContractVerifyLoadingModal)
  else Verification success
    P->>Modal: Display Success Modal (EvmContractVerifySuccessModal)
  end
Loading

Possibly related PRs

Suggested reviewers

  • songwongtp
  • Poafs1

Poem

I hopped through lines of code today,
In EVM fields where features now play.
Modals glow with states so clear,
Options renamed to bring success near.
With each bug fixed and charm displayed,
I twirl and smile in a rabbit’s parade!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

@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: 2

🧹 Nitpick comments (13)
src/lib/services/verification/evm/api.ts (1)

111-121: Extend support for additional verification options in 'submitEvmVerify'

The submitEvmVerify function currently handles only the SolidityContractCode option. To enhance functionality and user experience, consider implementing support for the other EvmVerifyOptions or providing placeholders with clear error messages.

Do you want me to assist in implementing the handling for the other verification options or open a new issue to track this task?

src/lib/services/verification/evm/utils.ts (1)

4-22: Refactor 'getVerifierUrl' using a mapping object for maintainability

Replacing the switch statement with a mapping object can improve readability and ease future extensions as new verification options are added.

Apply this diff to refactor the function:

 export const getVerifierUrl = (option: EvmVerifyOptions) => {
   const baseUrl = `${CELATONE_VERIFICATION_API}/evm/verification`;
-  switch (option) {
-    case EvmVerifyOptions.SolidityUploadFiles:
-      return `${baseUrl}/solidity/multi`;
-    case EvmVerifyOptions.SolidityContractCode:
-      return `${baseUrl}/solidity/flatten`;
-    case EvmVerifyOptions.SolidityJsonInput:
-      return `${baseUrl}/solidity/standard-json`;
-    case EvmVerifyOptions.VyperUploadFile:
-      return `${baseUrl}/vyper/upload-file`;
-    case EvmVerifyOptions.VyperContractCode:
-      return `${baseUrl}/vyper/contract-code`;
-    case EvmVerifyOptions.VyperJsonInput:
-      return `${baseUrl}/vyper/json-input`;
-    default:
-      throw new Error("Unsupported option (getVerifierUrl)");
-  }
+  const verifierUrlMap = {
+    [EvmVerifyOptions.SolidityUploadFiles]: `${baseUrl}/solidity/multi`,
+    [EvmVerifyOptions.SolidityContractCode]: `${baseUrl}/solidity/flatten`,
+    [EvmVerifyOptions.SolidityJsonInput]: `${baseUrl}/solidity/standard-json`,
+    [EvmVerifyOptions.VyperUploadFile]: `${baseUrl}/vyper/upload-file`,
+    [EvmVerifyOptions.VyperContractCode]: `${baseUrl}/vyper/contract-code`,
+    [EvmVerifyOptions.VyperJsonInput]: `${baseUrl}/vyper/json-input`,
+  };
+
+  const url = verifierUrlMap[option];
+  if (!url) {
+    throw new Error("Unsupported option (getVerifierUrl)");
+  }
+  return url;
 };
src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/index.tsx (1)

28-28: Consider responsive design for modal width.

The fixed width of 645px might cause issues on smaller screens. Consider using responsive values or adding a maxW prop to handle different screen sizes.

-    <ModalContent w="645px" bg="gray.800" maxW="100vw" py={10}>
+    <ModalContent w={{ base: "90vw", md: "645px" }} bg="gray.800" maxW="100vw" py={10}>
src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifyFailedModal.tsx (1)

29-32: Enhance error handling and responsiveness.

Two suggestions for improvement:

  1. Consider passing the actual error message to provide more specific feedback.
  2. The fixed width of 334px might cause issues on smaller screens.
-    <ModalBody overflow="overlay" pt={2} w="334px" mx="auto">
+    <ModalBody overflow="overlay" pt={2} w={{ base: "90%", md: "334px" }} mx="auto">
       <Text variant="body2" color="text.dark" textAlign="center">
-        There is something wrong with submission. Please try again later.
+        {errorMessage || "There is something wrong with submission. Please try again later."}
       </Text>
src/lib/services/verification/evm/index.ts (1)

35-38: Enhance mutation configuration.

Consider adding error handling, retry logic, and success/error callbacks to the mutation configuration for better error handling and user feedback.

 export const useSubmitEvmVerify = () =>
   useMutation({
     mutationFn: submitEvmVerify,
+    retry: 2,
+    onError: (error) => {
+      console.error('Contract verification failed:', error);
+    },
+    onSuccess: () => {
+      // Invalidate and refetch relevant queries
+      queryClient.invalidateQueries([CELATONE_QUERY_KEYS.EVM_VERIFY_INFO]);
+    },
   });
src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifyModalBody.tsx (2)

24-32: Simplify loading state management.

The fake loading implementation with a hard-coded timeout could be improved:

  1. Consider making the timeout duration configurable
  2. The loading state could be simplified to avoid unnecessary re-renders
+const LOADING_TIMEOUT = 1500;
+
 useEffect(() => {
   setFakeLoading(true);
 
   const timeoutId = setTimeout(() => {
-    setFakeLoading((newFakeLoading) => !newFakeLoading);
+    setFakeLoading(false);
-  }, 1500);
+  }, LOADING_TIMEOUT);
 
   return () => clearTimeout(timeoutId);
 }, [isLoading]);

36-40: Consider adding loading state transition.

The abrupt switch between loading and success states might be jarring. Consider adding a fade transition for smoother UX.

+import { Fade } from "@chakra-ui/react";

 return isLoading || fakeLoading ? (
-  <EvmContractVerifyLoadingModal />
+  <Fade in={true}><EvmContractVerifyLoadingModal /></Fade>
 ) : (
-  <EvmContractVerifySuccessModal control={control} />
+  <Fade in={true}><EvmContractVerifySuccessModal control={control} /></Fade>
 );
src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifySuccessModal.tsx (2)

38-48: Add aria-label to improve accessibility.

The modal header contains an icon and heading but lacks proper accessibility attributes.

-      <ModalHeader w="full">
+      <ModalHeader w="full" aria-label="Contract Verification Success">
         <ModalCloseButton color="gray.600" />
         <Stack alignItems="center" gap={4} w="100%">
           <CustomIcon
             name="check-circle-solid"
             color="success.main"
             boxSize={14}
+            aria-hidden="true"
           />
           <Heading variant="h5">Submitted Verification!</Heading>
         </Stack>
       </ModalHeader>

68-81: Consider adding loading states to buttons.

The footer buttons should indicate loading states when clicked to prevent double submissions.

       <ModalFooter pb={0} gap={4}>
         <Button
           variant="outline-primary"
           onClick={() => navigate({ pathname: "/evm-contract-verify" })}
           w="full"
+          isLoading={isNavigating}
+          loadingText="Navigating..."
         >
           Verify More
         </Button>
         <AppLink href={`/evm-contracts/${contractAddress}`}>
-          <Button variant="primary" w="full">
+          <Button
+            variant="primary"
+            w="full"
+            isLoading={isNavigating}
+            loadingText="Loading Details..."
+          >
             See Contract Details
           </Button>
         </AppLink>
       </ModalFooter>
src/lib/pages/evm-contract-verify/components/EvmContractVerifyOptions.tsx (1)

10-40: Refactor radio options to reduce code duplication and improve maintainability.

The radio options for both Vyper and Solidity contain repetitive code that could be extracted into a reusable configuration.

+const RADIO_STYLES = {
+  variant: "gray-card",
+  width: "fit-content",
+  overflow: "hidden",
+  w: "full",
+} as const;
+
+const VYPER_OPTIONS = [
+  { value: EvmVerifyOptions.VyperUploadFile, label: "Upload File" },
+  { value: EvmVerifyOptions.VyperContractCode, label: "Contract Code" },
+  { value: EvmVerifyOptions.VyperJsonInput, label: "JSON Input" },
+] as const;
+
+const SOLIDITY_OPTIONS = [
+  { value: EvmVerifyOptions.SolidityUploadFiles, label: "Upload File(s)" },
+  { value: EvmVerifyOptions.SolidityContractCode, label: "Contract Code" },
+  { value: EvmVerifyOptions.SolidityJsonInput, label: "JSON Input" },
+  { value: EvmVerifyOptions.SolidityHardhat, label: "Hardhat" },
+  { value: EvmVerifyOptions.SolidityFoundry, label: "Foundry" },
+] as const;
+
 const EvmContractVerifyOptionsVyper = () => (
   <>
-    <Radio
-      variant="gray-card"
-      width="fit-content"
-      value={EvmVerifyOptions.VyperUploadFile}
-      overflow="hidden"
-      w="full"
-    >
-      Upload File
-    </Radio>
-    // ... more radio options
+    {VYPER_OPTIONS.map(({ value, label }) => (
+      <Radio key={value} {...RADIO_STYLES} value={value}>
+        {label}
+      </Radio>
+    ))}
   </>
 );

Also applies to: 42-90

src/lib/services/types/verification/evm.ts (1)

80-80: LGTM! Consider adding JSDoc comments for better documentation.

The schema changes for making the optimizer optional and providing a default settings value are well-implemented. Consider adding JSDoc comments to document the purpose and format of these fields.

+/** Optimizer configuration in JSON string format. Example: { "enabled": true, "runs": 200 } */
 optimizer: z.string().optional(),
 constructor_arguments: z.string(),
 abi: z.string().optional(),
 bytecode_type: z.string(),
 verified_timestamp: zUtcDate.optional(),
 submitted_timestamp: zUtcDate,
 error_message: z.string().optional(),
+/** Contract verification settings in JSON string format. Defaults to empty object. */
 settings: z.string().default("{}"),

Also applies to: 87-87, 93-95

src/lib/pages/evm-contract-verify/types.ts (1)

29-33: Consider using numeric validation for the optimizer runs.

The runs field is changed from number to string type. While this allows for more flexible input handling, consider adding numeric validation to ensure valid optimizer configuration.

const zOptimizerConfig = z.object({
  enabled: z.boolean(),
-  runs: z.string(),
+  runs: z.string().regex(/^\d+$/, "Runs must be a positive number"),
});
src/lib/pages/evm-contract-verify/index.tsx (1)

92-99: Consider destructuring form values more selectively.

The destructuring of form values is comprehensive but could be more selective based on actual usage to avoid unnecessary re-renders.

const {
-  licenseType,
-  contractAddress,
-  language,
-  compilerVersion,
-  option,
-  verifyForm,
+  ...values
} = watch(['licenseType', 'contractAddress', 'language', 'compilerVersion', 'option', 'verifyForm']);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 79b8f0e and 7a2e626.

📒 Files selected for processing (18)
  • CHANGELOG.md (1 hunks)
  • src/lib/components/modal/evm-verify-status/EvmVerifyProcess.tsx (1 hunks)
  • src/lib/pages/evm-contract-details/components/evm-contract-details-contract-info/index.tsx (1 hunks)
  • src/lib/pages/evm-contract-details/components/evm-contract-details-overview/OverviewVerifiedInfo.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/EvmContractVerifyForms.tsx (2 hunks)
  • src/lib/pages/evm-contract-verify/components/EvmContractVerifyOptions.tsx (9 hunks)
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifyFailedModal.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifyLoadingModal.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifyModalBody.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifySuccessModal.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/index.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/helpers.ts (2 hunks)
  • src/lib/pages/evm-contract-verify/index.tsx (9 hunks)
  • src/lib/pages/evm-contract-verify/types.ts (5 hunks)
  • src/lib/services/types/verification/evm.ts (1 hunks)
  • src/lib/services/verification/evm/api.ts (2 hunks)
  • src/lib/services/verification/evm/index.ts (2 hunks)
  • src/lib/services/verification/evm/utils.ts (1 hunks)
🔇 Additional comments (13)
src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifyLoadingModal.tsx (1)

1-25: UI Implementation of 'EvmContractVerifyLoadingModal' is approved

The component is well-structured and effectively uses Chakra UI elements to provide a clear loading state to the user. The design enhances user experience during the verification submission process.

src/lib/pages/evm-contract-details/components/evm-contract-details-overview/OverviewVerifiedInfo.tsx (1)

34-38: LGTM! Improved null safety and readability.

The changes enhance error handling by safely accessing the optimizer property and provide clear fallback values.

src/lib/pages/evm-contract-verify/components/EvmContractVerifyForms.tsx (1)

2-2: LGTM! Consistent type naming.

The renaming of VerifyOptions to EvmVerifyOptions improves type naming consistency across the codebase.

Also applies to: 33-33, 40-40, 47-47, 49-49, 51-51, 54-54, 61-61, 68-68

src/lib/components/modal/evm-verify-status/EvmVerifyProcess.tsx (1)

46-50: LGTM! Better error message wrapping.

Added wordBreak="break-word" to prevent long error messages from overflowing their container.

src/lib/pages/evm-contract-verify/helpers.ts (2)

33-33: LGTM! Better type semantics.

Using undefined instead of empty string for licenseType better represents the absence of a license type.


13-13: Verify API compatibility with string type for optimizer runs.

The optimizer runs value has been changed from number (200) to string ("200"). Please ensure this aligns with the API's expectations.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Search for API request handling of optimizer runs
rg -A 5 'optimizer.*runs' --type ts

Length of output: 1842


API compatibility with string for optimizer runs verified.
The API conversion logic in src/lib/services/verification/evm/api.ts uses Number(optimizerConfig.runs), which means the string value from the configuration (e.g., "200") is correctly converted to a number before being sent. No action is required.

src/lib/pages/evm-contract-details/components/evm-contract-details-contract-info/index.tsx (1)

33-38: LGTM! Clean implementation of conditional rendering.

The conditional rendering of EvmVerifySection based on verification status is well-implemented and improves the UI by showing relevant content only when needed.

src/lib/pages/evm-contract-verify/types.ts (3)

1-4: LGTM! Clean import organization.

The imports are well-organized and the addition of EvmVerifyLicenseType aligns with the EVM-specific naming convention.


9-18: LGTM! Clear enum naming and comprehensive options.

The rename from VerifyOptions to EvmVerifyOptions improves clarity by making the EVM context explicit. The enum values cover all verification methods for both Solidity and Vyper.


114-116: LGTM! Improved type safety for license and verification options.

The schema updates properly leverage the enum types:

  • Making licenseType optional with native enum validation
  • Using the renamed EvmVerifyOptions enum
src/lib/pages/evm-contract-verify/index.tsx (2)

1-6: LGTM! Well-organized imports.

The imports are logically grouped and the addition of useCelatoneApp follows the established pattern.


304-320: LGTM! Clean modal rendering logic.

The conditional rendering of verification modals based on isVerifyByTools is well-implemented.

CHANGELOG.md (1)

42-43: LGTM! Well-documented changelog entry.

The changelog entry for PR #1220 follows the Keep a Changelog format and clearly describes the addition of EVM contract verification for Solidity with contract code.

Copy link
Collaborator

@Poafs1 Poafs1 left a comment

Choose a reason for hiding this comment

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

overall lgtm na. Just few changes from my side

Copy link

@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: 2

♻️ Duplicate comments (2)
src/lib/services/verification/evm/api.ts (1)

74-94: ⚠️ Potential issue

Add error handling to submitEvmVerifyFlatten.

The function lacks error handling for the axios request.

src/lib/pages/evm-contract-verify/index.tsx (1)

123-145: 🛠️ Refactor suggestion

Enhance error handling in submit function.

The error handling remains basic and could be improved by:

  • Adding specific error types
  • Providing user feedback
  • Logging structured error information
 const handleSubmit = async () => {
   if (!option || !language || !licenseType) return;

   // open modal for either verification status or verification result
   onOpen();

   // if verify by tools, don't need to submit verification
   if (isVerifyByExternals) return;

   try {
     await mutateAsync({
       option,
       verifyForm,
       contractAddress,
       compilerVersion,
       licenseType,
       chainId: currentChainId,
     });
   } catch (error) {
-    // eslint-disable-next-line no-console
-    console.error("Error submitting verification", error);
+    const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
+    console.error("Error submitting verification:", {
+      error: errorMessage,
+      contractAddress,
+      option,
+      chainId: currentChainId,
+    });
+    // Consider adding toast notification or error state management here
   }
 };
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7a2e626 and f15bb25.

📒 Files selected for processing (7)
  • src/lib/pages/evm-contract-verify/components/ContractLibraries.tsx (2 hunks)
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifyFailedModal.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifySuccessModal.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/index.tsx (9 hunks)
  • src/lib/services/types/verification/evm.ts (3 hunks)
  • src/lib/services/verification/evm/api.ts (2 hunks)
  • src/lib/services/verification/evm/index.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifyFailedModal.tsx
🧰 Additional context used
🪛 Biome (1.9.4)
src/lib/services/verification/evm/api.ts

[error] 56-56: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

🔇 Additional comments (10)
src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifySuccessModal.tsx (4)

1-24: LGTM!

The imports are well-organized and the type definitions are properly structured.


25-35: LGTM!

The component is well-structured and hooks are used appropriately.


36-67: LGTM!

The modal structure is well-organized with appropriate use of Chakra UI components for layout and styling.


68-81: Button sizing has been fixed.

Both buttons now have equal width using flex: 1, addressing the previous review comment about unequal button sizes.

src/lib/services/verification/evm/index.ts (1)

35-46: Consider enhancing mutation behavior.

The mutation hook correctly invalidates queries on success. However, based on past review comments, consider:

  1. Adding a minimum loading time to prevent UI flicker
  2. Verifying if additional queries need invalidation

Would you like me to propose an enhanced implementation with these improvements?

src/lib/services/verification/evm/api.ts (1)

110-113: Plan implementation of other verification options.

The TODO comment indicates pending implementation of other verification options. Consider creating tracking issues for each pending option.

Would you like me to help create tracking issues for the remaining verification options?

src/lib/pages/evm-contract-verify/components/ContractLibraries.tsx (1)

71-95: LGTM! Improved field naming and path construction.

The changes enhance code clarity by:

  1. Using more descriptive variable names
  2. Constructing explicit field paths
src/lib/services/types/verification/evm.ts (2)

85-92: LGTM! Improved schema flexibility.

The changes enhance the schema by:

  1. Making optimizer field optional
  2. Providing default settings value

109-124: LGTM! Well-structured verification types.

The new types provide clear separation of concerns and good type safety for verification submissions.

src/lib/pages/evm-contract-verify/index.tsx (1)

114-116: Consider renaming for consistency with past feedback.

The variable name isVerifyByExternals differs from the previously suggested isVerifyByTools. Consider using consistent naming across the codebase.

-  const isVerifyByExternals =
+  const isVerifyByTools =
     option === EvmVerifyOptions.SolidityFoundry ||
     option === EvmVerifyOptions.SolidityHardhat;

Copy link
Collaborator

@Poafs1 Poafs1 left a comment

Choose a reason for hiding this comment

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

lgtm

Copy link

@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

🔭 Outside diff range comments (1)
src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityHardhat.tsx (1)

25-51:

🧩 Analysis chain

Consider adding input validation for config generation.

The configuration generation uses template literals with potentially undefined values. Consider adding validation or default values for:

  • jsonRpc
  • currentChainId
  • evmChainId

🏁 Script executed:

#!/bin/bash
# Description: Check if these values are validated elsewhere in the codebase

# Search for validation of these values
rg -A 3 "(jsonRpc|currentChainId|evmChainId).*validation|validate.*(jsonRpc|currentChainId|evmChainId)"

Length of output: 105


I'll run another script targeting the specific file to check if any default values or validation logic is applied for these variables.

Once the results are available, we can confirm whether these variables are assigned validated defaults elsewhere in the file. If no default assignments or validation logic is found, it indicates that the configuration is generated with potentially undefined values, confirming that additional validation should be added.


🏁 Script executed:

#!/bin/bash
# Search for variable assignments or default values for jsonRpc, currentChainId, and evmChainId
grep -R "const .*jsonRpc" -n src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityHardhat.tsx || true
grep -R "const .*currentChainId" -n src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityHardhat.tsx || true
grep -R "const .*evmChainId" -n src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityHardhat.tsx || true

Length of output: 755


Validation Enhancements Needed for Config Generation

• The jsonRpc variable uses a fallback ("<invalid_network>") when evm.enabled is false, which partially guards against undefined values.
• However, currentChainId (sourced from useCelatoneApp) and evmChainId (derived via convertCosmosChainIdToEvmChainId) are not explicitly validated within this file. This could potentially lead to unexpected behavior if currentChainId isn’t defined or valid.

It would be advisable to add validation (or ensure that the upstream functions/hook handle it robustly) for currentChainId and evmChainId to safeguard the configuration generation process.

♻️ Duplicate comments (3)
src/lib/services/verification/evm/api.ts (1)

36-93: ⚠️ Potential issue

Add error handling to submitEvmVerifyFlatten function.

The function should handle potential errors from the axios request.

 const submitEvmVerifyFlatten = async ({
   verifierUrl,
   contractAddress,
   chainId,
   compilerVersion,
   licenseType,
   contractCode,
   optimizerConfig,
   constructorArgs,
   evmVersion,
   contractLibraries,
 }: SubmitEvmVerifyFlattenArgs) => {
+  try {
     const settings = {
       evmVersion: evmVersion === "default" ? "cancun" : evmVersion,
       optimizer: {
         enabled: optimizerConfig.enabled,
         runs: Number(optimizerConfig.runs),
       },
       libraries: contractLibraries.value.reduce((acc, library) => {
         Object.assign(acc, {
           [`${library.name}.sol`]: {
             [library.name]: library.address,
           },
         });
         return acc;
       }, {}),
       metadata: {
         bytecodeHash: "none",
       },
       outputSelection: {
         "*": {
           "": ["ast"],
           "*": ["abi", "evm.bytecode", "evm.methodIdentifiers", "metadata"],
         },
       },
     };

     return axios.post(
       verifierUrl,
       {
         license: licenseType,
         bytecode_type: "CREATION_INPUT",
         compiler_version: compilerVersion,
         constructor_arguments: constructorArgs.value,
         metadata: {
           chain_id: chainId,
           contract_address: contractAddress,
         },
         source_code: contractCode,
         settings: JSON.stringify(settings),
       },
       {
         headers: {
           "Content-Type": "application/json",
         },
       }
     );
+  } catch (error) {
+    throw new Error(`Verification submission failed: ${error.message}`);
+  }
 };
src/lib/pages/evm-contract-verify/index.tsx (2)

122-125: ⚠️ Potential issue

Implement form validation logic.

The isFormDisabled function currently returns false without any validation checks.

-// TODO
 const isFormDisabled = () => {
-  return false;
+  return !contractAddress || !option || !language || !licenseType || 
+    (option !== EvmVerifyOptions.SolidityFoundry && 
+     option !== EvmVerifyOptions.SolidityHardhat && 
+     !compilerVersion);
 };

127-157: ⚠️ Potential issue

Enhance error handling in submit function.

The submit function could benefit from more robust error handling and user feedback.

 const handleSubmit = () => {
   if (!option || !language || !licenseType) return;

   // open modal for either verification status or verification result
   onOpen();

   // if verify by tools, don't need to submit verification
   if (isVerifyByExternals) return;

   mutate(
     {
       option,
       verifyForm,
       contractAddress,
       compilerVersion,
       licenseType,
       chainId: currentChainId,
     },
     {
       onSuccess: () => {
         queryClient.invalidateQueries({
           queryKey: [
             CELATONE_QUERY_KEYS.EVM_VERIFY_INFO,
             currentChainId,
             contractAddress,
           ],
         });
       },
+      onError: (error) => {
+        const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
+        console.error("Error submitting verification:", errorMessage);
+        // Consider adding user notification here
+      },
     }
   );
 };
🧹 Nitpick comments (6)
src/lib/pages/evm-contract-verify/types.ts (1)

6-11: Improve query parameter validation schema.

The validation schema could be enhanced:

  1. Use a more descriptive error message for empty address instead of a single space.
  2. Simplify validation by combining the empty check with the hex validation.
 export const zEvmContractVerifyQueryParams = z.object({
   contractAddress: z.preprocess((val) => {
     const address = String(val).trim();
     return isHex20Bytes(address) ? address : undefined;
-  }, zHexAddr20.optional()),
+  }, zHexAddr20.optional().refine(
+    (val) => val !== "",
+    "Contract address is required"
+  )),
 });
src/lib/services/verification/evm/api.ts (2)

48-71: Extract settings object to a separate function.

The settings object construction could be extracted to improve reusability and maintainability.

+const createVerificationSettings = ({
+  evmVersion,
+  optimizerConfig,
+  contractLibraries,
+}: Pick<SubmitEvmVerifyFlattenArgs, "evmVersion" | "optimizerConfig" | "contractLibraries">) => ({
+  evmVersion: evmVersion === "default" ? "cancun" : evmVersion,
+  optimizer: {
+    enabled: optimizerConfig.enabled,
+    runs: Number(optimizerConfig.runs),
+  },
+  libraries: contractLibraries.value.reduce((acc, library) => {
+    Object.assign(acc, {
+      [`${library.name}.sol`]: {
+        [library.name]: library.address,
+      },
+    });
+    return acc;
+  }, {}),
+  metadata: {
+    bytecodeHash: "none",
+  },
+  outputSelection: {
+    "*": {
+      "": ["ast"],
+      "*": ["abi", "evm.bytecode", "evm.methodIdentifiers", "metadata"],
+    },
+  },
+});

95-113: Implement remaining verification options.

The TODO comment indicates missing implementations for other verification options.

Would you like me to help implement the remaining verification options? I can provide implementations for:

  • VyperUploadFile
  • VyperContractCode
  • VyperJsonInput
  • SolidityUploadFiles
  • SolidityJsonInput
  • SolidityHardhat
  • SolidityFoundry
src/lib/services/types/verification/evm.ts (2)

151-164: Improve error message in contract address validation.

The empty error message (" ") in the validation schema should be more descriptive.

 const zEvmContractVerifyBase = z.object({
   // TODO: refactor later
   contractAddress: zHexAddr20.superRefine((val, ctx) => {
     if (val === "")
       ctx.addIssue({
         code: ZodIssueCode.custom,
-        message: " ",
+        message: "Contract address is required",
       });

     if (!isHex20Bytes(val))
       ctx.addIssue({
         code: ZodIssueCode.custom,
         message: "Invalid address",
       });
   }),

81-85: Enhance type safety in form schemas.

The runs field in zOptimizerConfig and value field in zConstructorArgs could benefit from more specific validation.

 const zOptimizerConfig = z.object({
   enabled: z.boolean(),
-  runs: z.string(),
+  runs: z.string().regex(/^\d+$/, "Runs must be a positive number"),
 });

 const zConstructorArgs = z.object({
   enabled: z.boolean(),
-  value: z.string(),
+  value: z.string().regex(/^(0x)?[0-9a-fA-F]*$/, "Constructor arguments must be a valid hex string"),
 });

Also applies to: 87-91

src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityHardhat.tsx (1)

28-30: Consider making Solidity version configurable.

The Hardhat configuration currently hardcodes Solidity version to "v0.8.28". Consider making this configurable based on the contract's actual Solidity version.

-  solidity: "v0.8.28", // replace with your solidity version
+  solidity: {
+    version: solidityVersion, // Pass as prop or derive from contract metadata
+    settings: {
+      optimizer: {
+        enabled: true,
+        runs: 200
+      }
+    }
+  },
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f15bb25 and 4db53b2.

📒 Files selected for processing (20)
  • src/lib/pages/evm-contract-verify/components/EvmContractVerifyForms.tsx (2 hunks)
  • src/lib/pages/evm-contract-verify/components/EvmContractVerifyOptions.tsx (9 hunks)
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifyModalBody.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifySuccessModal.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/index.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityContractCode.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityFoundry.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityHardhat.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityJsonInput.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityUploadFiles.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/vyper/EvmContractVerifyVyperContractCode.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/vyper/EvmContractVerifyVyperJsonInput.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/components/vyper/EvmContractVerifyVyperUploadFile.tsx (1 hunks)
  • src/lib/pages/evm-contract-verify/helpers.ts (3 hunks)
  • src/lib/pages/evm-contract-verify/index.tsx (9 hunks)
  • src/lib/pages/evm-contract-verify/types.ts (1 hunks)
  • src/lib/services/types/verification/evm.ts (3 hunks)
  • src/lib/services/verification/evm/api.ts (2 hunks)
  • src/lib/services/verification/evm/index.ts (2 hunks)
  • src/lib/services/verification/evm/utils.ts (1 hunks)
✅ Files skipped from review due to trivial changes (4)
  • src/lib/pages/evm-contract-verify/components/vyper/EvmContractVerifyVyperUploadFile.tsx
  • src/lib/pages/evm-contract-verify/components/vyper/EvmContractVerifyVyperContractCode.tsx
  • src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityUploadFiles.tsx
  • src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityContractCode.tsx
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/lib/pages/evm-contract-verify/helpers.ts
  • src/lib/services/verification/evm/index.ts
  • src/lib/pages/evm-contract-verify/components/EvmContractVerifyOptions.tsx
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifySuccessModal.tsx
  • src/lib/services/verification/evm/utils.ts
  • src/lib/pages/evm-contract-verify/components/EvmContractVerifyForms.tsx
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/EvmContractVerifyModalBody.tsx
  • src/lib/pages/evm-contract-verify/components/evm-contract-verify-modal/index.tsx
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (5)
src/lib/pages/evm-contract-verify/components/vyper/EvmContractVerifyVyperJsonInput.tsx (1)

6-6: LGTM! Import path updated correctly.

The change from relative to absolute import path aligns with the codebase's import structure standardization.

src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityJsonInput.tsx (1)

6-6: LGTM! Import path updated correctly.

The change from relative to absolute import path maintains consistency with other components.

src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityFoundry.tsx (2)

8-8: LGTM! Import path updated correctly.

The change from relative to absolute import path aligns with the standardization effort.


23-33: Consider adding input validation for command generation.

The command generation uses template literals with potentially undefined values. Consider adding validation or default values for:

  • jsonRpc
  • contractAddress
  • currentChainId
src/lib/pages/evm-contract-verify/components/solidity/EvmContractVerifySolidityHardhat.tsx (1)

9-9: LGTM! Import path updated correctly.

The change from relative to absolute import path maintains consistency with other components.

Copy link

@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

🔭 Outside diff range comments (1)
src/lib/services/verification/evm/api.ts (1)

14-30: Add error handling to API calls.

Both getEvmVerifyConfig and getEvmVerifyInfo functions should handle potential API errors.

Apply this diff to add error handling:

 export const getEvmVerifyConfig = async () => {
+  try {
     return axios
       .get(`${CELATONE_VERIFICATION_API}/evm/verification/config`)
       .then(({ data }) => zEvmVerifyConfig.parse(data));
+  } catch (error) {
+    throw new Error(`Failed to fetch EVM verification config: ${error.message}`);
+  }
 };

 export const getEvmVerifyInfo = async (
   chainId: string,
   contractAddress: HexAddr20
 ) => {
+  try {
     return axios
       .get(`${CELATONE_VERIFICATION_API}/evm/verification/info`, {
         params: {
           chain_id: chainId,
           address: contractAddress,
         },
       })
       .then(({ data }) => zEvmVerifyInfo.parse(data));
+  } catch (error) {
+    throw new Error(`Failed to fetch EVM verification info: ${error.message}`);
+  }
 };
🧹 Nitpick comments (2)
src/lib/services/verification/evm/api.ts (2)

50-50: Avoid hardcoding EVM version.

The default EVM version "cancun" is hardcoded. Consider making it configurable or fetching it from the verification config.


116-116: Track the TODO comment for implementing other verification options.

The TODO comment indicates that other verification options need to be implemented.

Would you like me to create an issue to track the implementation of other verification options?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4db53b2 and 8b15992.

📒 Files selected for processing (1)
  • src/lib/services/verification/evm/api.ts (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
src/lib/services/verification/evm/api.ts (2)

3-9: Move types to a dedicated verification folder.

Consider moving the EVM verification types (EvmVerifyOptions, SubmitEvmVerifyArgs, etc.) to services/types/verification/evm for better code organization.


37-100: Add error handling to 'submitEvmVerifyFlatten' function.

The function should handle potential errors during the API call.

@evilpeach evilpeach merged commit ced1d23 into develop Feb 10, 2025
13 checks passed
@evilpeach evilpeach deleted the feat/solidity-flatten-wireup branch February 10, 2025 06:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants