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

Update hardhat account, support solana #190

Merged
merged 3 commits into from
Oct 29, 2024
Merged

Conversation

lukema95
Copy link
Collaborator

@lukema95 lukema95 commented Oct 19, 2024

related issue: #187

  1. Support automatic generation of Solana private keys. When using the --save option, store it in the SOLANA_PRIVATE_KEY environment variable in the .env file.
  2. Support recovery using Solana private key when using the --recover option. When ~/.config/solana/id.json exists locally, automatically load that private key. When it doesn't exist locally, users can input the private key in the command line or skip this step.
  3. Maintain backward compatibility. Locally, store PRIVATE_KEY, EVM_PRIVATE_KEY, and BTC_PRIVATE_KEY environment variables in the .env file, and their values are the same.

Summary by CodeRabbit

  • New Features

    • Introduced support for Solana wallets alongside EVM wallets.
    • Added functionality to retrieve Solana wallets from local files or user input.
    • Enhanced console output to display Solana wallet details upon creation.
  • Improvements

    • Updated prompts for clarity when entering recovery information.
    • Enhanced environment variable management to include Solana private keys.

@lukema95
Copy link
Collaborator Author

npx hardhat account --save  

    🔑 EVM Private key: 49db34db2e853bda91c17828eb614173573df9ec200bc563217aeb36687f2e0a

    🔑 Solana Private key: 2kP9uN3ySc25UNqhqqTWz5Vt1vRQpcjfgmcJ346NERKaTwUq99nwbVsPg61znaMTnwBHbYyAGnkKRmKgjJhhWq73

    🔐 EVM Mnemonic phrase: level treat gossip actress mistake parent trouble excite wild tone offer time

    😃 EVM address: 0xD7043474A099Cad2a0A3c12F746BA5A9aD74e85f
    😃 Bitcoin address: tb1qg5xxzl4qzn6pgee53a7kjve8lvewk43r8kpcjc
    😃 Bech32 address: zeta16uzrga9qn89d9g9rcyhhg6a94xkhf6zlne0vkz

    😃 Solana address: 2bZFnp4xkrhovr1ahDiuu7D8JxdoaWPyrptF4vDuy7ru

@lukema95
Copy link
Collaborator Author

@fadeev pls check

@fadeev
Copy link
Member

fadeev commented Oct 21, 2024

Looking good!

@lukema95 lukema95 marked this pull request as ready for review October 21, 2024 07:45
@lukema95 lukema95 requested review from andresaiello, fadeev and a team as code owners October 21, 2024 07:45
Copy link
Contributor

coderabbitai bot commented Oct 21, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request introduce functionality for handling Solana wallets in the account.ts file, alongside existing support for EVM wallets. A new method, getSolanaWalletFromLocalFileOrInput, is added to facilitate wallet retrieval from a configuration file or user input. The savePrivateKey function is modified to optionally handle Solana private keys, and various variable names are updated for clarity. Additionally, prompts for user input have been refined to improve user experience.

Changes

File Change Summary
packages/tasks/src/account.ts - Added method getSolanaWalletFromLocalFileOrInput for Solana wallet retrieval.
- Updated method signature of savePrivateKey to accept an optional solanaPrivateKey.
- Modified prompt in getWalletFromRecoveryInput for clarity.
- Changed variable names to evmWallet and solanaWallet in main function.
- Enhanced console output for Solana wallet creation.

Possibly related PRs

  • Support query solana balances #185: The changes in balances.ts regarding the handling of Solana private keys and the introduction of new environment variables directly relate to the enhancements made in account.ts for managing Solana wallets and private keys.

Suggested reviewers

  • fadeev

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai 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
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: 2

🧹 Outside diff range and nitpick comments (1)
packages/tasks/src/account.ts (1)

126-129: Exercise caution when displaying private keys in the console.

Displaying private keys in plain text may pose a security risk if the console output is logged or viewed by unauthorized persons. Consider informing users to handle the displayed keys securely.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 51b8705 and deee8db.

