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: add evm code snippet, fix fields bugs #1250

Merged
merged 2 commits into from
Feb 27, 2025
Merged

Conversation

evilpeach
Copy link
Collaborator

@evilpeach evilpeach commented Feb 26, 2025

Summary by CodeRabbit

  • New Features

    • Introduced an interactive modal that displays smart contract code snippets, featuring dedicated tabs for read and write operations along with a preview and one-click copy functionality.
    • Added a new entry in the changelog to inform users about the latest updates.
  • Bug Fixes

    • Improved input field behavior, including more accurate boolean selection for a smoother and more intuitive user experience.

Copy link

vercel bot commented Feb 26, 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 27, 2025 4:10am
initia-celatone-rehearsal ✅ Ready (Inspect) Visit Preview 💬 Add feedback Feb 27, 2025 4:10am
6 Skipped Deployments
Name Status Preview Comments Updated (UTC)
celatone-frontend-main ⬜️ Ignored (Inspect) Visit Preview Feb 27, 2025 4:10am
initia-celatone-frontend ⬜️ Ignored (Inspect) Visit Preview Feb 27, 2025 4:10am
neutron-celatone-frontend ⬜️ Ignored (Inspect) Visit Preview Feb 27, 2025 4:10am
osmosis-celatone-frontend ⬜️ Ignored (Inspect) Visit Preview Feb 27, 2025 4:10am
sei-celatone-frontend ⬜️ Ignored (Inspect) Visit Preview Feb 27, 2025 4:10am
terra-celatone-frontend ⬜️ Ignored (Inspect) Visit Preview Feb 27, 2025 4:10am

Copy link

coderabbitai bot commented Feb 26, 2025

Walkthrough

This pull request introduces an "EVM code snippet modal" feature by updating the CHANGELOG.md and implementing several improvements across the codebase. The changes include updating type definitions from strings to booleans in a field component, revising form field value retrieval with the useWatch hook, enhancing the EVM code snippet modal with proper props, and refining utility functions for handling EVM function data. Additionally, the UI layout in contract interaction components is updated to group related elements and adjust hook triggering conditions.

Changes

File(s) Change Summary
CHANGELOG.md Added a new feature entry: "Add evm code snippet modal and fix input fields" associated with PR #1250.
src/lib/components/evm-abi/fields/BoolField.tsx Updated BOOL_FIELD_OPTIONS type from SelectInputOption<string>[] to SelectInputOption<boolean>[], replacing "1"/"0" with true/false.
src/lib/components/evm-abi/fields/FieldTemplate.tsx Replaced direct value extraction with the useWatch hook from react-hook-form to observe form field changes.
src/lib/components/modal/EvmCodeSnippet.tsx Updated component props to include type, contractAddress, abiSection, and inputs; implemented modal structure with tabs, AceEditor for code display, and CopyButton; added logic to generate code snippets for read and write operations using the ethers library.
src/lib/pages/…/abi-read/ReadBox.tsx, src/lib/pages/…/abi-write/WriteBox.tsx Modified the integration of EvmCodeSnippet by updating hook enabling conditions and grouping UI elements using an HStack for improved layout.
src/lib/utils/evm.ts Introduced the JsonDataType for improved type safety; updated the signature of encodeEvmFunctionData; added formatEvmFunctionInputsArgs and refined result decoding with recursive formatting functions.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Modal as EvmCodeSnippet
    participant Memo as CodeSnippet Generator
    participant Ethers as Ethers Library
    participant UI as Tabs/AceEditor/CopyButton

    User->>Modal: Opens modal (isOpen true)
    Modal->>Memo: Compute code snippets using props
    Memo->>Ethers: Generate read/write snippet code
    Ethers-->>Memo: Return generated snippets
    Memo-->>Modal: Provide code snippets
    Modal->>UI: Render Tabs with AceEditor and CopyButton
    User->>UI: Select tab and click Copy
    UI-->>User: Display snippet copied confirmation
Loading

Possibly related PRs

Suggested reviewers

  • songwongtp

Poem

I'm a rabbit hopping through the code,
New modals and fields lighten my load.
Boolean carrots now taste so true,
Code snippets shine with a brilliant hue.
I hop with joy in every line I see,
Celebrating changes with glee and esprit!
🐰🌟

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/lib/components/modal/EvmCodeSnippet.tsx

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-import".

