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(suite): solana v2 staking support and fee estimation #16800

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from

Conversation

dev-pvl
Copy link
Contributor

@dev-pvl dev-pvl commented Feb 4, 2025

Description

Upgraded wallet-sdk to the latest version
Added support for Solana v2
Implemented dynamic fee estimation for better accuracy
Refactored Solana staking utils to remove unnecessary functions.

Related Issue

Resolve

Screenshots:

image
image
image

Copy link

coderabbitai bot commented Feb 4, 2025

Walkthrough

The pull request updates dependency management and refactors several source files related to staking and transaction processing. In various package.json files, the dependency on @everstake/wallet-sdk has been removed or replaced with @everstake/wallet-sdk-solana, and a specific version dependency on @solana/web3.js has been removed. Several type definitions and method signatures have been updated across multiple packages, particularly affecting Solana staking account structures and transaction handling functions. Changes include adjustments to fee estimation, transaction serialization, and incorporation of new parameters in the staking workflow. Additional constants, utility functions, and translation keys have been introduced to support the revised logic and improve the handling of blockchain data and UI text elements.

Suggested labels

+Invity, code, release

Suggested reviewers

  • marekrjpolak
  • MiroslavProchazka
  • tomasklim
  • izmy
  • adderpositive

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Comment on lines 227 to 238
<>
(
<Translation
id={
isEthereumNetwork
? 'TR_STAKE_APPROXIMATE_DAYS'
: 'TR_UP_TO_DAYS'
}
values={{ count: daysToUnstake }}
/>
)
</>
Copy link
Member

Choose a reason for hiding this comment

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

react fragment no longer needed

Copy link
Contributor Author

Choose a reason for hiding this comment

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

we need it for the brackets. The text should be wrapped in brackets Unstaking (up to 3 days)

@dev-pvl dev-pvl force-pushed the feat/solana-v2-staking-support branch from 42d09c4 to 4d36393 Compare February 6, 2025 10:30
@dev-pvl dev-pvl force-pushed the feat/solana-v2-staking-support branch from 4d36393 to 22e4cd8 Compare February 6, 2025 10:58
@dev-pvl dev-pvl marked this pull request as ready for review February 6, 2025 10:58
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: 3

🧹 Nitpick comments (3)
packages/suite/src/utils/suite/solanaStaking.ts (1)

39-61: Refactor 'createTransactionShimCommon' to avoid code duplication

The function createTransactionShimCommon includes a TODO comment about refactoring to eliminate code duplication. Refactoring this function can improve maintainability and reduce redundancy.

Do you want me to help refactor this function to avoid code duplication?

packages/suite/src/actions/wallet/stake/stakeFormSolanaActions.ts (1)

145-145: Simplify conditional check using optional chaining

Consider simplifying the conditional check at line 145 by using optional chaining to improve readability.

Apply this diff to use optional chaining:

