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(spaceward): key creation in sidebar #728

Merged
merged 4 commits into from
Aug 30, 2024
Merged

feat(spaceward): key creation in sidebar #728

merged 4 commits into from
Aug 30, 2024

Conversation

alex-nax
Copy link
Contributor

@alex-nax alex-nax commented Aug 28, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced dynamic handling of Ethereum and Cosmos chains based on network visibility settings.
    • Added context for wallet management in action components, improving interaction with queued actions.
    • Introduced new parameters for transaction requests, enhancing clarity and context in transaction processes.
    • Improved user experience in key creation modals by preventing multiple submissions during ongoing requests.
    • Expanded pagination limit for retrieving items, allowing for larger datasets in a single request.
  • Bug Fixes

    • Improved error handling and state management in key creation and asset sending processes.
  • Documentation

    • Updated function signatures to include new parameters for better context in transaction handling.

Copy link
Contributor

coderabbitai bot commented Aug 28, 2024

Walkthrough

Walkthrough

The changes involve significant modifications to the handling of Ethereum and Cosmos chains based on the networkVisibility environment variable, enhancing configurability. New parameters related to transaction titles are introduced across various functions. Additionally, the integration of wallet management context in several components improves interactions with wallet-related data. The code structure is refined for clarity, with enhanced error handling and state management in components dealing with key creation and asset transactions.

Changes

Files Change Summary
spaceward/src/config/tokens.ts Introduced filtering logic for enabled Ethereum and Cosmos chains based on networkVisibility.
spaceward/src/features/actions/Sidebar.tsx, spaceward/src/features/modals/CreateKey.tsx, spaceward/src/features/modals/SendAssets.tsx Enhanced components with wallet context integration, improved error handling, and streamlined control flows.
spaceward/src/features/assets/queries.ts, spaceward/src/features/assets/hooks.ts, spaceward/src/hooks/useEthereumTx.tsx, spaceward/src/hooks/useKeychainSigner.tsx Added title parameters to functions, simplifying transaction context and improving readability.
spaceward/package.json Updated "ethers" package version from "^6.9.2" to "6.13.2".
spaceward/src/lib/eth/constants.ts Updated RPC endpoints for the Ethereum Sepolia network.
spaceward/src/pages/Intents.tsx Increased pagination limit from BigInt(100) to BigInt(100000).

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 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.

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

vercel bot commented Aug 28, 2024

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

1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
warden-help-center ⬜️ Ignored (Inspect) Visit Preview Aug 30, 2024 7:56am

Copy link

Hey @alex-nax and thank you for opening this pull request! 👋🏼

It looks like you forgot to add a changelog entry for your changes. Make sure to add a changelog entry in the 'CHANGELOG.md' file.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

Outside diff range, codebase verification and nitpick comments (3)
spaceward/src/features/actions/hooks.ts (1)

Line range hint 77-122: Function updated to handle new parameters.

The useEnqueueAction function has been successfully updated to include title and keyThemeIndex in its parameters and internal logic. This enhances the function's capability to handle more complex scenarios. Consider refactoring the function to improve readability and maintainability, possibly by breaking down the addAction function into smaller, more focused functions.

spaceward/src/config/tokens.ts (1)

Line range hint 245-292: Approve the filtering logic for Cosmos chains.

The implementation for filtering _COSMOS_CHAINS based on the networkVisibility environment variable mirrors the approach taken with Ethereum chains, maintaining consistency and ensuring appropriate chain configurations are exported.

The changes are approved.

Similar to the Ethereum chains, adding unit tests for this filtering logic would ensure its correctness across different environments. Would you like help in creating these tests?

spaceward/src/features/actions/Sidebar.tsx (1)

Line range hint 374-498: Improve error handling and robustness in transaction broadcasting logic.

The logic for handling different network types and broadcasting transactions is complex and involves multiple conditional branches. While the implementation covers various scenarios, there are several areas where error handling and code clarity could be improved.

Consider refactoring the transaction broadcasting logic to separate concerns and improve readability. Here's a proposed refactor to organize the code better and enhance error handling:

- switch (item.networkType) {
-     case "eth-raw":
-         // existing logic
-         break;
-     case "eth":
-         // existing logic
-         break;
-     case "cosmos":
-         // existing logic
-         break;
-     default:
-         console.error("not implemented", item.networkType);
- }
+ const broadcastTransaction = async () => {
+     try {
+         switch (item.networkType) {
+             case "eth-raw":
+                 return handleEthRawTransaction(item);
+             case "eth":
+                 return handleEthTransaction(item);
+             case "cosmos":
+                 return handleCosmosTransaction(item);
+             default:
+                 throw new Error(`Network type ${item.networkType} not implemented`);
+         }
+     } catch (error) {
+         console.error("broadcast failed", error);
+         throw error;
+     }
+ };
+ const promise = broadcastTransaction();

This refactor introduces a function broadcastTransaction that encapsulates the logic for handling different network types, improving the separation of concerns and making the code easier to maintain and test.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5d44af6 and be7e2d3.