(The package "eslint-plugin-import" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-import@latest --save-dev

The plugin "eslint-plugin-import" was referenced from the config file in ".eslintrc.json".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

src/lib/utils/evm.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-import".

(The package "eslint-plugin-import" was not found when loaded as a Node module from the directory "".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-import@latest --save-dev

The plugin "eslint-plugin-import" was referenced from the config file in ".eslintrc.json".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
  • @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.

@evilpeach evilpeach changed the title feat: add evm code snippet, fix fields feat: add evm code snippet, fix fields bugs Feb 26, 2025
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

🧹 Nitpick comments (5)
src/lib/utils/evm.ts (2)

125-129: Consider handling edge cases within deepStringify.

Currently, non-boolean, non-array values are blindly converted to strings. If more complex non-boolean types (e.g., objects or null) surface in the future, it could lead to unexpected behavior. Consider adding extra type checks or fallback logic for non-primitive types.


140-151: Leading comma usage & potential null edge cases.

The formatEvmFunctionInputsArgs function introduces a leading comma in the returned string (e.g., , [123, true]). This works fine in the context of iface.encodeFunctionData("functionName" + formatEvmFunctionInputsArgs(inputs)), but it may be fragile if repurposed elsewhere. Also, similar to deepStringify, consider adding checks for null or unexpected object types to avoid "null" or "undefined" string conversions.

src/lib/components/modal/EvmCodeSnippet.tsx (3)

61-93: Well-structured "read" snippet generator.

Generating the read snippet with Ethers, encoding function data, and decoding results exemplifies a clear pattern for contract reading. Consider adding minimal error handling in the snippet for a more instructive example (e.g., try-catch around the provider.call).


94-119: Practical "write" snippet with wallet interaction.

Providing a code snippet with explicit wallet usage and transaction sending is helpful. A small caution: referencing "your-private-key" in the snippet might prompt inexperienced developers to paste secrets directly in code. Encourage external configuration or environment variables in the snippet example to illustrate best practices.


125-201: Modal structure is cohesive and user-friendly.

The tabbed UI and usage of AceEditor with a built-in copy button create a smooth developer experience. As a nice-to-have, consider extracting the snippet rendering logic into a separate component or custom hook to reduce the size of this component for better readability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 138ff1d and 3338f38.

📒 Files selected for processing (7)
  • CHANGELOG.md (1 hunks)
  • src/lib/components/evm-abi/fields/BoolField.tsx (1 hunks)
  • src/lib/components/evm-abi/fields/FieldTemplate.tsx (2 hunks)
  • src/lib/components/modal/EvmCodeSnippet.tsx (2 hunks)
  • src/lib/pages/evm-contract-details/components/interact-evm-contract/abi-read/ReadBox.tsx (4 hunks)
  • src/lib/pages/evm-contract-details/components/interact-evm-contract/abi-write/WriteBox.tsx (1 hunks)
  • src/lib/utils/evm.ts (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (11)
src/lib/components/evm-abi/fields/BoolField.tsx (1)

7-16: Improved type safety by using boolean values instead of strings.

The change from SelectInputOption<string>[] to SelectInputOption<boolean>[] and updating the values from strings ("1" and "0") to their corresponding boolean values (true and false) enhances type safety and more accurately represents the semantic meaning. This makes the code more maintainable and prevents potential type conversion issues.

src/lib/components/evm-abi/fields/FieldTemplate.tsx (2)

3-3: Added useWatch import from react-hook-form.

The addition of the useWatch hook import enables more efficient value monitoring.


22-29: Better form field value handling with useWatch.

Changing from direct destructuring of value to using the useWatch hook is a good practice. This approach provides more reliable access to field values and can reduce unnecessary re-renders, which is especially beneficial in complex forms.

src/lib/pages/evm-contract-details/components/interact-evm-contract/abi-write/WriteBox.tsx (1)

170-175: Enhanced EvmCodeSnippet with proper props for write operations.

The EvmCodeSnippet component now receives necessary context data including contract address, ABI section details, operation type, and input values. This improves the component's functionality by providing all required information to generate appropriate code snippets for write operations.

src/lib/pages/evm-contract-details/components/interact-evm-contract/abi-read/ReadBox.tsx (3)

85-85: Improved useEthCall hook enablement logic.

Adding the !inputRequired condition to the hook's enablement logic is a good optimization. This ensures the hook only runs when it's actually needed (when no input is required), preventing unnecessary API calls.


147-162: Better UI organization with HStack for related components.

Using HStack to group the CopyButton and EvmCodeSnippet components improves the UI layout and visual hierarchy. The EvmCodeSnippet component now also receives all necessary props for proper functionality in read operations.


206-220: Consistent implementation of EvmCodeSnippet in secondary location.

This change maintains consistency with the previous implementation, ensuring the code snippet functionality works correctly throughout the application. The proper props are provided to the EvmCodeSnippet component for read operations in this section as well.

src/lib/utils/evm.ts (2)

9-9: Good type import alignment.

The addition of JsonDataType is a neat improvement toward stronger typing and clarity throughout the file.


109-109: Enhanced type safety.

Switching from unknown[] to JsonDataType[] in the encodeEvmFunctionData parameters is a solid enhancement. It increases maintainability and ensures you benefit from correct type-checking.

src/lib/components/modal/EvmCodeSnippet.tsx (2)

36-42: Clear demarcation of snippet type.

Defining CodeSnippetType = "read" | "write" clarifies the modal’s intention. This approach is more explicit and maintainable than a generic boolean or string enumeration.


45-49: Comprehensive prop definition.

Exposing all key fields (type, contractAddress, abiSection, inputs) in EvmCodeSnippetProps is a straightforward way to ensure external components supply the necessary data. Good job on making this contract explicit.

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

🧹 Nitpick comments (4)
src/lib/components/modal/EvmCodeSnippet.tsx (4)

121-121: Consider optimizing useMemo dependencies.

Using JSON.stringify() on objects in dependency arrays can impact performance. Consider using more specific dependency tracking for large objects.

- }, [JSON.stringify(evm), JSON.stringify(inputs), abiSection]);
+ }, [evm?.enabled, evm?.jsonRpc, contractAddress, abiSection.name, inputs]);

100-101: Add security warning about private key handling.

Add a clear comment warning users about the security implications of handling private keys in code.

- const privateKey = "your-private-key";
+ // WARNING: Never hardcode private keys in production code or commit them to version control.
+ // Use environment variables or secure key management solutions instead.
+ const privateKey = "your-private-key"; 

69-118: Enhance code snippets with error handling.

The current code snippets lack error handling, which is crucial when interacting with blockchain contracts.

For the read snippet (around line 78-90), consider adding:

 const main = async () => {
+  try {
     const encodedData = iface.encodeFunctionData(${functionName}, ${inputsString});

     const rawResult = await provider.call({
       to: "${contractAddress}",
       data: encodedData,
     });

     const decodedResult = iface.decodeFunctionResult(${functionName}, rawResult);
     console.log(decodedResult);
+  } catch (error) {
+    console.error("Error calling contract:", error);
+  }
 };

Similarly for the write snippet (around line 107-115):

 const main = async () => {
+  try {
     const tx = await wallet.sendTransaction({
       to: "${contractAddress}",
       data: encodedData,
     });

     console.log(tx);
+    // Wait for transaction confirmation
+    const receipt = await tx.wait();
+    console.log("Transaction confirmed:", receipt);
+  } catch (error) {
+    console.error("Error sending transaction:", error);
+  }
 };

68-120: Consider adding more code snippet options.

Adding support for other popular libraries like Web3.js or wallet providers like MetaMask would make this component more versatile for different user preferences.

For example, you could add a MetaMask snippet by extending the codeSnippets object:

return {
  read: [
    {
      name: "Ethers",
      mode: "javascript",
      snippet: `...existing snippet...`
    },
    {
      name: "MetaMask",
      mode: "javascript",
      snippet: `// Make sure MetaMask is installed and connected
const ethereum = window.ethereum;
if (!ethereum) {
  console.error("Please install MetaMask");
  return;
}

const accounts = await ethereum.request({ method: 'eth_requestAccounts' });
const account = accounts[0];

const ABI = [${JSON.stringify(abiSection)}];
const contractInterface = new ethers.Interface(ABI);
const data = contractInterface.encodeFunctionData(${functionName}, ${inputsString});

const result = await ethereum.request({
  method: 'eth_call',
  params: [{
    from: account,
    to: "${contractAddress}",
    data,
  }, 'latest']
});

const decodedResult = contractInterface.decodeFunctionResult(${functionName}, result);
console.log(decodedResult);`
    }
  ],
  write: [
    // ...existing write snippets...
  ]
};
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3338f38 and 216dbad.

📒 Files selected for processing (2)
  • src/lib/components/modal/EvmCodeSnippet.tsx (2 hunks)
  • src/lib/utils/evm.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib/utils/evm.ts
🔇 Additional comments (1)
src/lib/components/modal/EvmCodeSnippet.tsx (1)

36-202: Well-implemented code snippet modal component!

The implementation of the EvmCodeSnippet component is clean, well-structured, and follows React best practices. The modal provides useful code snippets for EVM contract interaction.

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.

2 participants