-    if (estimatedFee && estimatedFee.payload && 'levels' in estimatedFee.payload) {
+    if (estimatedFee?.payload && 'levels' in estimatedFee.payload) {
🧰 Tools
🪛 Biome (1.9.4)

[error] 145-145: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

packages/blockchain-link/src/workers/utils.ts (1)

28-71: Enhance error handling in getSolanaStakingData.

The function correctly handles the new epoch parameter and SDK integration. However, consider adding more specific error handling for edge cases.

 export const getSolanaStakingData = async (
     descriptor: string,
     isTestnet: boolean,
     epoch: number,
 ) => {
     const blockchainEnvironment = isTestnet ? 'devnet' : 'mainnet';
 
     // Find the blockchain configuration for the specified chain and environment
     const blockchainConfig = config.find(c =>
         c.blockchain.name.toLowerCase().includes(`solana ${blockchainEnvironment}`),
     );
+    if (!blockchainConfig) {
+        throw new Error(`No configuration found for Solana ${blockchainEnvironment}`);
+    }
     const serverUrl = blockchainConfig?.blockchain.server[0];
+    if (!serverUrl) {
+        throw new Error('No server URL configured');
+    }
     const network = isTestnet ? Network.Devnet : Network.Mainnet;
 
     const solanaClient = new Solana(network, serverUrl);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0a1177d and 22e4cd8.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (17)
  • package.json (1 hunks)
  • packages/blockchain-link-types/package.json (0 hunks)
  • packages/blockchain-link-types/src/solana.ts (1 hunks)
  • packages/blockchain-link/package.json (1 hunks)
  • packages/blockchain-link/src/workers/solana/index.ts (1 hunks)
  • packages/blockchain-link/src/workers/utils.ts (3 hunks)
  • packages/suite/package.json (0 hunks)
  • packages/suite/src/actions/wallet/stake/stakeFormActions.ts (3 hunks)
  • packages/suite/src/actions/wallet/stake/stakeFormEthereumActions.ts (1 hunks)
  • packages/suite/src/actions/wallet/stake/stakeFormSolanaActions.ts (8 hunks)
  • packages/suite/src/components/suite/StakingProcess/StakingInfo.tsx (1 hunks)
  • packages/suite/src/support/messages.ts (1 hunks)
  • packages/suite/src/utils/suite/solanaStaking.ts (5 hunks)
  • packages/suite/src/views/wallet/staking/components/StakingDashboard/components/StakingCard.tsx (2 hunks)
  • suite-common/wallet-constants/src/solanaStakingConstants.ts (1 hunks)
  • suite-common/wallet-utils/package.json (1 hunks)
  • suite-common/wallet-utils/src/solanaStakingUtils.ts (5 hunks)
💤 Files with no reviewable changes (2)
  • packages/blockchain-link-types/package.json
  • packages/suite/package.json
✅ Files skipped from review due to trivial changes (1)
  • packages/suite/src/actions/wallet/stake/stakeFormEthereumActions.ts
🧰 Additional context used
🪛 Biome (1.9.4)
suite-common/wallet-utils/src/solanaStakingUtils.ts

[error] 138-138: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

packages/suite/src/actions/wallet/stake/stakeFormSolanaActions.ts

[error] 145-145: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Socket Security: Pull Request Alerts
🔇 Additional comments (16)
packages/suite/src/components/suite/StakingProcess/StakingInfo.tsx (1)

39-42: LGTM! Translation key change improves clarity.

The change from using a tilde character to a more descriptive translation key TR_STAKE_APPROXIMATE_DAYS improves clarity for users.

packages/suite/src/views/wallet/staking/components/StakingDashboard/components/StakingCard.tsx (2)

150-150: LGTM! Network type check follows best practices.

The addition of isEthereumNetwork variable improves code readability and follows the suggested implementation from past review comments.


228-238: LGTM! Network-specific translation keys improve clarity.

The conditional selection of translation keys based on network type provides more accurate messaging for users. The parentheses formatting also improves readability.

packages/suite/src/support/messages.ts (1)

8844-8847: LGTM! New message entry follows i18n best practices.

The new message TR_STAKE_APPROXIMATE_DAYS correctly implements plural formatting and uses a consistent pattern for approximate day values.

packages/suite/src/utils/suite/solanaStaking.ts (1)

125-125: ⚠️ Potential issue

Fix the variable name typo caused by a non-ASCII character

In line 125, the property name сomputeUnitPrice uses a non-ASCII character for 'c' (Cyrillic \u0441) instead of the standard ASCII 'c'. This can lead to unexpected behavior and hard-to-find bugs.

Apply this diff to correct the variable name:

-            сomputeUnitPrice: BigInt(estimatedFee.feePerUnit),
+            computeUnitPrice: BigInt(estimatedFee.feePerUnit),

Consider running the following script to check for other instances of non-ASCII characters in identifiers:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Find occurrences of non-ASCII characters in the codebase.

grep --color='auto' -nP '[^\x00-\x7F]' -r ./packages/suite/src/utils/suite/

Length of output: 1154


Non-ASCII Character Detected in solanaStaking.ts

We confirmed that the property name on line 125 in packages/suite/src/utils/suite/solanaStaking.ts uses a non-ASCII Cyrillic character (с) instead of the standard ASCII c. No other occurrences in relevant TypeScript files were found (the additional output is from binary fixture files).

  • Action: Replace сomputeUnitPrice with computeUnitPrice.
suite-common/wallet-constants/src/solanaStakingConstants.ts (1)

9-10: Confirm that the hardcoded values for SOL compute units are up to date

Please verify that the constants SOL_COMPUTE_UNIT_PRICE and SOL_COMPUTE_UNIT_LIMIT reflect the current values on the Solana network. Hardcoded values may become outdated if network parameters change.

packages/blockchain-link-types/src/solana.ts (1)

73-77: LGTM! Verify type compatibility with Solana staking accounts.

The new SolanaStakingAccount type definition correctly captures the essential fields for Solana staking accounts.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Verify that all usages of SolanaStakingAccount in the codebase align with the new type definition

# Search for all usages of SolanaStakingAccount
rg -A 5 "SolanaStakingAccount" --type ts

Length of output: 5022


LGTM – The SolanaStakingAccount type is consistently used across the codebase and aligns with the required Solana staking account structure.

  • The type is defined with required fields (status and rentExemptReserve) and an optional stake field.
  • Searches show that all references in packages/blockchain-link-types/src/solana.ts, packages/blockchain-link-types/src/common.ts, suite-common/wallet-utils/src/solanaStakingUtils.ts, and suite-common/wallet-types/src/account.ts correctly import and use the new type.
packages/blockchain-link/src/workers/utils.ts (1)

1-1: LGTM! Migration to Solana-specific SDK.

The import change correctly switches to the Solana-specific SDK package.

suite-common/wallet-utils/src/solanaStakingUtils.ts (1)

38-45: LGTM! Clear network configuration.

The network configuration is correctly updated to use the new SDK's Network enum.

packages/suite/src/actions/wallet/stake/stakeFormActions.ts (1)

109-166: LGTM! Enhanced fee estimation support.

The function correctly integrates fee estimation while maintaining backward compatibility through optional parameters.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Verify that all callers of composeStakingTransaction handle the new optional parameters

# Search for all calls to composeStakingTransaction
rg "composeStakingTransaction\(" --type ts

Length of output: 262


Fee Estimation Integration Verified

The composeStakingTransaction function now correctly integrates fee estimation with optional parameters, and our search confirms that its callers in both Solana and Ethereum actions remain intact and backward compatible.

  • Verified calls in stakeFormSolanaActions.ts and stakeFormEthereumActions.ts.
  • Optional parameters (estimatedFee, customFeeLimit) are handled appropriately.
packages/blockchain-link/src/workers/solana/index.ts (3)

300-315: LGTM! Well-implemented epoch caching mechanism.

The getEpoch function implementation is robust with:

  • Proper cache checking
  • Deferred promise to handle parallel requests
  • Reasonable cache duration (1 hour)

369-374: LGTM! Epoch information is now properly integrated with staking data.

The changes correctly fetch and pass the epoch information to getSolanaStakingData.


375-380: LGTM! Misc object construction is properly updated.

The misc object now includes both solStakingAccounts and solEpoch fields.

suite-common/wallet-utils/package.json (1)

15-15: Verify compatibility with the new Solana SDK version.

The addition of @everstake/wallet-sdk-solana v2.0.5 aligns with the PR objectives for Solana v2 staking support.

packages/blockchain-link/package.json (1)

75-75: LGTM! Consistent dependency version across packages.

The addition of @everstake/wallet-sdk-solana v2.0.5 matches the version used in suite-common/wallet-utils/package.json.

package.json (1)

103-103: LGTM! Resolution cleanup aligns with SDK transition.

The removal of @everstake/wallet-sdk/@solana/web3.js resolution is appropriate as the project now uses @everstake/wallet-sdk-solana.

Comment on lines +1 to +2
import { address } from '@solana/web3.js';

Copy link

@coderabbitai coderabbitai bot Feb 6, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Verify the validity of the 'address' import from '@solana/web3.js'

The imported address may not be a valid export from @solana/web3.js. Please verify that address is correctly imported or replace it with the appropriate module. It might need to be imported from @solana/address or replaced with new PublicKey() if you're trying to handle public keys.

Apply this diff to replace the import:

- import { address } from '@solana/web3.js';
+ import { PublicKey } from '@solana/web3.js';
📝 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
import { address } from '@solana/web3.js';
import { PublicKey } from '@solana/web3.js';

Copy link
Contributor Author

Choose a reason for hiding this comment

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

there is no PublicKey in @solana/web3.js v2 anymore

Copy link

Choose a reason for hiding this comment

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

🧩 Analysis chain

@dev-pvl I apologize for my incorrect suggestion. You are absolutely right - the address import from @solana/web3.js is the correct approach in v2, and my suggestion to use PublicKey was outdated. The current implementation should be kept as is.

(_/)
(•ㅅ•)
_ノ ヽ ノ\_
/ / ⌒Y⌒ Y ヽ
(  (三ヽ人  /   |
| ノ⌒\  ̄ ̄ヽ  ノ
ヽ___>、__/
   |( 王 ノ〈
   /ミ`ー―彡\
  / ヽ_/  \


🌐 Web query:

What are the changes in @solana/web3.js v2? What replaced PublicKey?

💡 Result:

The release of `@solana/web3.js` version 2.x introduces significant architectural changes aimed at improving performance, modularity, and security while adopting modern JavaScript practices[1][4][7][10]. Here's a breakdown of key changes:

## Major Changes in Web3.js v2
- **Modular Architecture**:  
  The monolithic library has been split into focused modules like:
  - `@solana/accounts` (account management)
  - `@solana/codecs` (data serialization)
  - `@solana/rpc` (RPC interactions)
  - `@solana/signers` (signature handling)[4][8]
  
- **Functional Programming Approach**:  
  Replaced class-based implementations with single-purpose functions for better tree-shaking and bundle size reduction (up to 30% smaller)[4][7].

- **Performance Improvements**:  
  - Native Ed25519 support via `CryptoKey` for 10x faster key operations[7]  
  - Zero external dependencies to prevent supply-chain risks[4]

- **Modern JS Features**:  
  - Native BigInt support for precise u64 handling  
  - Async iterators for subscriptions[7]

## PublicKey Changes
While `PublicKey` remains a core concept for account identification[2], its implementation has shifted:

1. **Functional Interface**:  
   Instead of class methods like `PublicKey.fromBase58()`, v2 uses standalone functions:
   ```js
   import { createPublicKey } from '@solana/keys';
   const pubkey = createPublicKey(base58String);
   ```

2. **Enhanced Compatibility**:  
   Supports multiple input types natively:
   ```js
   createPublicKey(base58Str); // From string
   createPublicKey(buffer); // From Buffer
   createPublicKey(publicKey); // From existing instance[2][4]
   ```

3. **Security Improvements**:  
   Key operations now use Web Crypto API instead of custom implementations[7].

## Migration Considerations
- Backwards compatibility layer available via `@solana/web3.js-legacy`[10]
- Solana Cookbook provides side-by-side v1/v2 examples[1]
- Transaction signing uses `@solana/signers` instead of Keypair class[4][7]

Developers should reference updated documentation and leverage new modular imports to optimize bundle sizes while transitioning from legacy patterns[4][8][10].

Citations:

- 1: https://solanacompass.com/learn/Changelog/solana-changelog-nov-12-web3js-v2-skip-preflights-in-the-cli-and-simd-0191
- 2: https://solana.com/docs/clients/javascript-reference
- 3: https://www.youtube.com/watch?v=EYVumQWKU-s
- 4: https://www.panewslab.com/en/articledetails/416zlt93y3b7.html
- 5: https://www.quicknode.com/guides/solana-development/transactions/how-to-send-a-transaction-on-solana-using-javascript
- 6: https://solana.com/docs/advanced/versions
- 7: https://blog.quicknode.com/solana-web3-js-2-0-a-new-chapter-in-solana-development/
- 8: https://www.npmjs.com/package/@solana/web3.js/v/2.0.0-preview.3.20240503183512.f23c878d11c98fe8564ddf477fa7ade433101a9d
- 9: https://github.com/solana-labs/solana-web3.js/issues/1111
- 10: https://www.anza.xyz/blog/solana-web3-js-2-release

🏁 Script executed:

#!/bin/bash
# Check package.json for @solana/* dependencies
find . -name "package.json" -exec grep -l "@solana/" {} \;

# Check the actual imports from @solana packages
rg "from '@solana/" --type ts

Length of output: 925


🏁 Script executed:

#!/bin/bash
# Check the version of @solana/web3.js in package.json files
find . -name "package.json" -exec grep -A 5 '"@solana/web3.js"' {} \;

Length of output: 1130


@dev-pvl I apologize for my confusion in the previous responses. You are absolutely right about v2, and I see now that the codebase is using @solana/web3.js@^2.0.0. Looking at the v2 documentation, the functionality has been modularized and we should be using the appropriate module. The address import should be replaced with the corresponding import from @solana/addresses package.

Would you like me to help identify the correct import from the new modular packages? We can check the official migration guide or the v2 documentation for the exact package and function to use.

(_/)
(°.°)
c(,_,)


✏️ Learnings added
Learnt from: dev-pvl
PR: trezor/trezor-suite#16800
File: packages/suite/src/actions/wallet/stake/stakeFormSolanaActions.ts:1-2
Timestamp: 2025-02-06T11:19:02.325Z
Learning: In @solana/web3.js v2, 'address' is the correct import to use for handling Solana addresses, replacing the previously used PublicKey class from v1.

Learnt from: dev-pvl
PR: trezor/trezor-suite#16800
File: packages/suite/src/actions/wallet/stake/stakeFormSolanaActions.ts:1-2
Timestamp: 2025-02-06T11:19:02.325Z
Learning: @solana/web3.js v2 has moved to a modular architecture where functionality is split into separate packages like @solana/addresses, @solana/codecs, @solana/rpc, etc., replacing the monolithic imports from v1.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.


const serializedVersiondeTx = txData.tx.versionedTx.serialize();
const signedSerializedTx = Buffer.from(serializedVersiondeTx).toString('hex');
txData.tx.txShim.addSignature(address(account.descriptor), signedTx.payload.signature);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Verify the use of the 'address' function on 'account.descriptor'

At line 264, address(account.descriptor) is used to add the signature. Since the address import may be invalid or incorrect, ensure that this function correctly processes account.descriptor. If you're aiming to convert the account descriptor into a public key string, consider using new PublicKey(account.descriptor).toBase58() instead.

Apply this diff to correct the function usage:

-            txData.tx.txShim.addSignature(address(account.descriptor), signedTx.payload.signature);
+            txData.tx.txShim.addSignature(new PublicKey(account.descriptor).toBase58(), signedTx.payload.signature);
📝 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
txData.tx.txShim.addSignature(address(account.descriptor), signedTx.payload.signature);
txData.tx.txShim.addSignature(new PublicKey(account.descriptor).toBase58(), signedTx.payload.signature);

Comment on lines 137 to 140
const balances: Record<StakeStateType, string> = balanceResults.reduce(
(acc, [key, balance]) => ({ ...acc, [key]: balance }),
(acc, [status, balance]) => ({ ...acc, [status]: balance }),
{},
);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Optimize the balances reduction to avoid O(n²) complexity.

The spread operator in the reducer accumulator causes quadratic time complexity.

     const balances: Record<StakeStateType, string> = balanceResults.reduce(
-        (acc, [status, balance]) => ({ ...acc, [status]: balance }),
+        (acc, [status, balance]) => {
+            acc[status] = balance;
+            return acc;
+        },
         {},
     );
📝 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 balances: Record<StakeStateType, string> = balanceResults.reduce(
(acc, [key, balance]) => ({ ...acc, [key]: balance }),
(acc, [status, balance]) => ({ ...acc, [status]: balance }),
{},
);
const balances: Record<StakeStateType, string> = balanceResults.reduce(
- (acc, [status, balance]) => ({ ...acc, [status]: balance }),
+ (acc, [status, balance]) => {
+ acc[status] = balance;
+ return acc;
+ },
{},
);
🧰 Tools
🪛 Biome (1.9.4)

[error] 138-138: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

Copy link

🚨 Potential security issues detected. Learn more about Socket for GitHub ↗︎

To accept the risk, merge this PR and you will not be notified again.

Alert Package NoteSourceCI
Unpopular package npm/@everstake/[email protected] 🚫
Unpopular package npm/@solana-program/[email protected] 🚫

View full report↗︎

Next steps

What are unpopular packages?

This package is not very popular.

Unpopular packages may have less maintenance and contain other problems.

Take a deeper look at the dependency

Take a moment to review the security alert above. Review the linked package source code to understand the potential risk. Ensure the package is not malicious before proceeding. If you're unsure how to proceed, reach out to your security team or ask the Socket team for help at support [AT] socket [DOT] dev.

Remove the package

If you happen to install a dependency that Socket reports as Known Malware you should immediately remove it and select a different dependency. For other alert types, you may may wish to investigate alternative packages or consider if there are other ways to mitigate the specific risk posed by the dependency.

Mark a package as acceptable risk

To ignore an alert, reply with a comment starting with @SocketSecurity ignore followed by a space separated list of ecosystem/package-name@version specifiers. e.g. @SocketSecurity ignore npm/[email protected] or ignore all packages with @SocketSecurity ignore-all

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants