Skip to content

Conversation

@epsjunior
Copy link
Contributor

@epsjunior epsjunior commented Jul 23, 2025

Add Developer Default Fee Configuration RPC Method

Summary

Introduces a new RPC method to allow developers to set default fee configurations for specific contract and method combinations in the GenLayer Wallet snap. This enhancement enables dApps and contract developers to provide sensible fee parameter defaults, improving the onboarding and transaction experience for users. The system ensures user preferences always take precedence, and developer defaults are only used when no user configuration exists.

Changes

🚀 New Features

  • Developer Default Fee RPC: Added setDefaultFeeConfig RPC method for setting per-contract+method default fee parameters
  • Per-Method Defaults: Developers can specify defaults for each contract method (e.g., transfer, approve)
  • User-First Priority: User-set values always override developer defaults
  • TypeScript Types: Introduced FeeConfig and FeeConfigState types for strong typing of fee configurations

🎯 Problem Solved

Issue: Users previously had to manually set all fee parameters, and there was no way for dApps to suggest sensible defaults for new contracts or methods.

Solution:

  • Developers can now set recommended defaults for each contract+method, which are used unless the user has already set their own preferences.

🔧 Implementation Details

  • RPC Handler: Added onRpcRequest handler for setDefaultFeeConfig
  • Storage Logic: Uses a composite key (contractAddress_methodName) to store defaults
  • No User Override: If a user has already set a config for a contract+method, developer defaults are not applied or overwritten
  • Type Safety: All configs are validated and typed
  • Error Handling: Throws clear errors for missing parameters or invalid input

📁 File Structure

packages/snap/src/
├── index.tsx                # Main snap logic, now with onRpcRequest handler
├── transactions/
│   └── transaction.ts       # getTransactionStorageKey, setDefaultFeeConfig, etc.
├── types/
│   └── index.ts             # FeeConfig, FeeConfigState types
├── components/
│   └── AdvancedOptionsForm.tsx # Uses FeeConfigState for form values

🏗️ Usage

Set Developer Default Fee Config (RPC)

await window.ethereum.request({
  method: 'wallet_invokeSnap',
  params: {
    snapId: 'genlayer-wallet-plugin',
    request: {
      method: 'setDefaultFeeConfig',
      params: {
        contractAddress: '0x1234567890123456789012345678901234567890',
        methodName: 'transfer',
        config: {
          'leader-timeout-input': '120',
          'validator-timeout-input': '60',
          'number-of-appeals': '2',
        }
      }
    }
  }
});
// Returns: { success: true } if set, { success: false } if user config exists

Priority System

  • User Config: If user has set a config for contract+method, it is always used
  • Developer Default: Used only if no user config exists
  • No Config: Falls back to empty/default values

🧪 Testing

  • Unit Tests: Added/updated tests for:
    • Setting developer defaults via RPC
    • Ensuring user config is never overwritten
    • Error handling for missing/invalid parameters
    • Integration with transaction and state management logic

✨ Code Quality

  • TypeScript: All new logic is fully typed
  • Error Handling: Clear error messages for all invalid input
  • No Breaking Changes: Existing user flows and configs are preserved
  • Modular Design: Fee config logic is encapsulated in the transactions module

🛡️ Security & Audit

  • No User Override: User configs are never overwritten by developer defaults
  • Input Validation: All RPC parameters are validated
  • Minimal Permissions: Only the required endowment:rpc permission is used
  • Audit Note: Adding an RPC method for developer defaults will not require a third-party audit from an approved auditor, but will need to be allowlisted before it can be installed. The allowlist uses strict versioning for all Snaps. After publishing a new version of the Snap to npm, we will must re-submit it for allowlisting by filling out the MetaMask Snaps Directory Information Update form. Users will not be able to install a new version until it is allowlisted.

Testing: ✅ All tests pass, including new RPC and priority logic
Type Safety: ✅ Full TypeScript coverage
User Experience: ✅ Users always have control, but benefit from sensible defaults
Developer Experience: ✅ Easy to set per-method defaults via a single RPC call
Security: ✅ User data protected, no breaking changes, clear error handling

Summary by CodeRabbit

  • New Features

    • Added support for setting default fee configurations for contract methods via a new RPC method.
    • Introduced new types for fee configuration to enhance form handling and state management.
  • Bug Fixes

    • Improved default value handling in advanced options forms for more accurate user input processing.
  • Tests

    • Expanded test coverage for RPC request handling, fee configuration logic, and user input events.
  • Chores

    • Updated permissions in the manifest file to support new RPC capabilities.

@coderabbitai
Copy link

coderabbitai bot commented Jul 23, 2025

Walkthrough

The changes introduce a new fee configuration system for contract methods, including type definitions, a storage utility (setDefaultFeeConfig), and related handlers. The manifest is updated for new permissions. Form components and handlers are refactored to use the new types. Comprehensive tests are added for the new logic and handlers.

Changes

File(s) Change Summary
packages/snap/snap.manifest.json Updated shasum and permissions; added endowment:rpc with config.
packages/snap/src/types/index.ts Added new types: FeeConfig and FeeConfigState.
packages/snap/src/components/AdvancedOptionsForm.tsx Refactored to use FeeConfigState type; replaced `
packages/snap/src/index.tsx Added onRpcRequest handler for "setDefaultFeeConfig"; refactored to use new fee config types.
packages/snap/src/index.test.tsx Added and refactored tests for new handler, fee config logic, and user input events.
packages/snap/src/transactions/transaction.ts Added setDefaultFeeConfig function for storing fee configs.
packages/snap/src/transactions/transaction.test.ts Added tests for setDefaultFeeConfig.

Sequence Diagram(s)

sequenceDiagram
    participant DApp
    participant Snap
    participant StateManager

    DApp->>Snap: onRpcRequest({ method: "setDefaultFeeConfig", params })
    Snap->>Snap: Validate params (contractAddress, methodName, config)
    Snap->>StateManager: get(key)
    alt Config exists
        Snap-->>DApp: Return false (not overwritten)
    else No config
        Snap->>StateManager: set(key, config)
        Snap-->>DApp: Return true (config set)
    end
Loading

Estimated code review effort

3 (~45 minutes)

Suggested reviewers

  • cristiam86

Poem

In the warren, code hops anew,
With configs for fees and tests in view,
Types aligned, handlers bright,
Storage keys tucked in tight.
A snap of change, permissions set—
This rabbit’s proud—review, don’t fret!
🐇✨

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.

yarn install v1.22.22
[1/4] Resolving packages...
(node:31539) [DEP0169] DeprecationWarning: url.parse() behavior is not standardized and prone to errors that have security implications. Use the WHATWG URL API instead. CVEs are not issued for url.parse() vulnerabilities.
(Use node --trace-deprecation ... to show where the warning was created)
warning eslint@8.57.1: This version is no longer supported. Please see https://eslint.org/version-support for other options.
warning eslint > @humanwhocodes/config-array@0.13.0: Use @eslint/config-array instead
warning eslint > @humanwhocodes/config-array > @humanwhocodes/object-schema@2.0.3: Use @eslint/object-schema instead
warning eslint > file-entry-cache > flat-cache > rimraf@3.0.2: Rimraf versions prior to v4 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob@7.2.3: Glob versions prior to v9 are no longer supported
warning eslint > file-entry-cache > flat-cache > rimraf > glob > inflight@1.0.6: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
warning jest > @jest/core > @jest/transform > babel-plugin-istanbul > test-exclude > glob@7.2.3: Glob versions prior to v9 are no longer supported
warning workspace-aggregator-ebe2636b-aa4c-41ff-9df3-6c6a517e2597 > eslint@8.57.1: This version is no longer supported. Please see https://eslint.org/version-support for other options.
[2/4] Fetching packages...
error eslint-plugin-jsdoc@41.1.2: The engine "node" is incompatible with this module. Expected version "^14 || ^16 || ^17 || ^18 || ^19". Got "24.3.0"
error Found incompatible module.
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

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)
packages/snap/src/index.tsx (1)

87-93: Fix switch clause variable declaration issue.

The static analysis tool correctly identifies that variable declarations in switch clauses can be accessed by other cases, which can lead to bugs.

Apply this fix to wrap the declarations in a block:

     case 'advanced_options':
-        // eslint-disable-next-line no-case-declarations
-        const currentStorageKey = await StateManager.get('currentStorageKey');
-        // eslint-disable-next-line no-case-declarations
-        const persistedData = (await StateManager.get(
-          currentStorageKey,
-        )) as FeeConfigState;
+        {
+          const currentStorageKey = await StateManager.get('currentStorageKey');
+          const persistedData = (await StateManager.get(
+            currentStorageKey,
+          )) as FeeConfigState;

-        await snap.request({
-          method: 'snap_updateInterface',
-          params: {
-            id,
-            ui: <AdvancedOptionsForm values={persistedData || {}} />,
-          },
-        });
-        break;
+          await snap.request({
+            method: 'snap_updateInterface',
+            params: {
+              id,
+              ui: <AdvancedOptionsForm values={persistedData || {}} />,
+            },
+          });
+          break;
+        }
🧹 Nitpick comments (3)
packages/snap/src/types/index.ts (1)

19-23: Consider refining the FeeConfigState type definition.

The current intersection type might not enforce the intended constraint that all FeeConfig keys must be strings. The index signature [key: string]: string could potentially override the mapped type behavior.

Consider this alternative approach for better type safety:

-export type FeeConfigState = {
-  [K in keyof FeeConfig]: string;
-} & {
-  [key: string]: string;
-};
+export type FeeConfigState = {
+  [K in keyof FeeConfig]-?: string;
+} & Record<string, string>;

This ensures all FeeConfig properties are required strings while maintaining extensibility.

packages/snap/src/transactions/transaction.ts (1)

107-128: LGTM: Well-implemented fee configuration function.

The setDefaultFeeConfig function correctly:

  • Validates required parameters
  • Uses consistent storage key generation
  • Respects existing configurations (won't overwrite)
  • Provides clear return values

Consider these minor improvements:

 export async function setDefaultFeeConfig(
   contractAddress: string,
   methodName: string,
   config: FeeConfig,
 ): Promise<boolean> {
-  if (!contractAddress || !methodName) {
-    throw new Error('Contract address and method name are required');
+  if (!contractAddress) {
+    throw new Error('Contract address is required');
+  }
+  if (!methodName) {
+    throw new Error('Method name is required');
   }
   const storageKey = generateStorageKey(contractAddress, methodName);

   const existingConfig = await StateManager.get<FeeConfig>(storageKey);
   if (existingConfig) {
     return false;
   }

-  const defaultConfig = {
-    ...config,
-  };
-
-  await StateManager.set(storageKey, defaultConfig);
+  await StateManager.set(storageKey, config);
   return true;
 }
packages/snap/src/index.tsx (1)

16-40: LGTM: Well-structured RPC handler with room for improvement.

The RPC handler correctly implements the setDefaultFeeConfig method with proper parameter validation and error handling.

Consider these improvements for robustness:

 export const onRpcRequest: OnRpcRequestHandler = async ({ request }) => {
   switch (request.method) {
     case 'setDefaultFeeConfig': {
       const { contractAddress, methodName, config } = request.params as {
         contractAddress: string;
         methodName: string;
-        config: Record<string, string>;
+        config: Record<string, string | undefined>;
       };

-      if (!contractAddress || !methodName) {
-        throw new Error('Contract address and method name are required');
+      if (!request.params || typeof request.params !== 'object') {
+        throw new Error('Invalid request parameters');
       }

       const wasSet = await setDefaultFeeConfig(
         contractAddress,
         methodName,
         config as FeeConfig,
       );
       return { success: wasSet };
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3fafa43 and de9ba0c.

📒 Files selected for processing (7)
  • packages/snap/snap.manifest.json (2 hunks)
  • packages/snap/src/components/AdvancedOptionsForm.tsx (4 hunks)
  • packages/snap/src/index.test.tsx (5 hunks)
  • packages/snap/src/index.tsx (3 hunks)
  • packages/snap/src/transactions/transaction.test.ts (3 hunks)
  • packages/snap/src/transactions/transaction.ts (2 hunks)
  • packages/snap/src/types/index.ts (1 hunks)
🧠 Learnings (7)
packages/snap/snap.manifest.json (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/transactions/transaction.ts (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/types/index.ts (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/components/AdvancedOptionsForm.tsx (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/transactions/transaction.test.ts (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/index.tsx (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/index.test.tsx (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

🧬 Code Graph Analysis (4)
packages/snap/src/transactions/transaction.ts (2)
packages/snap/src/types/index.ts (1)
  • FeeConfig (5-13)
packages/snap/src/libs/StateManager.tsx (1)
  • StateManager (1-59)
packages/snap/src/components/AdvancedOptionsForm.tsx (1)
packages/snap/src/types/index.ts (1)
  • FeeConfigState (19-23)
packages/snap/src/transactions/transaction.test.ts (2)
packages/snap/src/libs/StateManager.tsx (1)
  • StateManager (1-59)
packages/snap/src/transactions/transaction.ts (1)
  • setDefaultFeeConfig (107-128)
packages/snap/src/index.tsx (2)
packages/snap/src/transactions/transaction.ts (1)
  • setDefaultFeeConfig (107-128)
packages/snap/src/types/index.ts (2)
  • FeeConfig (5-13)
  • FeeConfigState (19-23)
🪛 Biome (2.1.2)
packages/snap/src/index.tsx

[error] 91-93: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Safe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

🧰 Additional context used
🧠 Learnings (7)
packages/snap/snap.manifest.json (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/transactions/transaction.ts (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/types/index.ts (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/components/AdvancedOptionsForm.tsx (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/transactions/transaction.test.ts (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/index.tsx (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

packages/snap/src/index.test.tsx (1)

Learnt from: epsjunior
PR: #34
File: packages/snap/src/transactions/transaction.ts:15-15
Timestamp: 2025-07-22T05:49:18.238Z
Learning: In packages/snap/src/transactions/transaction.ts, the team has decided to keep the ABI hardcoded to chains.localnet.consensusMainContract?.abi rather than making it configurable. This was a deliberate architectural decision made after discussion.

🧬 Code Graph Analysis (4)
packages/snap/src/transactions/transaction.ts (2)
packages/snap/src/types/index.ts (1)
  • FeeConfig (5-13)
packages/snap/src/libs/StateManager.tsx (1)
  • StateManager (1-59)
packages/snap/src/components/AdvancedOptionsForm.tsx (1)
packages/snap/src/types/index.ts (1)
  • FeeConfigState (19-23)
packages/snap/src/transactions/transaction.test.ts (2)
packages/snap/src/libs/StateManager.tsx (1)
  • StateManager (1-59)
packages/snap/src/transactions/transaction.ts (1)
  • setDefaultFeeConfig (107-128)
packages/snap/src/index.tsx (2)
packages/snap/src/transactions/transaction.ts (1)
  • setDefaultFeeConfig (107-128)
packages/snap/src/types/index.ts (2)
  • FeeConfig (5-13)
  • FeeConfigState (19-23)
🪛 Biome (2.1.2)
packages/snap/src/index.tsx

[error] 91-93: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Safe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

🔇 Additional comments (14)
packages/snap/snap.manifest.json (2)

10-10: LGTM: Source hash updated for new bundle.

The shasum update is expected when adding new functionality to the snap bundle.


24-27: LGTM: RPC permission correctly configured.

The endowment:rpc permission is properly configured to allow dapps to call RPC methods while restricting access from other snaps, which aligns with security best practices.

packages/snap/src/types/index.ts (1)

5-13: LGTM: Well-structured base fee configuration type.

The FeeConfig type properly defines optional fee parameters with appropriate naming conventions and includes an index signature for extensibility.

packages/snap/src/transactions/transaction.ts (1)

5-6: LGTM: Proper imports for new functionality.

The imports for StateManager and FeeConfig are correctly added to support the new fee configuration feature.

packages/snap/src/components/AdvancedOptionsForm.tsx (3)

14-14: LGTM: Improved type consistency with centralized definitions.

Importing FeeConfigState from the types module eliminates duplicate type definitions and ensures consistency across components.


17-17: LGTM: Consistent type usage in props.

Using FeeConfigState for the values prop aligns with the new centralized type definitions.


23-23: LGTM: Improved default value handling with nullish coalescing.

Changing from || to ?? is more semantically correct for handling null and undefined values, preventing issues with falsy strings like "0".

Also applies to: 32-32, 67-67, 76-76, 84-84, 92-92, 99-99

packages/snap/src/index.tsx (2)

2-2: LGTM: Proper imports for new RPC functionality.

The imports correctly include the new OnRpcRequestHandler type and related functions/types needed for the RPC feature.

Also applies to: 10-14


93-93: LGTM: Updated type casting for new fee configuration types.

The type casting to FeeConfigState and FeeConfig correctly aligns with the new centralized type definitions.

Also applies to: 114-114

packages/snap/src/transactions/transaction.test.ts (2)

347-468: Excellent comprehensive test coverage for setDefaultFeeConfig.

The test suite thoroughly covers all the key scenarios:

  • ✅ Successful configuration setting when none exists
  • ✅ Preservation of existing configurations (no overwrite)
  • ✅ Contract address normalization to lowercase
  • ✅ Error handling for missing required parameters
  • ✅ Partial configuration support

The mocking strategy is consistent and the test assertions accurately verify the expected behavior based on the implementation.


34-41: Well-structured mock setup with proper typing.

The StateManager mock is comprehensive and the typed mock variables enhance type safety and developer experience during testing.

Also applies to: 48-50

packages/snap/src/index.test.tsx (3)

76-210: Comprehensive and well-structured RPC handler test coverage.

The test suite for onRpcRequest excellently covers all scenarios:

  • ✅ Successful fee configuration setting
  • ✅ Handling existing configurations
  • ✅ Input validation for required parameters
  • ✅ Missing configuration parameter handling
  • ✅ Error propagation from underlying functions
  • ✅ Unknown method error handling

The test assertions properly verify both the function calls and return values, ensuring the RPC handler behaves correctly in all scenarios.


32-56: Excellent test infrastructure improvements.

The enhanced mock setup provides:

  • ✅ Explicit and properly typed mocks for better IntelliSense
  • ✅ Consistent test cleanup with beforeEach hook
  • ✅ Better separation of concerns in mock configuration

These changes significantly improve test maintainability and developer experience.

Also applies to: 72-74


238-359: Well-refactored user input tests with improved coverage.

The updated tests provide:

  • ✅ Cleaner event type handling with string literals
  • ✅ Comprehensive coverage of user interaction scenarios
  • ✅ Proper mock verification for StateManager operations
  • ✅ Appropriate handling of unknown user actions

The refactoring enhances test readability and ensures robust validation of user input handling.

@epsjunior epsjunior requested a review from cristiam86 July 23, 2025 19:12
}
const storageKey = generateStorageKey(contractAddress, methodName);

const existingConfig = await StateManager.get<FeeConfig>(storageKey);
Copy link
Member

Choose a reason for hiding this comment

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

@epsjunior why can we update the config if it was previously set?
I think that we are mixing the user catched fees and the developer suggestion. We always can accept and record the developer's fee suggestion.
Then, if the user wants to set their own, that's good too.
At the moment of sending the transaction, the priority would be:

  1. User fees configuration
  2. Developer fees configuration

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