Files ignored due to path filters (1)
  • spaceward/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (13)
  • spaceward/src/config/tokens.ts (3 hunks)
  • spaceward/src/env.ts (2 hunks)
  • spaceward/src/features/actions/Sidebar.tsx (10 hunks)
  • spaceward/src/features/actions/hooks.ts (4 hunks)
  • spaceward/src/features/actions/util.ts (1 hunks)
  • spaceward/src/features/assets/hooks.ts (1 hunks)
  • spaceward/src/features/assets/queries.ts (5 hunks)
  • spaceward/src/features/metamask/MetaMaskRequests.tsx (1 hunks)
  • spaceward/src/features/modals/CreateKey.tsx (5 hunks)
  • spaceward/src/features/modals/SendAssets.tsx (9 hunks)
  • spaceward/src/features/walletconnect/util.ts (2 hunks)
  • spaceward/src/hooks/useEthereumTx.tsx (2 hunks)
  • spaceward/src/hooks/useKeychainSigner.tsx (2 hunks)
Additional context used
Biome
spaceward/src/features/actions/util.ts

[error] 50-54: 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:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

spaceward/src/features/actions/Sidebar.tsx

[error] 48-48: Unexpected constant condition.

(lint/correctness/noConstantCondition)

Additional comments not posted (16)
spaceward/src/hooks/useKeychainSigner.tsx (2)

55-55: Usage of title: Ensure proper integration within the function logic.

The title parameter is correctly passed to the addAction function, which suggests it's being used as intended. This integration appears proper, but it's crucial to ensure that the title is handled correctly in all contexts where signAmino is used.

The integration of the title parameter within the addAction call is approved.


20-20: Parameter Addition: Review the integration of the new title parameter.

The addition of the title parameter to the signAmino function's signature is correctly implemented. However, ensure that all calls to this function across the application are updated to include this new parameter.

Verification successful

Integration of title Parameter Verified Successfully

All calls to the signAmino function have been updated to include the new title parameter. No further action is required.

  • useKeychainSigner.tsx: Function definition includes title.
  • SendAssets.tsx: Function call includes title.
  • util.ts: Function call includes title.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `useKeychainSigner` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type typescript -A 5 $'useKeychainSigner'

Length of output: 80


Script:

#!/bin/bash
# Description: Verify all function calls to `useKeychainSigner` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type ts -A 5 'useKeychainSigner'

Length of output: 3595


Script:

#!/bin/bash
# Description: Verify all function calls to `signAmino` include the new `title` parameter.

# Test: Search for the function usage. Expect: Only occurrences with the `title` parameter.
rg --type ts -A 5 'signAmino'

Length of output: 2286

spaceward/src/env.ts (2)

25-26: Addition of networkVisibility: Ensure correct default value and usage.

The new networkVisibility constant is correctly set with a default value of "testnet". This change enhances the configurability of the application by allowing different settings for network visibility based on the environment. Ensure that this constant is used appropriately across the application to control network visibility settings.

The addition of the networkVisibility constant is approved.


43-43: Integration of networkVisibility into the env object.

The networkVisibility constant is correctly integrated into the exported env object. This integration allows easy access to the network visibility settings from other modules within the application.

The integration of networkVisibility into the env object is approved.

spaceward/src/hooks/useEthereumTx.tsx (2)

89-89: Usage of title: Ensure proper integration within the function logic.

The title parameter is correctly passed to the transaction request object, which suggests it's being used as intended. This integration appears proper, but it's crucial to ensure that the title is handled correctly in all contexts where signEthereumTx is used.

The integration of the title parameter within the transaction request object is approved.


51-51: Parameter Addition: Review the integration of the new title parameter.

The addition of the title parameter to the signEthereumTx function's signature is correctly implemented. However, ensure that all calls to this function across the application are updated to include this new parameter.

Verification successful

Integration of title Parameter Verified

The signEthereumTx function's signature, including the new title parameter, is correctly updated across all calls in the codebase. No further action is needed.

  • spaceward/src/components/SendEth.tsx
  • spaceward/src/features/walletconnect/util.ts
  • spaceward/src/features/modals/SendAssets.tsx
  • spaceward/src/features/metamask/MetaMaskRequests.tsx
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `useEthereumTx` match the new signature.

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type typescript -A 5 $'useEthereumTx'

Length of output: 76


Script:

#!/bin/bash
# Description: Verify all function calls to `signEthereumTx` match the new signature with the `title` parameter.

# Corrected Test: Search for the function usage in TypeScript with JSX. Expect: Only occurrences of the new signature.
rg --type tsx -A 5 'signEthereumTx'

Length of output: 63


Script:

#!/bin/bash
# Description: Verify all function calls to `signEthereumTx` match the new signature with the `title` parameter.

# New Test: Search for the function usage across all files. Expect: Only occurrences of the new signature.
rg -A 5 'signEthereumTx'

Length of output: 3743

spaceward/src/features/actions/hooks.ts (1)

49-50: Interface properties added successfully.

The new optional properties title and keyThemeIndex have been added to the QueuedAction interface. Consider adding documentation comments for these new properties to explain their usage and impact.

spaceward/src/features/assets/hooks.ts (1)

85-88: Function useAssetQueries streamlined for better handling of RPC endpoints.

The modifications to the useAssetQueries function simplify the handling of RPC endpoints by removing the testnet check and focusing on whether the rpc property is provided. This change should streamline the function's control flow but consider conducting thorough testing to ensure that it handles all network scenarios correctly without introducing regressions.

spaceward/src/features/walletconnect/util.ts (1)

320-329: Approved: Enhanced clarity in transaction signing.

The addition of the descriptive string "Approve walletconnect request" in both Ethereum and Cosmos transaction signing calls enhances clarity and debugging capabilities. This change is consistent and well-integrated within the function's logic.

Also applies to: 495-495

spaceward/src/features/assets/queries.ts (1)

Line range hint 531-544: Approved with caution: Changes in handling ENABLED_ETH_CHAINS and debug functionality.

The direct use of ENABLED_ETH_CHAINS enhances clarity and performance. However, the removal of debug functionality, although it simplifies the code, could reduce visibility during troubleshooting. Ensure that this change aligns with the project's requirements for debugging and monitoring.

spaceward/src/features/modals/CreateKey.tsx (1)

34-56: Approved: Enhanced key creation functionality and state management.

The integration of useNewAction and useEnqueueAction hooks, along with the new pending state, significantly enhances the functionality and user experience of the CreateKeyModal component. These changes ensure that key creation actions are managed effectively and that the UI reflects the current state accurately.

Also applies to: 95-110

spaceward/src/features/metamask/MetaMaskRequests.tsx (1)

136-136: Enhanced Clarity in Transaction Signing

The addition of the string "Approve snap transaction" as an argument in the signEthereumTx function call is a positive change, enhancing the clarity of what the transaction approval is for. This can aid in debugging and improve user experience by providing more context in the transaction signing process.

The change is approved, but it's recommended to verify how this additional context impacts the user experience or debugging scenarios.

spaceward/src/features/modals/SendAssets.tsx (4)

19-20: Integration of Wallet Context

The addition of walletContext is a significant enhancement, allowing the SendAssetsModal to interact dynamically with wallet data. This change supports better state management and interaction with the wallet's RPC endpoints, which is crucial for transaction handling.

The integration is well-implemented and follows best practices for context usage in React.


35-35: Improved Type Safety and Clarity

Defining the type of results to include BalanceEntry and a refetch function enhances type safety and clarity. This change ensures that the data structure is predictable and robust, which is essential for managing state and UI updates effectively.

The change is approved as it improves the maintainability and robustness of the component.


90-91: Clear Transaction Titles

The introduction of the title variable to dynamically generate transaction titles based on the token and amount being sent is a thoughtful addition. This enhances the clarity of transactions, making it easier for users to understand the context of their actions.

This change is approved as it significantly improves user experience by providing clear and informative transaction descriptions.


106-111: Dynamic RPC Endpoint Handling

The logic to dynamically retrieve the RPC endpoint if a predefined one is not available is crucial for ensuring the robustness of network connections. This change allows the application to adapt to different network states and configurations, which is particularly important in blockchain applications where network endpoints may vary.

The implementation is robust and follows best practices for dynamic resource management in decentralized applications.

Comment on lines +14 to +126
const { typeUrl, value } = action.result;

switch (typeUrl) {
case warden.warden.v1beta3.MsgNewSignRequestResponse.typeUrl: {
const { id } =
warden.warden.v1beta3.MsgNewSignRequestResponse.decode(value);

getStatus = async (client) => {
const { signRequest } =
await client.warden.warden.v1beta3.signRequestById({
id,
});

switch (signRequest?.status) {
case warden.warden.v1beta3.SignRequestStatus
.SIGN_REQUEST_STATUS_PENDING:
return {
pending: true,
error: false,
done: false,
};
case warden.warden.v1beta3.SignRequestStatus
.SIGN_REQUEST_STATUS_FULFILLED:
const analyzers = (
data as Parameters<
typeof warden.warden.v1beta3.MsgNewSignRequest.encode
>[0]
).analyzers;

return {
pending: false,
error: false,
done: true,
next: analyzers.includes(
env.ethereumAnalyzerContract,
)
? "eth"
: analyzers.includes(env.aminoAnalyzerContract)
? "cosmos"
: // fixme
(walletConnectRequestId &&
walletConnectTopic) ||
snapRequestId
? "eth-raw"
: undefined,
value: signRequest?.signedData,
};

default:
return {
pending: false,
error: true,
done: true,
};
}
};
break;
}
case warden.warden.v1beta3.MsgNewKeyRequestResponse.typeUrl: {
const { id } =
warden.warden.v1beta3.MsgNewKeyRequestResponse.decode(value);

getStatus = async (client) => {
const { keyRequest } =
await client.warden.warden.v1beta3.keyRequestById({
id,
});

switch (keyRequest?.status) {
case warden.warden.v1beta3.KeyRequestStatus
.KEY_REQUEST_STATUS_PENDING:
return {
pending: true,
error: false,
done: false,
};
case warden.warden.v1beta3.KeyRequestStatus
.KEY_REQUEST_STATUS_FULFILLED:
return {
pending: false,
error: false,
done: true,
value: keyRequest.id,
};
default:
return {
pending: false,
error: true,
done: true,
};
}
};
break;
}
default:
throw new Error(`action type not implemented: ${typeUrl}`);
}

return { getStatus };
};
Copy link
Contributor

Choose a reason for hiding this comment

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

Function getActionHandler implemented with robust error handling.

The getActionHandler function is well-implemented with comprehensive error handling and status determination based on the Warden protocol responses. However, to address the static analysis hint and prevent potential scope leakage, consider wrapping the declarations within each case block of the switch statement.

case warden.warden.v1beta3.MsgNewSignRequestResponse.typeUrl: {
+ {
  const { id } = warden.warden.v1beta3.MsgNewSignRequestResponse.decode(value);
  ...
+ }
}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const getActionHandler = ({
action,
data,
snapRequestId,
walletConnectRequestId,
walletConnectTopic,
}: QueuedAction) => {
let getStatus: GetStatus;
if (!action?.result) {
throw new Error("invalid action result");
}
const { typeUrl, value } = action.result;
switch (typeUrl) {
case warden.warden.v1beta3.MsgNewSignRequestResponse.typeUrl: {
const { id } =
warden.warden.v1beta3.MsgNewSignRequestResponse.decode(value);
getStatus = async (client) => {
const { signRequest } =
await client.warden.warden.v1beta3.signRequestById({
id,
});
switch (signRequest?.status) {
case warden.warden.v1beta3.SignRequestStatus
.SIGN_REQUEST_STATUS_PENDING:
return {
pending: true,
error: false,
done: false,
};
case warden.warden.v1beta3.SignRequestStatus
.SIGN_REQUEST_STATUS_FULFILLED:
const analyzers = (
data as Parameters<
typeof warden.warden.v1beta3.MsgNewSignRequest.encode
>[0]
).analyzers;
return {
pending: false,
error: false,
done: true,
next: analyzers.includes(
env.ethereumAnalyzerContract,
)
? "eth"
: analyzers.includes(env.aminoAnalyzerContract)
? "cosmos"
: // fixme
(walletConnectRequestId &&
walletConnectTopic) ||
snapRequestId
? "eth-raw"
: undefined,
value: signRequest?.signedData,
};
default:
return {
pending: false,
error: true,
done: true,
};
}
};
break;
}
case warden.warden.v1beta3.MsgNewKeyRequestResponse.typeUrl: {
const { id } =
warden.warden.v1beta3.MsgNewKeyRequestResponse.decode(value);
getStatus = async (client) => {
const { keyRequest } =
await client.warden.warden.v1beta3.keyRequestById({
id,
});
switch (keyRequest?.status) {
case warden.warden.v1beta3.KeyRequestStatus
.KEY_REQUEST_STATUS_PENDING:
return {
pending: true,
error: false,
done: false,
};
case warden.warden.v1beta3.KeyRequestStatus
.KEY_REQUEST_STATUS_FULFILLED:
return {
pending: false,
error: false,
done: true,
value: keyRequest.id,
};
default:
return {
pending: false,
error: true,
done: true,
};
}
};
break;
}
default:
throw new Error(`action type not implemented: ${typeUrl}`);
}
return { getStatus };
};
export const getActionHandler = ({
action,
data,
snapRequestId,
walletConnectRequestId,
walletConnectTopic,
}: QueuedAction) => {
let getStatus: GetStatus;
if (!action?.result) {
throw new Error("invalid action result");
}
const { typeUrl, value } = action.result;
switch (typeUrl) {
case warden.warden.v1beta3.MsgNewSignRequestResponse.typeUrl: {
{
const { id } =
warden.warden.v1beta3.MsgNewSignRequestResponse.decode(value);
getStatus = async (client) => {
const { signRequest } =
await client.warden.warden.v1beta3.signRequestById({
id,
});
switch (signRequest?.status) {
case warden.warden.v1beta3.SignRequestStatus
.SIGN_REQUEST_STATUS_PENDING:
return {
pending: true,
error: false,
done: false,
};
case warden.warden.v1beta3.SignRequestStatus
.SIGN_REQUEST_STATUS_FULFILLED:
const analyzers = (
data as Parameters<
typeof warden.warden.v1beta3.MsgNewSignRequest.encode
>[0]
).analyzers;
return {
pending: false,
error: false,
done: true,
next: analyzers.includes(
env.ethereumAnalyzerContract,
)
? "eth"
: analyzers.includes(env.aminoAnalyzerContract)
? "cosmos"
: // fixme
(walletConnectRequestId &&
walletConnectTopic) ||
snapRequestId
? "eth-raw"
: undefined,
value: signRequest?.signedData,
};
default:
return {
pending: false,
error: true,
done: true,
};
}
};
}
break;
}
case warden.warden.v1beta3.MsgNewKeyRequestResponse.typeUrl: {
const { id } =
warden.warden.v1beta3.MsgNewKeyRequestResponse.decode(value);
getStatus = async (client) => {
const { keyRequest } =
await client.warden.warden.v1beta3.keyRequestById({
id,
});
switch (keyRequest?.status) {
case warden.warden.v1beta3.KeyRequestStatus
.KEY_REQUEST_STATUS_PENDING:
return {
pending: true,
error: false,
done: false,
};
case warden.warden.v1beta3.KeyRequestStatus
.KEY_REQUEST_STATUS_FULFILLED:
return {
pending: false,
error: false,
done: true,
value: keyRequest.id,
};
default:
return {
pending: false,
error: true,
done: true,
};
}
};
break;
}
default:
throw new Error(`action type not implemented: ${typeUrl}`);
}
return { getStatus };
};
Tools
Biome

[error] 50-54: 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:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

Comment on lines +226 to +241
const _ENABLED_ETH_CHAINS: { chainName: ChainName; testnet?: boolean }[] = [
{ chainName: "arbitrum" },
{ chainName: "base" },
{ chainName: "bsc" },
{ chainName: "mainnet" },
{ chainName: "optimism" },
{ chainName: "sepolia", testnet: true },
];

export const ENABLED_ETH_CHAINS = _ENABLED_ETH_CHAINS.filter(({ testnet }) =>
env.networkVisibility === "all"
? true
: env.networkVisibility === "mainnet"
? !testnet
: Boolean(testnet),
);
Copy link
Contributor

Choose a reason for hiding this comment

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

Approve the filtering logic for Ethereum chains.

The implementation of the filtering logic based on the networkVisibility environment variable is sound. It enhances the flexibility and security by ensuring that only the appropriate chains are exposed based on the operational environment.

The changes are approved.

It would be beneficial to add unit tests to verify the filtering logic under different networkVisibility settings. Would you like assistance in setting up these tests?


export const COSMOS_CHAINS: {
console.log("ENABLED_ETH_CHAINS", ENABLED_ETH_CHAINS);
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider conditional logging for production environments.

The addition of a console log to output ENABLED_ETH_CHAINS can be useful for debugging but might not be suitable for a production environment due to potential clutter and information leakage.

Consider wrapping this log statement with a condition to check if the environment is not production:

+ if (env.nodeEnv !== 'production') {
+   console.log("ENABLED_ETH_CHAINS", ENABLED_ETH_CHAINS);
+ }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log("ENABLED_ETH_CHAINS", ENABLED_ETH_CHAINS);
if (env.nodeEnv !== 'production') {
console.log("ENABLED_ETH_CHAINS", ENABLED_ETH_CHAINS);
}

Comment on lines +239 to +244
if (type === "key" && typeof status.value === "bigint") {
const keyId = status.value;
const settings = { ...ks?.settings, [keyId.toString()]: ks?.settings?.[TEMP_KEY] };
delete settings[TEMP_KEY];
setKeySettings({ settings })
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Enhance state management logic for key settings updates.

The logic for updating key settings based on the action result is a critical part of the component's functionality. The implementation correctly checks for the action type and status before updating the settings. However, there's a potential issue with direct manipulation of state objects which might lead to unintended side effects.

Ensure that state updates are handled immutably to prevent issues with React's state management. Here's a proposed change to handle state updates more safely:

- const settings = { ...ks?.settings, [keyId.toString()]: ks?.settings?.[TEMP_KEY] };
- delete settings[TEMP_KEY];
- setKeySettings({ settings })
+ const updatedSettings = { ...ks?.settings };
+ if (TEMP_KEY in updatedSettings) {
+     updatedSettings[keyId.toString()] = updatedSettings[TEMP_KEY];
+     delete updatedSettings[TEMP_KEY];
+ }
+ setKeySettings({ settings: updatedSettings });

This change ensures that the settings object is copied and modified as a new instance, preserving immutability and potentially preventing bugs related to state updates.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (type === "key" && typeof status.value === "bigint") {
const keyId = status.value;
const settings = { ...ks?.settings, [keyId.toString()]: ks?.settings?.[TEMP_KEY] };
delete settings[TEMP_KEY];
setKeySettings({ settings })
}
if (type === "key" && typeof status.value === "bigint") {
const keyId = status.value;
const updatedSettings = { ...ks?.settings };
if (TEMP_KEY in updatedSettings) {
updatedSettings[keyId.toString()] = updatedSettings[TEMP_KEY];
delete updatedSettings[TEMP_KEY];
}
setKeySettings({ settings: updatedSettings });
}

Comment on lines +36 to +50
const { walletManager } = useContext(walletContext);
const { data: ks, setData: setKeySettings } = useKeySettingsState();
const { toast } = useToast()
const { w } = useWeb3Wallet("wss://relay.walletconnect.org");
const { setData } = useActionsState();

const { getOfflineSignerDirect: getOfflineSigner } = useChain(
env.cosmoskitChainName,
);

const type = typeof item.keyThemeIndex !== "undefined" ?
"key" : (["walletConnectRequestId", "walletConnectTopic"] as const).every(key => typeof item[key] !== "undefined") ?
"wc" : typeof item.snapRequestId ?
"snap" : undefined

Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor action type determination logic for clarity and maintainability.

The new implementation for determining the action type (type) is more concise and readable. However, there's a static analysis error reported on line 48 due to a constant condition in the ternary operation. This might be a false positive, but it's worth verifying if the logic can be simplified or if there's an actual issue with the condition always evaluating to a constant value.

Consider revising the logic to ensure it's dynamic and correctly handles various conditions without resulting in constant outcomes. Here's a proposed refactor to address the potential issue:

- const type = typeof item.keyThemeIndex !== "undefined" ?
-     "key" : (["walletConnectRequestId", "walletConnectTopic"] as const).every(key => typeof item[key] !== "undefined") ?
-         "wc" : typeof item.snapRequestId ?
-             "snap" : undefined
+ const determineType = () => {
+     if (typeof item.keyThemeIndex !== "undefined") return "key";
+     if (item.walletConnectRequestId && item.walletConnectTopic) return "wc";
+     if (item.snapRequestId) return "snap";
+     return undefined;
+ };
+ const type = determineType();

This refactoring ensures that each condition is evaluated independently and only when necessary, potentially resolving the static analysis error.

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const { walletManager } = useContext(walletContext);
const { data: ks, setData: setKeySettings } = useKeySettingsState();
const { toast } = useToast()
const { w } = useWeb3Wallet("wss://relay.walletconnect.org");
const { setData } = useActionsState();
const { getOfflineSignerDirect: getOfflineSigner } = useChain(
env.cosmoskitChainName,
);
const type = typeof item.keyThemeIndex !== "undefined" ?
"key" : (["walletConnectRequestId", "walletConnectTopic"] as const).every(key => typeof item[key] !== "undefined") ?
"wc" : typeof item.snapRequestId ?
"snap" : undefined
const { walletManager } = useContext(walletContext);
const { data: ks, setData: setKeySettings } = useKeySettingsState();
const { toast } = useToast()
const { w } = useWeb3Wallet("wss://relay.walletconnect.org");
const { setData } = useActionsState();
const { getOfflineSignerDirect: getOfflineSigner } = useChain(
env.cosmoskitChainName,
);
const determineType = () => {
if (typeof item.keyThemeIndex !== "undefined") return "key";
if (item.walletConnectRequestId && item.walletConnectTopic) return "wc";
if (item.snapRequestId) return "snap";
return undefined;
};
const type = determineType();
Tools
Biome

[error] 48-48: Unexpected constant condition.

(lint/correctness/noConstantCondition)

@alex-nax alex-nax requested a review from jjheywood August 28, 2024 13:13
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Outside diff range, codebase verification and nitpick comments (1)
spaceward/src/pages/Intents.tsx (1)

166-167: Remove console log statement in production.

While adding a console log statement to log rules.data can be useful for debugging, it introduces a side effect that may affect performance or clutter the console in production. Consider removing this statement before deploying to production.

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between be7e2d3 and bd7f9fe.

Files selected for processing (10)
  • spaceward/src/components/SendEth.tsx (1 hunks)
  • spaceward/src/config/tokens.ts (3 hunks)
  • spaceward/src/features/actions/Sidebar.tsx (10 hunks)
  • spaceward/src/features/assets/Assets.tsx (1 hunks)
  • spaceward/src/features/assets/queries.ts (8 hunks)
  • spaceward/src/features/home/HomeAssets.tsx (1 hunks)
  • spaceward/src/features/home/TotalAssetValue.tsx (1 hunks)
  • spaceward/src/features/intents/util/query.ts (1 hunks)
  • spaceward/src/features/modals/util.ts (1 hunks)
  • spaceward/src/pages/Intents.tsx (1 hunks)
Files skipped from review due to trivial changes (3)
  • spaceward/src/features/home/HomeAssets.tsx
  • spaceward/src/features/intents/util/query.ts
  • spaceward/src/features/modals/util.ts
Files skipped from review as they are similar to previous changes (1)
  • spaceward/src/features/assets/queries.ts
Additional context used
Biome
spaceward/src/features/actions/Sidebar.tsx

[error] 48-48: Unexpected constant condition.

(lint/correctness/noConstantCondition)

Additional comments not posted (11)
spaceward/src/features/home/TotalAssetValue.tsx (1)

12-12: LGTM!

The destructuring of provider from the object returned by getProvider("sepolia") is a good practice for future extensibility.

The code changes are approved.

spaceward/src/components/SendEth.tsx (1)

11-11: LGTM!

The destructuring of provider from the object returned by getProvider("sepolia") is a good practice for future extensibility.

The code changes are approved.

spaceward/src/config/tokens.ts (2)

226-241: Approve the filtering logic for Ethereum chains.

The implementation of the filtering logic based on the networkVisibility environment variable is sound. It enhances the flexibility and security by ensuring that only the appropriate chains are exposed based on the operational environment.

The code changes are approved.


Line range hint 243-290: Approve the filtering logic for Cosmos chains.

The implementation of the filtering logic based on the networkVisibility environment variable is sound. It enhances the flexibility and security by ensuring that only the appropriate chains are exposed based on the operational environment.

The code changes are approved.

spaceward/src/features/assets/Assets.tsx (1)

18-18: LGTM!

Destructuring the provider variable from the object returned by getProvider("sepolia") is a good change. It enhances flexibility and readability.

The code changes are approved.

spaceward/src/pages/Intents.tsx (1)

163-163: Verify the impact of increasing the pagination limit.

Increasing the pagination limit from BigInt(100) to BigInt(100000) significantly expands the number of items that can be retrieved in a single request. Ensure that this change does not negatively impact data processing and rendering times.

spaceward/src/features/actions/Sidebar.tsx (5)

5-5: LGTM!

The import of useChain and walletContext from @cosmos-kit/react-lite is a good change. It indicates the utilization of context for wallet management and chain-related functionalities.

The code changes are approved.


36-36: LGTM!

Using useContext to access walletContext in the ActionItem component is a good change. It facilitates the management of wallet states and improves interactions with wallet-related data.

The code changes are approved.


374-374: LGTM!

Using the getProvider function to get the provider for broadcasting transactions is a good change. It enhances the flexibility and maintainability of the code.

The code changes are approved.


489-497: LGTM!

Resolving the RPC endpoint for the Cosmos chain ensures that the correct endpoint is used for broadcasting transactions. This change improves the reliability of the code.

The code changes are approved.


239-244: Enhance state management logic for key settings updates.

The logic for updating key settings based on the action result is correctly implemented. However, ensure that state updates are handled immutably to prevent issues with React's state management.

- const settings = { ...ks?.settings, [keyId.toString()]: ks?.settings?.[TEMP_KEY] };
- delete settings[TEMP_KEY];
- setKeySettings({ settings })
+ const updatedSettings = { ...ks?.settings };
+ if (TEMP_KEY in updatedSettings) {
+     updatedSettings[keyId.toString()] = updatedSettings[TEMP_KEY];
+     delete updatedSettings[TEMP_KEY];
+ }
+ setKeySettings({ settings: updatedSettings });

Likely invalid or redundant comment.

Comment on lines +46 to +50
const type = typeof item.keyThemeIndex !== "undefined" ?
"key" : (["walletConnectRequestId", "walletConnectTopic"] as const).every(key => typeof item[key] !== "undefined") ?
"wc" : typeof item.snapRequestId ?
"snap" : undefined

Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor action type determination logic to address static analysis error.

The refactored logic for determining the action type is more concise and readable. However, there's a static analysis error due to a constant condition in the ternary operation. Consider revising the logic to ensure it handles various conditions correctly.

- const type = typeof item.keyThemeIndex !== "undefined" ?
-     "key" : (["walletConnectRequestId", "walletConnectTopic"] as const).every(key => typeof item[key] !== "undefined") ?
-         "wc" : typeof item.snapRequestId ?
-             "snap" : undefined
+ const determineType = () => {
+     if (typeof item.keyThemeIndex !== "undefined") return "key";
+     if (item.walletConnectRequestId && item.walletConnectTopic) return "wc";
+     if (item.snapRequestId) return "snap";
+     return undefined;
+ };
+ const type = determineType();
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const type = typeof item.keyThemeIndex !== "undefined" ?
"key" : (["walletConnectRequestId", "walletConnectTopic"] as const).every(key => typeof item[key] !== "undefined") ?
"wc" : typeof item.snapRequestId ?
"snap" : undefined
const determineType = () => {
if (typeof item.keyThemeIndex !== "undefined") return "key";
if (item.walletConnectRequestId && item.walletConnectTopic) return "wc";
if (item.snapRequestId) return "snap";
return undefined;
};
const type = determineType();
Tools
Biome

[error] 48-48: Unexpected constant condition.

(lint/correctness/noConstantCondition)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between bd7f9fe and 6ee3139.

Files ignored due to path filters (1)
  • spaceward/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (4)
  • spaceward/package.json (1 hunks)
  • spaceward/src/features/modals/util.ts (4 hunks)
  • spaceward/src/lib/eth/constants.ts (1 hunks)
  • spaceward/src/pages/Intents.tsx (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • spaceward/src/features/modals/util.ts
  • spaceward/src/pages/Intents.tsx
Additional comments not posted (4)
spaceward/src/lib/eth/constants.ts (3)

36-36: LGTM!

The addition of the new RPC URL https://ethereum-sepolia.rpc.subquery.network/public enhances redundancy and reliability.


37-37: LGTM! But verify the reason for the replacement.

The addition of the new RPC URL https://rpc.sepolia.org/ seems valid. Ensure that the removed URL was no longer needed or was replaced for a valid reason.

Please confirm the reason for replacing the previous URL.


38-39: LGTM!

The addition of the new RPC URLs https://ethereum-sepolia.blockpi.network/v1/rpc/public and https://sepolia.gateway.tenderly.co enhances redundancy and reliability.

spaceward/package.json (1)

92-92: LGTM! But verify compatibility with other dependencies.

The update to the version of the "ethers" package from "^6.9.2" to "6.13.2" can ensure stability. However, verify compatibility with other dependencies that rely on "ethers".

Please confirm that this version update does not cause any compatibility issues with other dependencies.

@jjheywood jjheywood merged commit dd26e0c into main Aug 30, 2024
13 checks passed
@jjheywood jjheywood deleted the key-creation-tx branch August 30, 2024 09:22
mn13 pushed a commit that referenced this pull request Sep 3, 2024
* fix key icon in sidebar

cleanup

* fix getProider call

* bump ethers version; fix erc20 send
mn13 added a commit that referenced this pull request Sep 5, 2024
…dd-genesis-space (#723)

* validate bench32 in cmd
add-genesis-keychain
add-genesis-space

* in executeAnalyzers return error on bad contract address (#716)

* in executeAnalyzers return error on bad contract address

* update changelog

* validate bench32 in cmd
add-genesis-keychain
add-genesis-space

* fix spelling and duplicates

* * Added KeybaseId, Url and Name fields to keychain

* Added changelog

* Review comments

* Code review fixes

* Regenerated model

---------

Co-authored-by: Archie <artur.abliazimov@gmail.com>

* Fix of localnet.just (#726)

* Fixed localnet.just

* Fixed localnet.just

* Remove the GMP default params from genesis (#727)

* feat(faucet): new faucet (#479)

* feat(faucet): new faucet

This version of the Faucet does not have any limitations per user, only
limitations are daily token supply

* fix: minor css changes for mobile

* fix(faucet): add daily refresh and token refresh job

* fix(faucet): fix bugs and ci

* fix(faucet): remove unnessary go.mod files, replace dockerfile faucet-v2

* chore(faucet): remove unnessary variables and modify types

this will modify the types of DailyLimit and Batchinterval to remove
unnessary conversions and remove Cooldown and BatchInterval

* fix(faucet): acquire a lock when setting the new supply

* fix(faucet): removed locking where it's not needed

other enhancements as well, the loading and setting context to correct
place

* fix(faucet): converted background to much smaller image

* feat(faucet): make the run out of daily nicer

* feat(faucet): add new style

* feat(faucet): add check that same address cannot be multiple time in one batch

* feat(faucet): add metrics

* fix(faucet): Dockerfile libwasmvm was missing access rights

* feat(faucet): add pre input option to address form

---------

Co-authored-by: Jon Heywood <94459819+jjheywood@users.noreply.github.com>

* chore(wardend): bump ibc-go to v8.4.0

* docs: Update Keychain SDK (#706)

* Upgrade keychain docs

Update go version

Update json for keychain-fees

Update chain-id

* Add categorization to Keychain SDK

* Categorization

* Add Keychain SDK + Description

* Create a new tutorial

Add basic info for keychain

Implement main func with - handleKeyRequest and handleSignRequest

Write test function

* fixed a link in the Tools menu

* quick fixes

* quick fixes

* quick fixes

* remove )

---------

Co-authored-by: Margarita Skomorokh <ijonele@gmail.com>

* fixed links to the keychain sdk (#733)

* Made KeychainFees = nil invalid

* ci: add check to ensure go.mod is tidy

* chore: go mod tidy

* fix(wardend): ICAHostKeeper initialization requires QueryRouter to be set

Breaking change introduced in ibc-go v8.3

* feat(spaceward): key creation in sidebar (#728)

* fix key icon in sidebar

cleanup

* fix getProider call

* bump ethers version; fix erc20 send

* build: use new justfile commands

* fix(x/warden): make KeychainFees non-nullable

* fix(x/warden): allow empty KeychainFees

* cosmoshubtestnet hotfix; do not fail on wrong message type (#746)

* feat(faucet): configurable chain name (#747)

this change adds configurable chain/faucet name to the site

* fix(faucet): chain variable missing from struct (#749)

This PR adds the missing Chain variable that missed in #747

* #561 Keychain fees should not be paid in advance (#662)

* Added keychain max wanted fees handling

* Implemented new testcase & snapshot

* Added annotations

* Added keychain fee max value specification

* Code review fixes

* Changed validation messages

* fix(x/act): add support for sdk.Coins in CLI flags

* Changed type to sdk.Coin

* Updated CHANGELOG.md

* Implemented escrow accounts for keychain fees

* Added CHANGELOG.md line

* Regenerated keychain snapshot

* Updated keychain deduction fee code

* Added test case for fee deduction with --max-keychain-fee

* Fixed actions auto parsing for cli

* Fixed bug with not forking fees deduction and context missing values

* Docker versions update

* Update cmd/wardend/cmd/gen-keychains.go

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Proto rebuild

* Merged changes from #560

* Code-review fixes

* Implemented integration test for escrow account

* Code review fixes

* Made KeychainFees = nil invalid

* Fixed error message

* Keychain fee validations

* Code review fixes

* Merge conflict fixes

* Lint fixes

---------

Co-authored-by: Antonio Pitasi <antonio@pitasi.dev>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* feat(spaceward): update for rebrand (#748)

* feat(spaceward): New theme added

* fix(spaceward): Some theme fixes

* fix(spaceward): Fixed keychains

* fix(spaceward): Some theme fixes and metamask

* fix(spaceward): Some more

* fix(spaceward): Space Mono

* fix(spaceward): fix for space mono font issue (#750)

* fix(spaceward): updated welcome message (#751)

* fix(faucet): fix daily limit i64 (#755)

This fixes issue where user puts high uward amount to daily limit and go
cannot parse it due to int restrictions

* Add chain upgrade instructions for v0.4.2 (#757)

* Add chain upgrade instructions for v0.4.2

* Update v0.4.2.md

* update v0.4.2

Co-authored-by: Joonas Lehtimäki <joonas.lehtimaki@gmail.com>

* remove reference to side-car

---------

Co-authored-by: Joonas Lehtimäki <joonas.lehtimaki@gmail.com>

* fixed spelling (#758)

* fixed spelling

* deleted the tip, fixed spelling

* update slinky

* fix(x/act): simplify prepareHandlerContext to always use sdk.Context

* updated gov proto; fix governance types (#761)

* Fix returned field (#765)

* fix(spaceward): Fix logos (#767)

* fix(spaceward): Fix logos

* fix(spaceward): updated logo for WC connection and updated hover fill colour

---------

Co-authored-by: Jon Heywood <94459819+jjheywood@users.noreply.github.com>

* fix(faucet): tx page loading (#768)

* feat(faucet): add new metric dailySupply

* fix(faucet): page keeps loading even if tx was finished

---------

Co-authored-by: backsapc <backsapce@hotmail.com>
Co-authored-by: Archie <artur.abliazimov@gmail.com>
Co-authored-by: Joonas Lehtimäki <joonas.lehtimaki@gmail.com>
Co-authored-by: Jon Heywood <94459819+jjheywood@users.noreply.github.com>
Co-authored-by: Antonio Pitasi <antonio@pitasi.dev>
Co-authored-by: Aliasgar Merchant <44069404+alijnmerchant21@users.noreply.github.com>
Co-authored-by: Margarita Skomorokh <ijonele@gmail.com>
Co-authored-by: Margarita Skomorokh <margaret.skomorokh@anychart.com>
Co-authored-by: Alex D <alex.d.nax@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Alice <37526212+laniakea42@users.noreply.github.com>
Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants