-
Notifications
You must be signed in to change notification settings - Fork 20
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
Conversation
The latest updates on your projects. Learn more about Vercel for Git ↗︎
6 Skipped Deployments
|
WalkthroughThis pull request introduces an "EVM code snippet modal" feature by updating the Changes
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
Possibly related PRs
Suggested reviewers
Poem
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
src/lib/components/modal/EvmCodeSnippet.tsxOops! 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:
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.tsOops! 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:
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
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 withindeepStringify
.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 ofiface.encodeFunctionData("functionName" + formatEvmFunctionInputsArgs(inputs))
, but it may be fragile if repurposed elsewhere. Also, similar todeepStringify
, consider adding checks fornull
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
📒 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>[]
toSelectInputOption<boolean>[]
and updating the values from strings ("1"
and"0"
) to their corresponding boolean values (true
andfalse
) 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 theuseWatch
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 theCopyButton
andEvmCodeSnippet
components improves the UI layout and visual hierarchy. TheEvmCodeSnippet
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[]
toJsonDataType[]
in theencodeEvmFunctionData
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
) inEvmCodeSnippetProps
is a straightforward way to ensure external components supply the necessary data. Good job on making this contract explicit.
There was a problem hiding this 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
📒 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.
Summary by CodeRabbit
New Features
Bug Fixes