⛔ Files ignored due to path filters (26)
  • typechain-types/@openzeppelin/contracts/index.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC1155Errors.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC20Errors.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC721Errors.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/index.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/interfaces/index.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/token/ERC20/ERC20.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/token/ERC20/IERC20.ts is excluded by !typechain-types/**
  • typechain-types/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.ts is excluded by !typechain-types/**
  • typechain-types/contracts/EthZetaMock.sol/ZetaEthMock.ts is excluded by !typechain-types/**
  • typechain-types/contracts/TestZRC20.ts is excluded by !typechain-types/**
  • typechain-types/contracts/shared/MockZRC20.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/index.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC1155Errors__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC20Errors__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/IERC721Errors__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/interfaces/draft-IERC6093.sol/index.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/interfaces/index.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/token/ERC20/ERC20__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/token/ERC20/IERC20__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/contracts/EthZetaMock.sol/ZetaEthMock__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/contracts/TestZRC20__factory.ts is excluded by !typechain-types/**
  • typechain-types/factories/contracts/shared/MockZRC20__factory.ts is excluded by !typechain-types/**
  • typechain-types/hardhat.d.ts is excluded by !typechain-types/**
  • typechain-types/index.ts is excluded by !typechain-types/**
📒 Files selected for processing (1)
  • packages/tasks/src/account.ts (3 hunks)
🧰 Additional context used
🪛 Biome
packages/tasks/src/account.ts

[error] 85-86: Unnecessary continue statement

Unsafe fix: Delete the unnecessary continue statement

(lint/correctness/noUnnecessaryContinue)

packages/tasks/src/account.ts Outdated Show resolved Hide resolved
packages/tasks/src/account.ts Outdated Show resolved Hide resolved
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: 3

🧹 Outside diff range and nitpick comments (3)
packages/tasks/src/account.ts (3)

63-64: Validate the Format of secretKey Before Usage

Before creating a Keypair from the secretKey, add validation to ensure it is in the correct format. This prevents potential runtime errors if the id.json file contains invalid data.

Consider adding a validation step:

const secretKey = JSON.parse(fileContent);
+if (!Array.isArray(secretKey) || secretKey.length !== 64) {
+  throw new Error("Invalid Solana secret key format in id.json.");
+}

74-75: Clarify Prompt Message for Solana Private Key Input

To improve usability, specify the expected format of the Solana private key in the prompt message. This helps users provide the correct input without confusion.

Update the prompt message:

let solanaPrivateKey = await input({
-  message: "Solana private key (press Enter to skip):",
+  message: "Solana private key (base58 encoded, press Enter to skip):",
});

126-138: Standardize Formatting of Console Outputs

The console outputs have inconsistent indentation, which may affect readability. Standardizing the indentation improves the user experience.

Adjust the indentation as follows:

 console.log(`
-    🔑 EVM Private key: ${pk}`);
+🔑 EVM Private key: ${pk}`);

 solanaWallet &&
   console.log(`
-    🔑 Solana Private key: ${bs58.encode(solanaWallet.secretKey)}`);
+🔑 Solana Private key: ${bs58.encode(solanaWallet.secretKey)}`);

 mnemonic &&
   console.log(`
-    🔐 EVM Mnemonic phrase: ${mnemonic.phrase}`);
+🔐 EVM Mnemonic phrase: ${mnemonic.phrase}`);

 console.log(`
-  😃 EVM address: ${address}
-    😃 Bitcoin address: ${bitcoinAddress(pk, "testnet")}
-    😃 Bech32 address: ${hexToBech32Address(address, "zeta")}`);
+😃 EVM address: ${address}
+😃 Bitcoin address: ${bitcoinAddress(pk, "testnet")}
+😃 Bech32 address: ${hexToBech32Address(address, "zeta")}`);

 solanaWallet &&
   console.log(`
-    😃 Solana address: ${solanaWallet.publicKey.toString()}`);
+😃 Solana address: ${solanaWallet.publicKey.toString()}`);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between deee8db and 118431c.

📒 Files selected for processing (1)
  • packages/tasks/src/account.ts (3 hunks)
🧰 Additional context used
🪛 Biome
packages/tasks/src/account.ts

[error] 85-86: Unnecessary continue statement

Unsafe fix: Delete the unnecessary continue statement

(lint/correctness/noUnnecessaryContinue)

🔇 Additional comments (1)
packages/tasks/src/account.ts (1)

99-100: Verify Using the Same Private Key for EVM and Bitcoin

The code assigns the same private key to both EVM_PRIVATE_KEY and BTC_PRIVATE_KEY. Ensure that this is intentional and that using the same key across different platforms does not introduce security vulnerabilities.

You can run the following script to check for any differing implementations:

Comment on lines 1 to 3
import { bs58 } from "@coral-xyz/anchor/dist/cjs/utils/bytes";
import { input } from "@inquirer/prompts";
import { Keypair } from "@solana/web3.js";
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use Direct Import of bs58 Package for Clarity and Maintainability

Instead of importing bs58 from "@coral-xyz/anchor/dist/cjs/utils/bytes", consider importing it directly from the bs58 package. This reduces dependency on internal paths of other packages, which may change and cause unexpected issues.

Apply this diff to import bs58 directly:

-import { bs58 } from "@coral-xyz/anchor/dist/cjs/utils/bytes";
+import bs58 from "bs58";

Ensure the bs58 package is added to your project's dependencies:

npm install bs58

packages/tasks/src/account.ts Show resolved Hide resolved
packages/tasks/src/account.ts Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (1)
packages/tasks/src/account.ts (1)

49-87: LGTM: Solana wallet retrieval function added.

The new getSolanaWalletFromLocalFileOrInput function provides a robust way to retrieve Solana wallets, with good support for both automatic loading from a config file and manual input.

Consider improving error handling for config file loading.

As per a previous review comment, instead of throwing an error when failing to load the Solana wallet from the config file, consider logging the error and proceeding to prompt the user for input. This would enhance user experience by allowing recovery from errors without terminating the process.

Apply this diff to improve error handling:

    } catch (error) {
      console.error("Failed to load Solana private key:", error);
-     throw new Error(
-       `Failed to load Solana wallet from ${solanaConfigPath}`
-     );
+     console.log("Proceeding to manual input...");
    }

Add a retry limit for manual Solana key input.

The current implementation could potentially lead to an infinite loop if the user repeatedly enters invalid keys. Consider adding a maximum number of retry attempts to improve user experience.

Apply this diff to add a retry limit:

+   const MAX_RETRIES = 3;
+   let retries = 0;
    while (true) {
+     if (retries >= MAX_RETRIES) {
+       console.log("Maximum retry attempts reached. Skipping Solana wallet creation.");
+       return null;
+     }
      let solanaPrivateKey = await input({
        message: "Solana private key (press Enter to skip):",
      });
      if (solanaPrivateKey.trim() === "") {
        console.log("Skipped Solana private key input.");
        return null;
      }
      try {
        return Keypair.fromSecretKey(bs58.decode(solanaPrivateKey));
      } catch (e) {
        console.error(`❌ Invalid Solana private key: ${e}`);
+       retries++;
      }
    }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 118431c and 37b24d4.

📒 Files selected for processing (1)
  • packages/tasks/src/account.ts (3 hunks)
🧰 Additional context used
🔇 Additional comments (7)
packages/tasks/src/account.ts (7)

2-2: LGTM: Import changes for Solana support.

The addition of Keypair import and the direct import of bs58 are appropriate for the new Solana functionality. The bs58 import change also addresses a previous review comment.

Also applies to: 5-5


28-28: LGTM: Clarified prompt for EVM wallet recovery.

The updated prompt message clearly specifies that the input is for EVM wallets, which is a good distinction given the new Solana support.


89-103: LGTM: Updated savePrivateKey function to support Solana.

The changes to the savePrivateKey function appropriately handle the new Solana private key while maintaining existing functionality for EVM and BTC keys.

Security concern: Storing private keys in plaintext.

Saving private keys in plaintext within environment files poses security risks, especially if the .env file is not properly secured or is accidentally committed to version control.
[security]
Consider implementing one or more of the following security measures:

  1. Encrypt the private keys before saving them to the .env file.
  2. Provide clear instructions to users on how to securely store and manage their private keys.
  3. Implement a secure key management system or integrate with existing key management solutions.
  4. Add a prominent warning in the console output about the security implications of storing private keys in the .env file.

110-118: LGTM: Integration of Solana wallet functionality in main function.

The changes to the main function effectively integrate Solana wallet functionality alongside existing EVM wallet handling. The updated variable names (evmWallet and solanaWallet) improve code clarity.


125-140: LGTM: Comprehensive console output for EVM and Solana wallets.

The updated console output provides clear and comprehensive information for both EVM and Solana wallets. The use of conditional statements ensures that Solana information is only displayed when available.


143-146: LGTM: Updated savePrivateKey call to include Solana private key.

The savePrivateKey call has been correctly updated to include the Solana private key when available, aligning with the new function signature.


Line range hint 1-164: Overall: Excellent implementation of Solana wallet support.

The changes in this pull request successfully introduce Solana wallet functionality while maintaining existing EVM and BTC support. The code is well-structured, with clear variable names and appropriate error handling. The integration of Solana wallet generation, recovery, and key saving is comprehensive and aligns well with the existing codebase.

A few minor suggestions for improvement have been made, primarily around error handling and security considerations. Addressing these points will further enhance the robustness and security of the implementation.

Great work on this feature addition!

@fadeev fadeev merged commit f0b0244 into zeta-chain:main Oct 29, 2024
3 checks passed
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