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/stake #46

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open

Feat/stake #46

wants to merge 20 commits into from

Conversation

ManiReddyt
Copy link
Collaborator

@ManiReddyt ManiReddyt commented Aug 7, 2024

  • stake
  • payment channels
  • utils
  • BTC wallet connectors

Summary by CodeRabbit

  • New Features

    • Introduced new packages for payment channels, staking, and wallet connectors, enhancing functionality across multiple blockchain interactions.
    • Added React components and utilities for managing Bitcoin wallet connections.
  • Bug Fixes

    • Improved workspace configuration for testing, integrating additional package paths.
  • Documentation

    • New README files added in test package directories to guide setup and usage.
  • Chores

    • Added ESLint and TypeScript configurations for improved code quality and consistency across new packages.

Copy link

coderabbitai bot commented Aug 7, 2024

Caution

Review failed

The head commit changed during the review from e88e447 to efb33f8.


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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 16

Outside diff range, codebase verification and nitpick comments (11)
packages/walletConnectors/test/src/App.tsx (2)

5-7: Remove commented-out code

The commented-out console log statement should be removed to keep the code clean.

-  // console.log('suppported wallets', SupportedBTCWallets);

1-3: Ensure correct import paths

  • The App.css file exists at the specified path.
  • The Hello component exists but is located at packages/walletConnectors/test/src/components/Hello.tsx. Update the import path accordingly.
  • The BTCWalletProvider is exported from packages/walletConnectors/src/bitcoin/index.ts. Update the import path to import { BTCWalletProvider } from './../../src/bitcoin';.

Updated import statements:

import './App.css';
import { BTCWalletProvider } from './../../src/bitcoin';
import { Hello } from './components/Hello';
Analysis chain

Ensure correct import paths

  • import './App.css'; imports the CSS file for styling.
  • import { BTCWalletProvider } from './../../src'; imports the BTCWalletProvider from the source directory.
  • import { Hello } from './components/Hello'; imports the Hello component from the components directory.

These import statements are correct, but verify that the paths are accurate and the imported modules exist.


Let's gather more information to verify the correct paths for BTCWalletProvider and Hello components.


Let's correct the commands and re-run the verification.


Let's search for the BTCWalletProvider export more broadly within the src directory.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the imported modules exist in the specified paths.

# Test: Check for the existence of the imported files. Expect: All files should exist.
test -f packages/walletConnectors/test/src/App.css && echo "App.css exists" || echo "App.css missing"
test -f packages/walletConnectors/src/index.js && echo "BTCWalletProvider exists" || echo "BTCWalletProvider missing"
test -f packages/walletConnectors/test/src/components/Hello.js && echo "Hello component exists" || echo "Hello component missing"

Length of output: 323


Script:

#!/bin/bash
# Description: Verify the existence and correct paths for BTCWalletProvider and Hello component.

# Search for BTCWalletProvider in the src directory
ast-grep --lang typescript --pattern 'export { BTCWalletProvider }' packages/walletConnectors/src

# Search for Hello component in the components directory
fd --type f --name 'Hello.*' packages/walletConnectors/test/src/components

Length of output: 427


Script:

#!/bin/bash
# Description: Verify the existence and correct paths for BTCWalletProvider and Hello component.

# Search for BTCWalletProvider in the src directory
ast-grep --lang typescript --pattern 'export { BTCWalletProvider }' packages/walletConnectors/src

# Search for any files related to Hello component in the components directory
fd 'Hello' packages/walletConnectors/test/src/components

Length of output: 212


Script:

#!/bin/bash
# Description: Verify the existence and correct paths for BTCWalletProvider.

# Search for BTCWalletProvider export in the src directory
rg 'BTCWalletProvider' packages/walletConnectors/src

Length of output: 882

packages/stake/package.json (1)

38-41: Unused Dependency: axios

The dependency axios is not used anywhere in the codebase and should be removed from the package.json file to avoid unnecessary bloat.

  • axios is listed as a dependency but is not used in any JavaScript or TypeScript files.

Please remove axios from the dependencies in packages/stake/package.json.

Analysis chain

Verify the dependencies.

Ensure that the dependencies are correctly defined and used in the codebase.


Let's modify the script to search for the usage of each dependency within JavaScript files by specifying the correct file extensions.


Let's specifically search for the usage of axios to confirm whether it is used in the codebase.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the definition and usage of dependencies.

# Test: Search for the usage of each dependency. Expect: Correct usage.
rg --type javascript '@catalogfi/utils|axios|siwe|viem'

Length of output: 92


Script:

#!/bin/bash
# Description: Verify the definition and usage of dependencies.

# Test: Search for the usage of each dependency. Expect: Correct usage.
rg '@catalogfi/utils|axios|siwe|viem' --glob '*.js' --glob '*.jsx' --glob '*.ts' --glob '*.tsx'

Length of output: 3474


Script:

#!/bin/bash
# Description: Verify the usage of the `axios` dependency.

# Test: Search for the usage of `axios`. Expect: Correct usage.
rg 'axios' --glob '*.js' --glob '*.jsx' --glob '*.ts' --glob '*.tsx'

Length of output: 68

packages/walletConnectors/vite.config.ts (1)

6-16: Consider enabling node polyfills if required.

The nodePolyfills plugin is commented out. If your package requires Node.js built-in modules, consider enabling it.

-    // nodePolyfills(),
+    nodePolyfills(),
packages/stake/src/lib/utils.ts (1)

12-49: Ensure proper error handling and logging.

The function checkAllowanceAndApprove handles errors but does not log them. Consider adding logging for better debugging.

-    return Err('Failed to approve: ' + error);
+    console.error('Failed to approve:', error);
+    return Err('Failed to approve: ' + error);
packages/walletConnectors/src/bitcoin/bitcoin.types.ts (1)

15-38: Consider adding documentation for all methods.

The interface IInjectedBitcoinProvider is well-defined, but some methods lack documentation. Consider adding JSDoc comments for better clarity.

+  /**
+   * Gets the balance of the connected account.
+   * @returns {AsyncResult<Balance, string>}
+   */
  getBalance: () => AsyncResult<Balance, string>;
+  /**
+   * Sends Bitcoin to a specified address.
+   * @param {string} toAddress - The address to send Bitcoin to.
+   * @param {number} satoshis - The amount to send in satoshis.
+   * @returns {AsyncResult<string, string>}
+   */
  sendBitcoin: (
    toAddress: string,
    satoshis: number
  ) => AsyncResult<string, string>;
packages/stake/src/lib/abi/ERC20ABI.ts (2)

52-70: Issues found in the balanceOf function ABI definition.

The balanceOf function ABI definition is missing the constant and inputs properties. According to the ERC20 standard, the balanceOf function should include:

  • constant: true
  • inputs: [{ name: '_owner', type: 'address' }]

Please update the ABI definition to include these properties.

Analysis chain

Verify the correctness of the balanceOf function ABI.

Ensure that the balanceOf function ABI definition follows the ERC20 standard.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the balanceOf function ABI.

# Test: Check the ERC20 standard for the balanceOf function. Expect: The ABI definition should match the ERC20 standard.
rg --type md 'balanceOf' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 86


Script:

#!/bin/bash
# Description: Extract the full ABI definition of the balanceOf function and verify its correctness.

# Extract the full ABI definition of the balanceOf function.
rg -A 15 'name: .balanceOf.' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 325


71-93: The extracted snippets do not show the inputs field for the transfer function, which is a crucial part of the ERC20 standard. This suggests that the inputs might either be missing or incorrectly defined.

The transfer function ABI definition is missing the required inputs field.

  • The transfer function should include two inputs: _to (address) and _value (uint256).

Please update the ABI definition to include these inputs.

Analysis chain

Verify the correctness of the transfer function ABI.

Ensure that the transfer function ABI definition follows the ERC20 standard.


Let's extract the ABI definition of the transfer function from the ERC20ABI.ts file and compare it with the ERC20 standard to ensure its correctness.


Let's perform another search to capture the complete definition of the transfer function, including the inputs field.


Let's perform a broader search to ensure we capture the full definition of the transfer function, including the inputs field.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the transfer function ABI.

# Test: Check the ERC20 standard for the transfer function. Expect: The ABI definition should match the ERC20 standard.
rg --type md 'transfer' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 110


Script:

#!/bin/bash
# Extract the ABI definition of the transfer function from the ERC20ABI.ts file
rg -A 15 'name: .transfer.' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 581


Script:

#!/bin/bash
# Extract the complete ABI definition of the transfer function from the ERC20ABI.ts file
rg -A 20 'name: .transfer.' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 753


Script:

#!/bin/bash
# Extract the complete ABI definition of the transfer function from the ERC20ABI.ts file with more context lines
rg -A 25 'name: .transfer.' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 889

packages/walletConnectors/src/bitcoin/btcWalletsProvider.tsx (2)

1-7: Remove unused imports.

The ReactNode import is not used in this file.

-  ReactNode,

123-129: Improve error message in useBitcoinWallet hook.

The error message can be improved for better clarity.

    throw new Error('useBitcoinWallet must be used within a BTCWalletProvider');
packages/paymentChannel/src/lib/utils.ts (1)

15-20: Ensure consistent error messages.

The error message should be consistent with the rest of the codebase.

  return Err('Provider not found in the signer');
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 55989c9 and efb33f8.

Files ignored due to path filters (85)
  • docs/docs/cookbook/images/basic_setup_swapper.png is excluded by !**/*.png
  • docs/docs/cookbook/images/final_dapp.png is excluded by !**/*.png
  • docs/docs/cookbook/images/layout.png is excluded by !**/*.png
  • docs/docs/cookbook/images/order_component.png is excluded by !**/*.png
  • docs/docs/cookbook/images/swap.png is excluded by !**/*.png
  • docs/docs/cookbook/images/swapper_createbitcoinwallet.png is excluded by !**/*.png
  • docs/docs/cookbook/images/swapper_createevmwallet.png is excluded by !**/*.png
  • docs/docs/cookbook/images/swapper_getdetails.png is excluded by !**/*.png
  • docs/docs/cookbook/images/swapper_swapwbtctobtc.png is excluded by !**/*.png
  • docs/docs/developers/images/alice_create_order.png is excluded by !**/*.png
  • docs/docs/developers/images/initiating.png is excluded by !**/*.png
  • docs/docs/developers/images/order_matching.png is excluded by !**/*.png
  • docs/docs/developers/images/redeeming.png is excluded by !**/*.png
  • docs/docs/developers/images/refunding.png is excluded by !**/*.png
  • docs/docs/home/images/Token_economics.png is excluded by !**/*.png
  • docs/docs/home/images/alt_colorway_1.png is excluded by !**/*.png
  • docs/docs/home/images/alt_colorway_2.png is excluded by !**/*.png
  • docs/docs/home/images/garden_horizontal_darkgrey.png is excluded by !**/*.png
  • docs/docs/home/images/garden_horizontal_darkgrey.svg is excluded by !**/*.svg
  • docs/docs/home/images/garden_horizontal_white.png is excluded by !**/*.png
  • docs/docs/home/images/garden_horizontal_white.svg is excluded by !**/*.svg
  • docs/docs/home/images/garden_logomark.png is excluded by !**/*.png
  • docs/docs/home/images/garden_logomark.svg is excluded by !**/*.svg
  • docs/docs/home/images/garden_logos.zip is excluded by !**/*.zip
  • docs/docs/home/images/guide-btc-wbtc-1.png is excluded by !**/*.png
  • docs/docs/home/images/guide-btc-wbtc-10.png is excluded by !**/*.png
  • docs/docs/home/images/guide-btc-wbtc-11.png is excluded by !**/*.png
  • docs/docs/home/images/guide-btc-wbtc-12.png is excluded by !**/*.png
  • docs/docs/home/images/guide-btc-wbtc-2.png is excluded by !**/*.png
  • docs/docs/home/images/guide-btc-wbtc-3.png is excluded by !**/*.png
  • docs/docs/home/images/guide-btc-wbtc-4.png is excluded by !**/*.png
  • docs/docs/home/images/guide-btc-wbtc-5.png is excluded by !**/*.png
  • docs/docs/home/images/guide-btc-wbtc-6.png is excluded by !**/*.png
  • docs/docs/home/images/guide-btc-wbtc-7.png is excluded by !**/*.png
  • docs/docs/home/images/guide-btc-wbtc-8.png is excluded by !**/*.png
  • docs/docs/home/images/guide-btc-wbtc-9.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-1.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-10.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-11.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-12.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-2.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-3.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-4.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-5.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-6.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-7.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-8.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-btc-9.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-wbtc-1.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-wbtc-10.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-wbtc-11.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-wbtc-2.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-wbtc-3.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-wbtc-4.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-wbtc-5.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-wbtc-6.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-wbtc-7.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-wbtc-8.png is excluded by !**/*.png
  • docs/docs/home/images/guide-wbtc-wbtc-9.png is excluded by !**/*.png
  • docs/docs/home/images/htlc1.png is excluded by !**/*.png
  • docs/docs/home/images/main_colorway.png is excluded by !**/*.png
  • docs/docs/home/images/mutiplier.png is excluded by !**/*.png
  • docs/docs/home/images/s1_vol.png is excluded by !**/*.png
  • docs/docs/home/images/s2-vol.jpeg is excluded by !**/*.jpeg
  • docs/docs/home/images/seed-1.png is excluded by !**/*.png
  • docs/docs/home/images/seed-2.png is excluded by !**/*.png
  • docs/docs/home/images/seed-3.png is excluded by !**/*.png
  • docs/docs/home/images/seed-4.png is excluded by !**/*.png
  • docs/docs/home/images/seed-5.png is excluded by !**/*.png
  • docs/static/img/alice_create_order.png is excluded by !**/*.png
  • docs/static/img/catalog-white.svg is excluded by !**/*.svg
  • docs/static/img/catalog.svg is excluded by !**/*.svg
  • docs/static/img/flower.svg is excluded by !**/*.svg
  • docs/static/img/garden-docs-white.svg is excluded by !**/*.svg
  • docs/static/img/garden-docs.svg is excluded by !**/*.svg
  • docs/static/img/garden-white.svg is excluded by !**/*.svg
  • docs/static/img/garden.svg is excluded by !**/*.svg
  • docs/static/img/init.png is excluded by !**/*.png
  • docs/static/img/match.png is excluded by !**/*.png
  • docs/static/img/redeem.png is excluded by !**/*.png
  • docs/static/img/refund.png is excluded by !**/*.png
  • packages/walletConnectors/test/public/vite.svg is excluded by !**/*.svg
  • packages/walletConnectors/test/src/assets/react.svg is excluded by !**/*.svg
  • packages/walletConnectors/test/yarn.lock is excluded by !**/yarn.lock, !**/*.lock
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
Files selected for processing (83)
  • .github/workflows/publish.yml (1 hunks)
  • .gitignore (1 hunks)
  • .vscode/settings.json (1 hunks)
  • .yarnrc.yml (1 hunks)
  • package.json (1 hunks)
  • packages/orderbook/package.json (2 hunks)
  • packages/orderbook/src/lib/orderbook.spec.ts (1 hunks)
  • packages/orderbook/src/lib/orderbook.ts (2 hunks)
  • packages/orderbook/src/lib/orderbook.types.ts (1 hunks)
  • packages/paymentChannel/package.json (1 hunks)
  • packages/paymentChannel/src/index.ts (1 hunks)
  • packages/paymentChannel/src/lib/abi/atomicSwap.ts (1 hunks)
  • packages/paymentChannel/src/lib/constants.ts (1 hunks)
  • packages/paymentChannel/src/lib/index.ts (1 hunks)
  • packages/paymentChannel/src/lib/paymentChannel.spec.ts (1 hunks)
  • packages/paymentChannel/src/lib/paymentChannel.types.ts (1 hunks)
  • packages/paymentChannel/src/lib/utils.spec.ts (1 hunks)
  • packages/paymentChannel/src/lib/utils.ts (1 hunks)
  • packages/paymentChannel/tsconfig.json (1 hunks)
  • packages/paymentChannel/tsconfig.lib.json (1 hunks)
  • packages/paymentChannel/tsconfig.spec.json (1 hunks)
  • packages/paymentChannel/vite.config.ts (1 hunks)
  • packages/stake/package.json (1 hunks)
  • packages/stake/src/index.ts (1 hunks)
  • packages/stake/src/lib/abi/ERC20ABI.ts (1 hunks)
  • packages/stake/src/lib/abi/flowerABI.ts (1 hunks)
  • packages/stake/src/lib/abi/stakeABI.ts (1 hunks)
  • packages/stake/src/lib/constants.ts (1 hunks)
  • packages/stake/src/lib/feehub.spec.ts (1 hunks)
  • packages/stake/src/lib/feehub.ts (1 hunks)
  • packages/stake/src/lib/stake.spec.ts (1 hunks)
  • packages/stake/src/lib/stake.ts (1 hunks)
  • packages/stake/src/lib/stake.types.ts (1 hunks)
  • packages/stake/src/lib/utils.ts (1 hunks)
  • packages/stake/tsconfig.json (1 hunks)
  • packages/stake/tsconfig.lib.json (1 hunks)
  • packages/stake/tsconfig.spec.json (1 hunks)
  • packages/stake/vite.config.ts (1 hunks)
  • packages/utils/package.json (1 hunks)
  • packages/utils/src/index.ts (1 hunks)
  • packages/utils/src/lib/auth/auth.types.ts (1 hunks)
  • packages/utils/src/lib/auth/siwe.ts (1 hunks)
  • packages/utils/src/lib/url/Url.ts (1 hunks)
  • packages/utils/tsconfig.json (1 hunks)
  • packages/utils/tsconfig.lib.json (1 hunks)
  • packages/utils/tsconfig.spec.json (1 hunks)
  • packages/utils/vite.config.ts (1 hunks)
  • packages/walletConnectors/package.json (1 hunks)
  • packages/walletConnectors/src/bitcoin/bitcoin.types.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/btcWalletsProvider.tsx (1 hunks)
  • packages/walletConnectors/src/bitcoin/constants.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/index.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/providers/okx/okx.types.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/providers/okx/provider.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/providers/unisat/provider.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/providers/unisat/unisat.types.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/providers/xdefi/provider.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/providers/xdefi/xdefi.types.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/providers/xverse/provider.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/providers/xverse/xverse.types.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/utils.spec.ts (1 hunks)
  • packages/walletConnectors/src/bitcoin/utils.ts (1 hunks)
  • packages/walletConnectors/src/index.ts (1 hunks)
  • packages/walletConnectors/test/.eslintrc.cjs (1 hunks)
  • packages/walletConnectors/test/.gitignore (1 hunks)
  • packages/walletConnectors/test/README.md (1 hunks)
  • packages/walletConnectors/test/index.html (1 hunks)
  • packages/walletConnectors/test/package.json (1 hunks)
  • packages/walletConnectors/test/src/App.css (1 hunks)
  • packages/walletConnectors/test/src/App.tsx (1 hunks)
  • packages/walletConnectors/test/src/components/Hello.tsx (1 hunks)
  • packages/walletConnectors/test/src/index.css (1 hunks)
  • packages/walletConnectors/test/src/main.tsx (1 hunks)
  • packages/walletConnectors/test/src/vite-env.d.ts (1 hunks)
  • packages/walletConnectors/test/tsconfig.app.json (1 hunks)
  • packages/walletConnectors/test/tsconfig.json (1 hunks)
  • packages/walletConnectors/test/tsconfig.node.json (1 hunks)
  • packages/walletConnectors/test/vite.config.ts (1 hunks)
  • packages/walletConnectors/tsconfig.json (1 hunks)
  • packages/walletConnectors/tsconfig.lib.json (1 hunks)
  • packages/walletConnectors/tsconfig.spec.json (1 hunks)
  • packages/walletConnectors/vite.config.ts (1 hunks)
  • vitest.workspace.js (1 hunks)
Files skipped from review due to trivial changes (32)
  • .github/workflows/publish.yml
  • .gitignore
  • .vscode/settings.json
  • packages/orderbook/src/lib/orderbook.spec.ts
  • packages/orderbook/src/lib/orderbook.types.ts
  • packages/paymentChannel/src/index.ts
  • packages/paymentChannel/tsconfig.json
  • packages/paymentChannel/tsconfig.lib.json
  • packages/stake/src/index.ts
  • packages/stake/tsconfig.json
  • packages/stake/tsconfig.spec.json
  • packages/stake/vite.config.ts
  • packages/utils/package.json
  • packages/utils/src/index.ts
  • packages/utils/src/lib/url/Url.ts
  • packages/utils/tsconfig.lib.json
  • packages/utils/tsconfig.spec.json
  • packages/walletConnectors/src/bitcoin/constants.ts
  • packages/walletConnectors/src/index.ts
  • packages/walletConnectors/test/.eslintrc.cjs
  • packages/walletConnectors/test/.gitignore
  • packages/walletConnectors/test/README.md
  • packages/walletConnectors/test/index.html
  • packages/walletConnectors/test/package.json
  • packages/walletConnectors/test/src/App.css
  • packages/walletConnectors/test/src/index.css
  • packages/walletConnectors/test/src/main.tsx
  • packages/walletConnectors/test/src/vite-env.d.ts
  • packages/walletConnectors/test/tsconfig.json
  • packages/walletConnectors/test/vite.config.ts
  • packages/walletConnectors/tsconfig.json
  • packages/walletConnectors/tsconfig.lib.json
Additional context used
Biome
packages/walletConnectors/test/tsconfig.app.json

[error] 11-11: JSON standard does not allow comments.

(parse)


[error] 12-12: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 12-12: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 12-12: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 12-12: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 13-13: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 13-13: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 13-13: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 13-13: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 14-14: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 14-14: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 14-14: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 14-14: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 15-15: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 15-15: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 15-15: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 15-15: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 16-16: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 16-16: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 16-16: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)

packages/walletConnectors/src/bitcoin/btcWalletsProvider.tsx

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)


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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

packages/orderbook/src/lib/orderbook.ts

[error] 161-161: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)


[error] 165-165: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

(lint/suspicious/noGlobalIsNan)

packages/paymentChannel/src/lib/index.ts

[error] 278-278: Don't use 'BigInt' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'bigint' instead

(lint/complexity/noBannedTypes)

Additional comments not posted (187)
packages/walletConnectors/src/bitcoin/index.ts (3)

2-2: Verify the export of SupportedWallets.

Ensure that SupportedWallets is correctly defined and exported in ./constants.

Verification successful

Verified the export of SupportedWallets.

The SupportedWallets is correctly defined and exported in ./constants.

  • ./packages/walletConnectors/src/bitcoin/constants.ts: export const SupportedWallets = {
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the presence of `SupportedWallets` in `./constants`.

# Test: Search for the definition and export. Expect: Definition and export of `SupportedWallets`.
rg --type ts 'SupportedWallets' ./packages/walletConnectors/src/bitcoin/constants.ts

Length of output: 118


3-3: Verify the export of getBalance.

Ensure that getBalance is correctly defined and exported in ./utils.

Verification successful

Verified: The getBalance function is correctly defined and exported in ./utils.

  • getBalance is defined as export const getBalance = async ( in ./utils.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the presence of `getBalance` in `./utils`.

# Test: Search for the definition and export. Expect: Definition and export of `getBalance`.
rg --type ts 'getBalance' ./packages/walletConnectors/src/bitcoin/utils.ts

Length of output: 108


1-1: Verify the export of BTCWalletProvider and useBitcoinWallet.

Ensure that BTCWalletProvider and useBitcoinWallet are correctly defined and exported in ./btcWalletsProvider.

Verification successful

The file extension should be .tsx instead of .ts.

The BTCWalletProvider and useBitcoinWallet are correctly defined and exported in btcWalletsProvider.tsx. The export statement in index.ts is accurate but ensure that the file extension is correctly referenced.

  • BTCWalletProvider definition: packages/walletConnectors/src/bitcoin/btcWalletsProvider.tsx
  • useBitcoinWallet definition: packages/walletConnectors/src/bitcoin/btcWalletsProvider.tsx
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the presence of `BTCWalletProvider` and `useBitcoinWallet` in `./btcWalletsProvider`.

# Test: Search for the definitions and exports. Expect: Definitions and exports of `BTCWalletProvider` and `useBitcoinWallet`.
rg --type ts 'BTCWalletProvider|useBitcoinWallet' ./packages/walletConnectors/src/bitcoin/btcWalletsProvider.ts

Length of output: 215


Script:

#!/bin/bash
# Description: Search for definitions of `BTCWalletProvider` and `useBitcoinWallet` across the entire repository.

# Test: Locate the files containing definitions of `BTCWalletProvider` and `useBitcoinWallet`.
rg --type ts 'BTCWalletProvider|useBitcoinWallet'

Length of output: 982

packages/walletConnectors/src/bitcoin/providers/xverse/xverse.types.ts (1)

1-10: LGTM! Interface definition is clear and follows best practices.

The XVerseBitcoinProvider interface is well-defined with a request method that has appropriate parameters and return type.

packages/paymentChannel/tsconfig.spec.json (1)

1-9: LGTM! TypeScript configuration is clear and follows best practices.

The TypeScript configuration for tests is well-defined and extends the main tsconfig.json with appropriate compilerOptions and file inclusions.

packages/walletConnectors/tsconfig.spec.json (1)

1-9: LGTM! Configuration for TypeScript tests is correctly set up.

The tsconfig.spec.json file extends the base tsconfig.json and sets appropriate compiler options for test files. The configuration appears to be correct and follows best practices.

.yarnrc.yml (1)

12-13: LGTM! Yarn configuration is correctly set up.

The addition of the yarnPath property specifying the path to the Yarn binary (version 4.3.1) enhances the project's dependency management by ensuring consistency across different environments.

packages/utils/src/lib/auth/auth.types.ts (3)

1-2: LGTM! Import statement is correct.

The import statement correctly imports IStore from the specified path.


3-6: LGTM! Type definition for SiweOpts is correct.

The type definition for SiweOpts includes optional properties domain and store, which are appropriately typed.


8-11: LGTM! Interface definition for IAuth is correct.

The interface IAuth defines methods for getting and verifying tokens, with appropriate return types.

packages/stake/tsconfig.lib.json (3)

1-2: Extending the base configuration

The file extends the base TypeScript configuration from ./tsconfig.json, which is a good practice to maintain consistency across different configurations.


3-8: Compiler options are well-configured

  • target: "ESNext" ensures the latest ECMAScript features are used.
  • outDir: "../dist/out-tsc" specifies the output directory for compiled files.
  • declaration: true generates declaration files, useful for TypeScript projects.
  • types: ["node", "vite/client"] includes type definitions for Node.js and Vite.

These settings are appropriate for a modern TypeScript project.


9-10: Include and exclude patterns are appropriate

  • include: ["src/**/*.ts", "src/**/*.json"] ensures all TypeScript and JSON files in the src directory are included.
  • exclude: ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"] excludes test files and configuration files from the build process, which is a good practice.

These patterns are well-chosen for the project.

packages/walletConnectors/test/src/App.tsx (2)

8-12: Functional component structure is correct

The App component correctly uses the BTCWalletProvider to wrap the Hello component. This ensures that the Hello component has access to the context provided by BTCWalletProvider.


15-15: Exporting the component

The App component is correctly exported as the default export.

vitest.workspace.js (2)

1-1: Import statement is correct

The defineWorkspace function is correctly imported from vitest/config.


4-10: New package paths added to the workspace configuration

The new package paths for paymentChannel, stake, and walletConnectors have been correctly added to the workspace configuration. This ensures that these packages are included in the testing and development workflow.

The formatting with semicolons is consistent and improves readability.

packages/walletConnectors/test/tsconfig.node.json (1)

1-13: Review TypeScript Configuration

The tsconfig.node.json file appears to be correctly configured for the project. Here are some points to consider:

  • Composite Projects: The composite option is set to true, which is useful for incremental builds in a multi-package project.
  • Build Info File: The tsBuildInfoFile is stored in a temporary directory, which is a good practice.
  • Skip Library Check: The skipLibCheck option is set to true, which can speed up compilation by skipping type checking of all declaration files.
  • Module and Module Resolution: The module is set to ESNext, and moduleResolution is set to bundler, which are appropriate for modern JavaScript development.
  • Allow Synthetic Default Imports: The allowSyntheticDefaultImports is set to true, which is useful for interoperability with CommonJS modules.
  • Strict Mode: The strict option is set to true, which enables all strict type-checking options.
  • No Emit: The noEmit option is set to true, which means no output files will be generated.

The include array specifies that only the vite.config.ts file is included in the project, which is appropriate for a configuration file.

Overall, the configuration looks good.

packages/paymentChannel/src/lib/constants.ts (1)

1-14: Review Constants and Configuration

The constants.ts file defines several constants and configuration objects. Here are some points to consider:

  • Supported Chains: The SupportedChains array includes the chain IDs 42161 and 11155111, which should be verified to ensure they are correct.
  • ETH Blocks Per Day: The ETH_BLOCKS_PER_DAY constant is set to 7200, which is accurate based on the average block time of Ethereum.
  • Version: The VERSION constant is set to '1', which is straightforward.
  • Atomic Swap Configuration: The AtomicSwapConfig object defines configurations for two chains:
    • Chain 42161 with FEE_HUB and GARDEN_HTLC_ADDR addresses.
    • Chain 11155111 with FEE_HUB and GARDEN_HTLC_ADDR addresses.

It is important to verify that the addresses used in the AtomicSwapConfig are correct and belong to the intended contracts.

Overall, the constants and configuration objects are well-defined.

packages/walletConnectors/src/bitcoin/providers/xdefi/xdefi.types.ts (1)

1-15: Review TypeScript Types and Interface

The xdefi.types.ts file defines types and interfaces for the xdefi Bitcoin provider. Here are some points to consider:

  • Import Statement: The Network type is imported from ../../bitcoin.types, which should be verified to ensure it is correctly defined.
  • Request Function Type: The RequestFunction type is defined as a function that takes an object with method and params properties and a callback, and returns a Promise<any>. This type definition looks appropriate.
  • XdefiBitcoinProvider Interface: The interface defines several properties and methods:
    • request: A RequestFunction.
    • network: A Network.
    • requestAccounts: A function that returns a Promise<string[]>.
    • getAccounts: A function that returns a Promise<string[]>.
    • on: A function that registers an event listener.
    • off: A function that unregisters an event listener.

The interface is well-defined and covers the necessary functionalities for the xdefi Bitcoin provider.

Overall, the types and interfaces are correctly defined.

packages/stake/src/lib/abi/flowerABI.ts (2)

3-10: LGTM! The changeVote function definition is correct.

The structure and types of the inputs and outputs are appropriate for an ABI.


13-17: LGTM! The mint function definition is correct.

The structure and types of the input and outputs are appropriate for an ABI.

packages/stake/src/lib/feehub.spec.ts (2)

9-12: LGTM! The test case for getStakingRewards is correct.

The test case correctly checks the expected behavior of the getStakingRewards method.


13-16: LGTM! The test case for getStakeApy is correct.

The test case correctly checks the expected behavior of the getStakeApy method.

packages/walletConnectors/src/bitcoin/providers/unisat/unisat.types.ts (9)

2-2: LGTM! The _selectedAddress property definition is correct.

The property correctly represents the selected address as a string.


3-3: LGTM! The getAccounts method definition is correct.

The method correctly returns a promise that resolves to an array of strings.


4-4: LGTM! The requestAccounts method definition is correct.

The method correctly returns a promise that resolves to an array of strings.


5-5: LGTM! The sendBitcoin method definition is correct.

The method correctly takes two parameters and returns a promise that resolves to a string.


6-10: LGTM! The getBalance method definition is correct.

The method correctly returns a promise that resolves to an object with three properties of type number.


11-11: LGTM! The getNetwork method definition is correct.

The method correctly returns a promise that resolves to a string.


12-12: LGTM! The getPublicKey method definition is correct.

The method correctly returns a promise that resolves to a string.


13-13: LGTM! The on method definition is correct.

The method correctly takes two parameters and returns void.


14-14: LGTM! The removeListener method definition is correct.

The method correctly takes two parameters and returns void.

packages/walletConnectors/src/bitcoin/utils.spec.ts (3)

1-3: LGTM! Imports are correct and necessary.

The import statements are appropriate for the functionality of the tests.


5-5: LGTM! Correct usage of describe block.

The describe block is appropriately used to group related tests for the getBalance function.


6-17: LGTM! Correct usage of test block and assertions.

The test block is appropriately used to test the getBalance function. The assertions ensure that the returned balance has the expected structure and types.

packages/utils/tsconfig.json (1)

1-26: LGTM! TypeScript configuration is appropriate.

The TypeScript configuration extends the base configuration and includes specific compiler options, files, include, exclude, and references. The settings ensure strict type checking and consistent casing.

packages/walletConnectors/test/tsconfig.app.json (1)

1-27: LGTM! TypeScript configuration is appropriate.

The TypeScript configuration includes compiler options and includes the src directory. The settings ensure strict type checking and consistent casing.

Tools
Biome

[error] 11-11: JSON standard does not allow comments.

(parse)


[error] 12-12: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 12-12: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 12-12: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 12-12: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 13-13: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 13-13: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 13-13: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 13-13: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 14-14: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 14-14: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 14-14: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 14-14: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 15-15: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 15-15: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 15-15: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 15-15: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 16-16: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 16-16: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)


[error] 16-16: End of file expected

Use an array for a sequence of values: [1, 2]

(parse)

packages/walletConnectors/src/bitcoin/providers/okx/okx.types.ts (2)

3-26: LGTM!

The interface OKXBitcoinProvider is well-defined and covers necessary methods for Bitcoin transactions and account management.


1-1: Verify the SelectedAccount type usage.

Ensure that the SelectedAccount type is correctly defined and used in the codebase.

Verification successful

The SelectedAccount type is correctly defined and used.

  • The SelectedAccount type is defined in packages/walletConnectors/src/bitcoin/bitcoin.types.ts with the properties address and publicKey, both of which are strings.
  • The type is imported and used in packages/walletConnectors/src/bitcoin/providers/okx/okx.types.ts.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the definition and usage of `SelectedAccount` type.

# Test: Search for the `SelectedAccount` type definition. Expect: Correct type definition.
rg --type typescript 'type SelectedAccount' -A 5

Length of output: 85


Script:

#!/bin/bash
# Description: Verify the definition and usage of `SelectedAccount` type.

# Test: Search for the `SelectedAccount` type definition.
ast-grep --lang typescript --pattern 'type SelectedAccount { $$$ }'

# Test: Search for the usage of `SelectedAccount` type.
rg 'SelectedAccount'

Length of output: 949


Script:

#!/bin/bash
# Description: Verify the definition of `SelectedAccount` type.

# Print the relevant lines from the file where `SelectedAccount` is defined.
rg 'export type SelectedAccount' -A 5 packages/walletConnectors/src/bitcoin/bitcoin.types.ts

Length of output: 203

packages/stake/package.json (1)

1-43: LGTM!

The package configuration for staking functionalities is well-defined and includes necessary scripts, dependencies, and publish settings.

packages/walletConnectors/package.json (2)

1-43: LGTM!

The package configuration for wallet connectors is well-defined and includes necessary scripts, dependencies, and publish settings.


38-41: Verify the dependencies.

Ensure that the dependencies are correctly defined and used in the codebase.

Verification successful

Dependencies are correctly defined and used in the codebase.

The dependencies @catalogfi/utils, @gardenfi/utils, and react are properly defined in the package.json file and are used across multiple source files.

  • @catalogfi/utils is used in various files such as provider.ts, btcWalletsProvider.tsx, and others.
  • @gardenfi/utils is used in files like stake.ts, feehub.ts, and others.
  • react is referenced in configuration files like tsconfig.lib.json and tsconfig.json, and in source files such as btcWalletsProvider.tsx.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the definition and usage of dependencies.

# Test: Search for the usage of each dependency. Expect: Correct usage.
rg --type javascript '@catalogfi/utils|@gardenfi/utils|react'

Length of output: 98


Script:

#!/bin/bash
# Description: Verify the definition and usage of dependencies.

# Test: Search for the usage of each dependency. Expect: Correct usage.
rg '@catalogfi/utils|@gardenfi/utils|react'

Length of output: 6128

package.json (2)

17-18: Verify the correctness and necessity of new workspaces.

The additions of packages/walletConnectors/test and packages/utils to the workspaces section should be verified to ensure they are correct and necessary for the project.


Line range hint 6-6:
Verify the alternative approach for documentation management.

The start:docs script has been removed. Ensure that there is an alternative approach to managing documentation.

packages/stake/src/lib/feehub.ts (2)

14-23: Verify the correctness of error handling in getStakingRewards.

Ensure that the error handling in the getStakingRewards method correctly captures and returns meaningful error messages.


25-34: Verify the correctness of error handling in getStakeApy.

Ensure that the error handling in the getStakeApy method correctly captures and returns meaningful error messages.

packages/paymentChannel/package.json (4)

5-8: Verify the correctness and necessity of scripts.

Ensure that the build, test, and dev scripts are correctly defined and necessary for the @gardenfi/paymentchannel package.


10-12: Verify the correctness of the files section.

Ensure that the dist directory is the correct output directory for the @gardenfi/paymentchannel package.


13-15: Verify the correctness of main, module, and typings fields.

Ensure that the main, module, and typings fields correctly point to the compiled output of the @gardenfi/paymentchannel package.


37-43: Verify the necessity and correctness of dependencies.

Ensure that the listed dependencies are necessary and correctly versioned for the @gardenfi/paymentchannel package.

packages/orderbook/package.json (3)

16-18: LGTM! The relocation of the files section is approved.

The files section retains its original content and the relocation should not affect the functionality.


19-23: LGTM! The relocation of the scripts section is approved.

The scripts section retains its original content and the relocation should not affect the functionality.


28-37: LGTM! The addition of the new dependency @gardenfi/utils is approved.

The new dependency is correctly added and does not conflict with existing dependencies.

packages/utils/vite.config.ts (3)

1-4: LGTM! The import statements are correct and necessary for the configuration.

The import statements include Vite configuration and DTS plugin, which are essential for the configuration.


9-16: LGTM! The DTS plugin configuration is approved.

The DTS plugin is correctly configured with the necessary options.


24-44: LGTM! The build configuration is approved.

The build configuration includes commonjs options, library entry point, and rollup options, which are correctly set up and align with the project requirements.

packages/paymentChannel/vite.config.ts (3)

1-4: LGTM! The import statements are correct and necessary for the configuration.

The import statements include Vite configuration and DTS plugin, which are essential for the configuration.


9-16: LGTM! The DTS plugin configuration is approved.

The DTS plugin is correctly configured with the necessary options.


24-44: LGTM! The build configuration is approved.

The build configuration includes commonjs options, library entry point, and rollup options, which are correctly set up and align with the project requirements.

packages/walletConnectors/vite.config.ts (3)

1-4: Ensure the necessity of /// <reference types='vitest' />.

If Vitest is not used for testing in this package, consider removing this reference.


24-43: Ensure commonjsOptions.include is correctly configured.

The include array in commonjsOptions is empty. Ensure that this is intentional and that no CommonJS modules need to be included.


18-21: Verify the necessity of worker configuration.

If your package uses workers, consider uncommenting and configuring the worker section.

packages/stake/src/lib/utils.ts (1)

4-7: LGTM!

The function convertTo0xString is correct and follows best practices.

packages/walletConnectors/src/bitcoin/bitcoin.types.ts (4)

3-7: LGTM!

The type definition for Balance is correct and follows best practices.


9-13: LGTM!

The type definition for Connect is correct and follows best practices.


40-48: LGTM!

The type definitions for Network and SelectedAccount are correct and follow best practices.


50-54: LGTM!

The interface definition for BitcoinWallet is correct and follows best practices.

packages/stake/src/lib/constants.ts (4)

4-4: LGTM!

The constant STAKING_CHAIN is defined correctly.


6-12: LGTM!

The constant DURATION_MAP is defined correctly and uses MaxUint256 for the infinite duration.


14-17: LGTM!

The constants SEED_FOR_MINTING_NFT, MIN_STAKE, ETH_BLOCKS_PER_DAY, and INFINITE are defined correctly.


18-43: LGTM!

The constant STAKING_CONFIG is defined correctly and includes all necessary configurations for each chain.

packages/stake/src/lib/stake.types.ts (6)

4-14: LGTM!

The type Stake is defined correctly and includes all necessary fields.


16-26: LGTM!

The type Config is defined correctly and includes all necessary fields.


28-32: LGTM!

The type GlobalStakingData is defined correctly and includes all necessary fields.


34-36: LGTM!

The type StakeRewards is defined correctly and includes all necessary fields.


38-43: LGTM!

The type StakeApy is defined correctly and includes all necessary fields.


47-77: LGTM!

The interfaces IStakeProvider and IFeehub are defined correctly and include all necessary methods.

packages/paymentChannel/src/lib/utils.spec.ts (1)

30-39: LGTM!

The test case getL1BlockNumber is defined correctly.

packages/walletConnectors/src/bitcoin/utils.ts (4)

4-13: Verify the correctness of explorer URLs.

Ensure that the URLs for Mempool and Blockstream explorers are correct and accessible.

Verification successful

The explorer URLs are correct and accessible.

The URLs for Mempool and Blockstream explorers have been verified and are functioning as expected.

  • https://mempool.space/testnet
  • https://blockstream.info/testnet
  • https://mempool.space
  • https://blockstream.info
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of explorer URLs.

# Test: Check if the URLs are accessible. Expect: All URLs should be accessible.
curl -I https://mempool.space/testnet
curl -I https://blockstream.info/testnet
curl -I https://mempool.space
curl -I https://blockstream.info

Length of output: 4219


1-2: Ensure all imported modules are used.

Verify that all imported modules from @catalogfi/utils and ./bitcoin.types are necessary and used in the code.

Verification successful

All imported modules are used.

The verification shows that all imported modules from @catalogfi/utils and ./bitcoin.types are used within the packages/walletConnectors/src/bitcoin/utils.ts file.

  • AsyncResult is used in the function return type.
  • Err is used in error handling.
  • Fetcher is used to fetch data.
  • Ok is used to return a successful result.
  • Balance is used in the type definition.
  • Network is used in the type definition.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all imported modules are used in the code.

# Test: Search for the usage of imported modules. Expect: All imported modules should be used in the code.
rg --type ts '@catalogfi/utils' packages/walletConnectors/src/bitcoin/utils.ts
rg --type ts './bitcoin.types' packages/walletConnectors/src/bitcoin/utils.ts

Length of output: 274


Script:

#!/bin/bash
# Description: Verify the usage of each imported module in the code.

# Test: Search for the usage of each imported module. Expect: All imported modules should be used in the code.
rg 'AsyncResult' packages/walletConnectors/src/bitcoin/utils.ts
rg 'Err' packages/walletConnectors/src/bitcoin/utils.ts
rg 'Fetcher' packages/walletConnectors/src/bitcoin/utils.ts
rg 'Ok' packages/walletConnectors/src/bitcoin/utils.ts
rg 'Balance' packages/walletConnectors/src/bitcoin/utils.ts
rg 'Network' packages/walletConnectors/src/bitcoin/utils.ts

Length of output: 1427


43-50: Ensure Fetcher.getWithFallback handles retries correctly.

Verify that the Fetcher.getWithFallback function handles retries as expected and consider logging retry attempts for better debugging.


15-31: Ensure the BalanceResponse type covers all necessary fields.

Verify that the BalanceResponse type definition accurately reflects the response structure from the explorers.

Verification successful

To accurately verify the BalanceResponse type definition, we need to use valid Bitcoin addresses. Let's generate a new script with valid addresses to fetch the correct response structure from the explorers.


To accurately verify the BalanceResponse type definition, we need to use different valid Bitcoin addresses that are correctly recognized by the explorers. Let's generate a new script with different known valid addresses.


The BalanceResponse type definition accurately reflects the response structure from the explorers.

The structure of the responses from both Blockstream and Mempool explorers matches the BalanceResponse type definition, confirming its accuracy.

  • chain_stats and mempool_stats fields are present and contain the expected subfields.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the BalanceResponse type definition accurately reflects the response structure from the explorers.

# Test: Check the response structure from the explorers. Expect: The response structure should match the BalanceResponse type definition.
curl https://blockstream.info/testnet/api/address/someaddress
curl https://mempool.space/testnet/api/address/someaddress
curl https://blockstream.info/api/address/someaddress
curl https://mempool.space/api/address/someaddress

Length of output: 2204


Script:

#!/bin/bash
# Description: Verify that the BalanceResponse type definition accurately reflects the response structure from the explorers using valid Bitcoin addresses.

# Using known valid Bitcoin testnet and mainnet addresses
VALID_TESTNET_ADDRESS="tb1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh"
VALID_MAINNET_ADDRESS="bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kygt080"

# Fetching the response structure from the explorers
curl https://blockstream.info/testnet/api/address/$VALID_TESTNET_ADDRESS
curl https://mempool.space/testnet/api/address/$VALID_TESTNET_ADDRESS
curl https://blockstream.info/api/address/$VALID_MAINNET_ADDRESS
curl https://mempool.space/api/address/$VALID_MAINNET_ADDRESS

Length of output: 2494


Script:

#!/bin/bash
# Description: Verify that the BalanceResponse type definition accurately reflects the response structure from the explorers using valid Bitcoin addresses.

# Using different known valid Bitcoin testnet and mainnet addresses
VALID_TESTNET_ADDRESS="tb1q7g0j3w0h9u9n0j9k9j9k9j9k9j9k9j9k9j9k9j"
VALID_MAINNET_ADDRESS="bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh"

# Fetching the response structure from the explorers
curl https://blockstream.info/testnet/api/address/$VALID_TESTNET_ADDRESS
curl https://mempool.space/testnet/api/address/$VALID_TESTNET_ADDRESS
curl https://blockstream.info/api/address/$VALID_MAINNET_ADDRESS
curl https://mempool.space/api/address/$VALID_MAINNET_ADDRESS

Length of output: 3193

packages/stake/src/lib/abi/ERC20ABI.ts (3)

2-24: Verify the correctness of the approve function ABI.

Ensure that the approve function ABI definition follows the ERC20 standard.

Verification successful

Verify the correctness of the approve function ABI.

Ensure that the approve function ABI definition follows the ERC20 standard.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the approve function ABI.

# Test: Check the ERC20 standard for the approve function. Expect: The ABI definition should match the ERC20 standard.
rg --type md 'approve' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 82


25-51: Verify the correctness of the transferFrom function ABI.

Ensure that the transferFrom function ABI definition follows the ERC20 standard.

Verification successful

The transferFrom function ABI is correctly defined and follows the ERC20 standard.

  • constant: false
  • inputs: _from (address), _to (address), _value (uint256)
  • name: 'transferFrom'
  • outputs: type 'bool'
  • payable: false
  • stateMutability: 'nonpayable'
  • type: 'function'
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the transferFrom function ABI.

# Test: Check the ERC20 standard for the transferFrom function. Expect: The ABI definition should match the ERC20 standard.
rg --type md 'transferFrom' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 92


Script:

#!/bin/bash
# Extract the ABI definition of the transferFrom function from the specified file and verify its correctness.
rg -A 20 'name: .transferFrom.' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 408


Script:

#!/bin/bash
# Extract a larger context around the ABI definition of the transferFrom function to capture all necessary fields.
rg -A 30 'name: .transferFrom.' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 562


Script:

#!/bin/bash
# Extract an even larger context around the ABI definition of the transferFrom function to capture all necessary fields.
rg -A 50 'name: .transferFrom.' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 889


Script:

#!/bin/bash
# Extract the entire content of the file to manually locate the transferFrom function ABI definition.
cat packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 1879


94-117: Verify the correctness of the allowance function ABI.

Ensure that the allowance function ABI definition follows the ERC20 standard.

Verification successful

To ensure the allowance function ABI definition follows the ERC20 standard, we need to compare the ABI details more thoroughly. Let's extract the ABI definition and compare it with the standard.


Let's re-extract the complete ABI definition for the allowance function to ensure all parts are included.


Let's verify the presence of the _owner and _spender inputs within the ABI definition for the allowance function.


Verified the correctness of the allowance function ABI.

The ABI definition for the allowance function includes the necessary inputs (_owner and _spender) and outputs, and it follows the ERC20 standard.

  • The inputs _owner and _spender are present in the file.
  • The outputs and other properties match the ERC20 standard.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correctness of the allowance function ABI.

# Test: Check the ERC20 standard for the allowance function. Expect: The ABI definition should match the ERC20 standard.
rg --type md 'allowance' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 86


Script:

#!/bin/bash
# Extract the ABI definition for the allowance function and compare it with the ERC20 standard.

# Extract the allowance function ABI definition from the specified file.
rg -A 15 'name: .allowance.' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 253


Script:

#!/bin/bash
# Re-extract the complete ABI definition for the allowance function, including inputs.

# Extract the allowance function ABI definition from the specified file.
rg -A 20 'name: .allowance.' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 253


Script:

#!/bin/bash
# Verify the presence of the _owner and _spender inputs within the ABI definition for the allowance function.

# Search for _owner input in the specified file.
rg '_owner' packages/stake/src/lib/abi/ERC20ABI.ts

# Search for _spender input in the specified file.
rg '_spender' packages/stake/src/lib/abi/ERC20ABI.ts

Length of output: 203

packages/stake/src/lib/stake.spec.ts (1)

1-8: Ensure all imported modules are used.

Verify that all imported modules from vitest, ethers, viem, and @gardenfi/utils are necessary and used in the code.

Verification successful

All imported modules are used.

The imported modules from vitest, ethers, viem, and @gardenfi/utils are all utilized in the code as expected.

  • vitest: describe, expect, test
  • ethers: ethers.JsonRpcProvider
  • viem: privateKeyToAccount, createPublicClient, createWalletClient, http, parseGwei, sepolia
  • @gardenfi/utils: Url
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that all imported modules are used in the code.

# Test: Search for the usage of imported modules. Expect: All imported modules should be used in the code.
rg --type ts 'vitest' packages/stake/src/lib/stake.spec.ts
rg --type ts 'ethers' packages/stake/src/lib/stake.spec.ts
rg --type ts 'viem' packages/stake/src/lib/stake.spec.ts
rg --type ts '@gardenfi/utils' packages/stake/src/lib/stake.spec.ts

Length of output: 582


Script:

#!/bin/bash
# Description: Verify that all imported modules are used in the code.

# Test: Search for the usage of specific imported modules. Expect: All imported modules should be used in the code.
rg --type ts 'describe|expect|test' packages/stake/src/lib/stake.spec.ts
rg --type ts 'ethers' packages/stake/src/lib/stake.spec.ts
rg --type ts 'privateKeyToAccount|createPublicClient|createWalletClient|http|parseGwei|sepolia' packages/stake/src/lib/stake.spec.ts
rg --type ts 'convertTo0xString' packages/stake/src/lib/stake.spec.ts
rg --type ts 'Url' packages/stake/src/lib/stake.spec.ts

Length of output: 1905

packages/stake/src/lib/abi/stakeABI.ts (6)

2-30: LGTM!

The vote function definition is correct and consistent with typical staking contract requirements.


31-47: LGTM!

The changeVote function definition is correct and consistent with typical staking contract requirements.


48-61: LGTM!

The first refund function definition is correct and consistent with typical staking contract requirements.


62-73: LGTM!

The second refund function definition is correct and consistent with typical staking contract requirements.


74-91: LGTM!

The renew function definition is correct and consistent with typical staking contract requirements.


92-109: LGTM!

The extend function definition is correct and consistent with typical staking contract requirements.

packages/walletConnectors/test/src/components/Hello.tsx (7)

1-3: Import statements are correct.

The import statements for useState and useBitcoinWallet are correct and necessary for the component functionality.


4-13: Component initialization is correct.

The component initializes state variables and uses the useBitcoinWallet hook correctly.


15-31: Wallet connection handling is correct.

The component correctly maps over walletList to display wallet connection options and handles the connection process.


32-33: Account and network display is correct.

The component correctly displays the connected account and network.


34-52: Balance retrieval handling is correct.

The component correctly handles balance retrieval and updates the state accordingly.


53-79: Send Bitcoin input handling is correct.

The component correctly handles input changes for sendAmount and sendAddress.


80-93: Send Bitcoin functionality is correct.

The component correctly handles the process of sending Bitcoin and logs the transaction ID.

packages/walletConnectors/src/bitcoin/providers/unisat/provider.ts (10)

1-4: Import statements are correct.

The import statements for UnisatBitcoinProvider, Err, executeWithTryCatch, Ok, IInjectedBitcoinProvider, and Network are correct and necessary for the class functionality.


5-11: Constructor and private member initialization are correct.

The constructor correctly initializes the #unisatProvider private member.


13-35: Connect method is correct.

The connect method correctly handles the process of connecting to the Unisat wallet, requesting accounts, and retrieving the network.


37-41: Request accounts method is correct.

The requestAccounts method correctly handles the process of requesting accounts from the Unisat wallet.


44-48: Get accounts method is correct.

The getAccounts method correctly handles the process of retrieving accounts from the Unisat wallet.


51-57: Get network method is correct.

The getNetwork method correctly handles the process of retrieving the network from the Unisat wallet.


59-64: Get balance method is correct.

The getBalance method correctly handles the process of retrieving the balance from the Unisat wallet.


66-70: Send Bitcoin method is correct.

The sendBitcoin method correctly handles the process of sending Bitcoin from the Unisat wallet.


72-74: Event handling method on is correct.

The on method correctly handles the process of subscribing to events from the Unisat wallet.


76-78: Event handling method off is correct.

The off method correctly handles the process of unsubscribing from events from the Unisat wallet.

packages/walletConnectors/src/bitcoin/providers/okx/provider.ts (9)

1-11: LGTM!

The constructor and property declarations are correctly implemented.


37-41: LGTM!

The getPublicKey method is correctly implemented using executeWithTryCatch for error handling.


43-48: LGTM!

The requestAccounts method is correctly implemented using executeWithTryCatch for error handling.


50-54: LGTM!

The getAccounts method is correctly implemented using executeWithTryCatch for error handling.


56-62: LGTM!

The getNetwork method is correctly implemented using executeWithTryCatch for error handling.


64-69: LGTM!

The getBalance method is correctly implemented using executeWithTryCatch for error handling.


71-75: LGTM!

The sendBitcoin method is correctly implemented using executeWithTryCatch for error handling.


77-79: LGTM!

The on method is correctly implemented.


81-83: LGTM!

The off method is correctly implemented.

packages/walletConnectors/src/bitcoin/providers/xdefi/provider.ts (8)

1-12: LGTM!

The constructor and property declarations are correctly implemented.


35-41: LGTM!

The requestAccounts method is correctly implemented using executeWithTryCatch for error handling.


43-48: LGTM!

The getAccounts method is correctly implemented using executeWithTryCatch for error handling.


51-53: LGTM!

The getNetwork method is correctly implemented.


55-57: LGTM!

The getPublicKey method correctly returns an error message.


59-64: LGTM!

The getBalance method is correctly implemented using the getBalance utility function and handles errors appropriately.


94-96: LGTM!

The on method is correctly implemented.


97-99: LGTM!

The off method is correctly implemented.

packages/paymentChannel/src/lib/paymentChannel.types.ts (6)

3-13: LGTM!

The HTLCStatus enum is well-defined and covers all necessary statuses.


15-19: LGTM!

The PendingHTLC type is well-defined and includes all necessary fields.


21-36: LGTM!

The HTLC type is well-defined and includes all necessary fields. The comments provide additional context for some fields.


38-51: LGTM!

The Channel type is well-defined and includes all necessary fields.


53-65: LGTM!

The LatestState type is well-defined and includes all necessary fields.


67-72: LGTM!

The ConditionalPaymentInitialRequest type is well-defined and includes all necessary fields.

packages/utils/src/lib/auth/siwe.ts (3)

2-2: LGTM! Import changes are correct.

The import statement has been updated to include SiweOpts from auth.types, replacing OrderbookOpts.


11-11: LGTM! New property addition is correct.

The new private readonly property API is correctly defined to hold the URL for the API.


17-18: LGTM! Constructor changes are correct.

The constructor parameter type for opts has been changed from OrderbookOpts to SiweOpts, and the default value for the url parameter has been modified to use API.

packages/walletConnectors/src/bitcoin/providers/xverse/provider.ts (6)

1-7: LGTM! Import statements are correct.

The import statements include the necessary types and utilities required for the XverseProvider class.


9-15: LGTM! Class definition and constructor are correct.

The XverseProvider class correctly implements the IInjectedBitcoinProvider interface, and the constructor initializes the XVerseBitcoinProvider.


17-47: LGTM! Connect method is correctly implemented.

The connect method correctly attempts to connect to the XVerse wallet and retrieve the network information, handling errors appropriately.


50-55: LGTM! GetBalance method is correctly implemented.

The getBalance method correctly retrieves the balance from the XVerse wallet, handling errors appropriately.


61-69: LGTM! GetAccounts method is correctly implemented.

The getAccounts method correctly retrieves the accounts from the XVerse wallet, handling errors appropriately.


71-93: LGTM! SendBitcoin method is correctly implemented.

The sendBitcoin method correctly sends Bitcoin to a specified address using the XVerse wallet, handling errors appropriately.

packages/paymentChannel/src/lib/paymentChannel.spec.ts (6)

1-5: LGTM! Import statements are correct.

The import statements include the necessary modules required for testing the PaymentChannel service.


10-23: LGTM! Test setup is correctly implemented.

The test setup correctly initializes the PaymentChannel service and related dependencies.


25-31: LGTM! Skipped test for getChannel is correctly implemented.

The test for getChannel includes a sanity check for the service and can be enabled as needed.


33-52: LGTM! Skipped test for createConditionalPayment is correctly implemented.

The test for createConditionalPayment includes a sanity check for the service and can be enabled as needed.


54-63: LGTM! Skipped test for computeSecretsForWithdrawal is correctly implemented.

The test for computeSecretsForWithdrawal includes a sanity check for the service and can be enabled as needed.


65-72: LGTM! Skipped test for initiateWithdraw is correctly implemented.

The test for initiateWithdraw includes a sanity check for the service and can be enabled as needed.

packages/walletConnectors/src/bitcoin/btcWalletsProvider.tsx (3)

69-75: Ensure immutability when updating state.

The addToWalletList function correctly uses the spread operator to maintain immutability when updating the state.


114-121: Ensure context values are correctly provided.

The context provider correctly passes the state values and functions to the context consumers.


99-112: Add cleanup function to useEffect hook.

The useEffect hook should include a cleanup function to remove the event listener when the component unmounts.

    return () => {
      provider.off('accountsChanged', handleAccountsChanged);
    };

Likely invalid or redundant comment.

packages/paymentChannel/src/lib/abi/atomicSwap.ts (1)

1-156: Ensure ABI definition is correct and follows best practices.

The ABI definition appears to be correct and follows best practices.

packages/paymentChannel/src/lib/utils.ts (6)

22-27: Ensure comprehensive error handling.

The parseError function correctly handles different error types and returns a meaningful message.


77-94: Ensure accurate timelock calculation.

The getTimelock function correctly handles different network conditions and calculates the timelock accurately.


100-105: Handle potential errors in getBlockNumber function.

The getBlockNumber function correctly handles the provider call and potential errors.


107-121: Handle potential errors in getLatestBlock function.

The getLatestBlock function correctly handles different network conditions and potential errors.


128-140: Handle potential errors in getL1BlockNumber function.

The getL1BlockNumber function correctly handles different network conditions and potential errors.


148-167: Ensure correct implementation of utility functions.

The isDurationExceeded and hashString functions correctly handle their respective tasks and potential errors.

packages/orderbook/src/lib/orderbook.ts (9)

3-10: LGTM! Import statements restructuring improves readability.

The consolidation of imports enhances clarity.

Also applies to: 17-17


26-29: LGTM! Class properties reformatting improves readability.

The reformatting enhances code aesthetics without altering functionality.


31-44: LGTM! Constructor reformatting improves readability.

The reformatting enhances code aesthetics without altering functionality.


48-67: LGTM! Static init method reformatting improves readability.

The reformatting enhances code aesthetics without altering functionality.


69-87: LGTM! getSupportedContracts method reformatting improves readability.

The reformatting enhances code aesthetics without altering functionality.


90-93: LGTM! getOrder method reformatting improves readability.

The reformatting enhances code aesthetics without altering functionality.


95-123: LGTM! createOrder method reformatting improves readability.

The reformatting enhances code aesthetics without altering functionality.


126-146: LGTM! getOrders method reformatting improves readability.

The reformatting enhances code aesthetics without altering functionality.


149-155: LGTM! subscribeOrders and unsubscribeOrders methods reformatting improves readability.

The reformatting enhances code aesthetics without altering functionality.

packages/stake/src/lib/stake.ts (10)

29-54: LGTM! Constructor and init method ensure proper initialization.

The initialization logic is clear and correct.


56-66: LGTM! getStakes method handles errors gracefully.

The use of executeWithTryCatch ensures robust error handling.


68-77: LGTM! getGlobalStakingData method handles errors gracefully.

The use of executeWithTryCatch ensures robust error handling.


79-146: LGTM! stakeAndVote method handles staking and voting logic effectively.

The method includes necessary checks and handles approvals and transactions correctly.


149-164: LGTM! unStake method handles unstaking logic effectively.

The use of executeWithTryCatch ensures robust error handling.


166-187: LGTM! renewStake method handles stake renewal logic effectively.

The use of executeWithTryCatch ensures robust error handling.


188-209: LGTM! extendStake method handles stake extension logic effectively.

The use of executeWithTryCatch ensures robust error handling.


Line range hint 233-274:
LGTM! computeSecretsForWithdrawal method generates secrets securely.

The method includes necessary checks and handles secret generation correctly.


Line range hint 276-339:
LGTM! signWithdrawMessage method handles message signing securely.

The method includes necessary checks and handles message signing correctly.


Line range hint 341-367:
LGTM! requestWithdrawal method handles withdrawal request logic effectively.

The use of executeWithTryCatch ensures robust error handling.

packages/paymentChannel/src/lib/index.ts (10)

44-66: LGTM! Constructor and init method ensure proper initialization.

The initialization logic is clear and correct.


73-87: LGTM! getChannel method handles errors gracefully.

The method ensures robust error handling.


94-105: LGTM! getSignatureForConditionalPayment method handles signature generation securely.

The method includes necessary checks and handles signature generation correctly.


112-149: LGTM! createConditionalPayment method handles payment creation securely.

The method includes necessary checks and handles payment creation correctly.


157-179: LGTM! _lockChannel method handles channel locking effectively.

The use of executeWithTryCatch ensures robust error handling.


186-217: LGTM! payConditionally method handles payment request securely.

The method includes necessary checks and handles payment request correctly.


219-231: LGTM! getWithdrawNonce method handles errors gracefully.

The use of executeWithTryCatch ensures robust error handling.


233-274: LGTM! computeSecretsForWithdrawal method generates secrets securely.

The method includes necessary checks and handles secret generation correctly.


276-339: LGTM! signWithdrawMessage method handles message signing securely.

The method includes necessary checks and handles message signing correctly.

Tools
Biome

[error] 278-278: Don't use 'BigInt' as a type.

Use lowercase primitives for consistency.
Safe fix: Use 'bigint' instead

(lint/complexity/noBannedTypes)


341-367: LGTM! requestWithdrawal method handles withdrawal request logic effectively.

The use of executeWithTryCatch ensures robust error handling.

Comment on lines +15 to +21
test('getBlockNumber', async () => {
const ethBlockNumber = await getBlockNumber(ethProvider);
const arbBlockNumber = await getBlockNumber(arbProvider);
const sepoliaBlockNumber = await getBlockNumber(sepoliaProvider);
console.log('ethBlockNumber :', ethBlockNumber.val);
console.log('arbBlockNumber :', arbBlockNumber.val);
console.log('sepoliaBlockNumber :', sepoliaBlockNumber.val);
Copy link

Choose a reason for hiding this comment

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

Remove console log statements.

The test case includes console log statements that should be removed to keep the test output clean.

-    console.log('ethBlockNumber :', ethBlockNumber.val);
-    console.log('arbBlockNumber :', arbBlockNumber.val);
-    console.log('sepoliaBlockNumber :', sepoliaBlockNumber.val);
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
test('getBlockNumber', async () => {
const ethBlockNumber = await getBlockNumber(ethProvider);
const arbBlockNumber = await getBlockNumber(arbProvider);
const sepoliaBlockNumber = await getBlockNumber(sepoliaProvider);
console.log('ethBlockNumber :', ethBlockNumber.val);
console.log('arbBlockNumber :', arbBlockNumber.val);
console.log('sepoliaBlockNumber :', sepoliaBlockNumber.val);
test('getBlockNumber', async () => {
const ethBlockNumber = await getBlockNumber(ethProvider);
const arbBlockNumber = await getBlockNumber(arbProvider);
const sepoliaBlockNumber = await getBlockNumber(sepoliaProvider);

Comment on lines +52 to +67
const confirmedBalanceSatoshis =
response.chain_stats.funded_txo_sum - response.chain_stats.spent_txo_sum;
const unconfirmedBalanceSatoshis =
response.mempool_stats.funded_txo_sum -
response.mempool_stats.spent_txo_sum;
const totalBalanceSatoshis =
confirmedBalanceSatoshis + unconfirmedBalanceSatoshis;

return Ok({
confirmed: confirmedBalanceSatoshis,
unconfirmed: unconfirmedBalanceSatoshis,
total: totalBalanceSatoshis,
});
} catch (error) {
return Err('Error while fetching balance', error);
}
Copy link

Choose a reason for hiding this comment

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

Improve error handling in getBalance function.

Consider logging the error message for better debugging and provide more context in the error message.

-  return Err('Error while fetching balance', error);
+  console.error(`Error while fetching balance for address ${address} on ${network}:`, error);
+  return Err(`Error while fetching balance for address ${address} on ${network}`);

Committable suggestion was skipped due to low confidence.

Comment on lines +33 to +38
export const getBalance = async (
address: string,
network: Network
): AsyncResult<Balance, string> => {
const explorers = BitcoinExplorers[network];
if (!explorers) return Err('Invalid network');
Copy link

Choose a reason for hiding this comment

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

Handle invalid network error more gracefully.

Consider throwing an error or logging the invalid network error for better debugging.

-  if (!explorers) return Err('Invalid network');
+  if (!explorers) {
+    console.error(`Invalid network: ${network}`);
+    return Err('Invalid network');
+  }
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 getBalance = async (
address: string,
network: Network
): AsyncResult<Balance, string> => {
const explorers = BitcoinExplorers[network];
if (!explorers) return Err('Invalid network');
export const getBalance = async (
address: string,
network: Network
): AsyncResult<Balance, string> => {
const explorers = BitcoinExplorers[network];
if (!explorers) {
console.error(`Invalid network: ${network}`);
return Err('Invalid network');
}

Comment on lines +13 to +35
async connect() {
try {
const result = await this.#okxProvider.connect();
this.address = result.address;

if (!window.okxwallet || !window.okxwallet.bitcoin)
return Err('OKX wallet not found');

const provider = new OKXProvider(window.okxwallet.bitcoin);
this.#okxProvider = provider.#okxProvider;

const network = await this.getNetwork();
if (network.error) return Err('Could not get network', network.error);

return Ok({
address: this.address,
provider: provider,
network: network.val,
});
} catch (error) {
return Err('Error while connecting to the OKX wallet', error);
}
}
Copy link

Choose a reason for hiding this comment

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

Remove unnecessary reinitialization of OKXProvider.

Reinitializing the OKXProvider instance within the connect method is unnecessary and can be removed.

-      const provider = new OKXProvider(window.okxwallet.bitcoin);
-      this.#okxProvider = provider.#okxProvider;
+      if (!window.okxwallet || !window.okxwallet.bitcoin)
+        return Err('OKX wallet not found');
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
async connect() {
try {
const result = await this.#okxProvider.connect();
this.address = result.address;
if (!window.okxwallet || !window.okxwallet.bitcoin)
return Err('OKX wallet not found');
const provider = new OKXProvider(window.okxwallet.bitcoin);
this.#okxProvider = provider.#okxProvider;
const network = await this.getNetwork();
if (network.error) return Err('Could not get network', network.error);
return Ok({
address: this.address,
provider: provider,
network: network.val,
});
} catch (error) {
return Err('Error while connecting to the OKX wallet', error);
}
}
async connect() {
try {
const result = await this.#okxProvider.connect();
this.address = result.address;
if (!window.okxwallet || !window.okxwallet.bitcoin)
return Err('OKX wallet not found');
const network = await this.getNetwork();
if (network.error) return Err('Could not get network', network.error);
return Ok({
address: this.address,
provider: this.#okxProvider,
network: network.val,
});
} catch (error) {
return Err('Error while connecting to the OKX wallet', error);
}
}

Comment on lines +66 to +92
//TODO: not yet tested
sendBitcoin = async (toAddress: string, satoshis: number) => {
const res = await new Promise<{ error: any; txHash: string }>(
(resolve, reject) => {
this.#xdefiProvider.request(
{
method: 'transfer',
params: [
{
feeRate: 10,
from: this.address,
recipient: toAddress,
amount: satoshis,
memo: 'Send Bitcoin',
},
],
},
(error: any, txHash: string) => {
console.log('here :', error);
resolve({ error, txHash });
}
);
}
);
if (res.error) return Err(res.error);
return Ok(res.txHash);
};
Copy link

Choose a reason for hiding this comment

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

Remove console log and add proper error handling.

Logging errors to the console is not a recommended practice. Add proper error handling instead. Also, the TODO comment indicates that the method is not yet tested.

-        console.log('here :', error);
+        if (error) reject(error);

Do you want me to assist with testing this method or open a GitHub issue to track this task?

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
//TODO: not yet tested
sendBitcoin = async (toAddress: string, satoshis: number) => {
const res = await new Promise<{ error: any; txHash: string }>(
(resolve, reject) => {
this.#xdefiProvider.request(
{
method: 'transfer',
params: [
{
feeRate: 10,
from: this.address,
recipient: toAddress,
amount: satoshis,
memo: 'Send Bitcoin',
},
],
},
(error: any, txHash: string) => {
console.log('here :', error);
resolve({ error, txHash });
}
);
}
);
if (res.error) return Err(res.error);
return Ok(res.txHash);
};
//TODO: not yet tested
sendBitcoin = async (toAddress: string, satoshis: number) => {
const res = await new Promise<{ error: any; txHash: string }>(
(resolve, reject) => {
this.#xdefiProvider.request(
{
method: 'transfer',
params: [
{
feeRate: 10,
from: this.address,
recipient: toAddress,
amount: satoshis,
memo: 'Send Bitcoin',
},
],
},
(error: any, txHash: string) => {
if (error) reject(error);
resolve({ error, txHash });
}
);
}
);
if (res.error) return Err(res.error);
return Ok(res.txHash);
};

Comment on lines +29 to +75
export const signPayment = async (
channel: Channel,
paymentRequest: ConditionalPaymentInitialRequest,
signer: JsonRpcSigner | Wallet
) => {
if (!signer.provider) throw new Error('Provider not found in the signer');
const selectedChainId = (await signer.provider.getNetwork()).chainId;

const types: Record<string, TypedDataField[]> = {
Claim: [
{ name: 'nonce', type: 'uint256' },
{ name: 'amount', type: 'uint256' },
{ name: 'htlcs', type: 'HTLC[]' },
],
HTLC: [
{ name: 'secretHash', type: 'bytes32' },
{ name: 'timeLock', type: 'uint256' },
{ name: 'sendAmount', type: 'uint256' },
{ name: 'receiveAmount', type: 'uint256' },
],
};

const domain = {
name: 'FEEAccount',
version: '1',
chainId: +selectedChainId.toString(),
verifyingContract: channel.address,
};

const claim = {
nonce: channel.latestState.nonce + 1,
amount: channel.latestState.amount,
htlcs: [
...channel.latestState.htlcs.map((htlc) => ({
secretHash: htlc.secretHash.startsWith('0x')
? htlc.secretHash
: '0x' + htlc.secretHash,
timeLock: htlc.timeLock,
sendAmount: htlc.sendAmount,
receiveAmount: htlc.receiveAmount,
})),
paymentRequest,
],
};

return await signer.signTypedData(domain, types, claim);
};
Copy link

Choose a reason for hiding this comment

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

Handle potential errors in signPayment function.

The signPayment function should handle potential errors more gracefully, such as logging or providing user feedback.

+  try {
    if (!signer.provider) throw new Error('Provider not found in the signer');
    const selectedChainId = (await signer.provider.getNetwork()).chainId;

    const types: Record<string, TypedDataField[]> = {
      Claim: [
        { name: 'nonce', type: 'uint256' },
        { name: 'amount', type: 'uint256' },
        { name: 'htlcs', type: 'HTLC[]' },
      ],
      HTLC: [
        { name: 'secretHash', type: 'bytes32' },
        { name: 'timeLock', type: 'uint256' },
        { name: 'sendAmount', type: 'uint256' },
        { name: 'receiveAmount', type: 'uint256' },
      ],
    };

    const domain = {
      name: 'FEEAccount',
      version: '1',
      chainId: +selectedChainId.toString(),
      verifyingContract: channel.address,
    };

    const claim = {
      nonce: channel.latestState.nonce + 1,
      amount: channel.latestState.amount,
      htlcs: [
        ...channel.latestState.htlcs.map((htlc) => ({
          secretHash: htlc.secretHash.startsWith('0x')
            ? htlc.secretHash
            : '0x' + htlc.secretHash,
          timeLock: htlc.timeLock,
          sendAmount: htlc.sendAmount,
          receiveAmount: htlc.receiveAmount,
        })),
        paymentRequest,
      ],
    };

    return await signer.signTypedData(domain, types, claim);
+  } catch (error) {
+    console.error('Failed to sign payment:', error);
+    throw new Error('Failed to sign payment');
+  }
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 signPayment = async (
channel: Channel,
paymentRequest: ConditionalPaymentInitialRequest,
signer: JsonRpcSigner | Wallet
) => {
if (!signer.provider) throw new Error('Provider not found in the signer');
const selectedChainId = (await signer.provider.getNetwork()).chainId;
const types: Record<string, TypedDataField[]> = {
Claim: [
{ name: 'nonce', type: 'uint256' },
{ name: 'amount', type: 'uint256' },
{ name: 'htlcs', type: 'HTLC[]' },
],
HTLC: [
{ name: 'secretHash', type: 'bytes32' },
{ name: 'timeLock', type: 'uint256' },
{ name: 'sendAmount', type: 'uint256' },
{ name: 'receiveAmount', type: 'uint256' },
],
};
const domain = {
name: 'FEEAccount',
version: '1',
chainId: +selectedChainId.toString(),
verifyingContract: channel.address,
};
const claim = {
nonce: channel.latestState.nonce + 1,
amount: channel.latestState.amount,
htlcs: [
...channel.latestState.htlcs.map((htlc) => ({
secretHash: htlc.secretHash.startsWith('0x')
? htlc.secretHash
: '0x' + htlc.secretHash,
timeLock: htlc.timeLock,
sendAmount: htlc.sendAmount,
receiveAmount: htlc.receiveAmount,
})),
paymentRequest,
],
};
return await signer.signTypedData(domain, types, claim);
};
export const signPayment = async (
channel: Channel,
paymentRequest: ConditionalPaymentInitialRequest,
signer: JsonRpcSigner | Wallet
) => {
try {
if (!signer.provider) throw new Error('Provider not found in the signer');
const selectedChainId = (await signer.provider.getNetwork()).chainId;
const types: Record<string, TypedDataField[]> = {
Claim: [
{ name: 'nonce', type: 'uint256' },
{ name: 'amount', type: 'uint256' },
{ name: 'htlcs', type: 'HTLC[]' },
],
HTLC: [
{ name: 'secretHash', type: 'bytes32' },
{ name: 'timeLock', type: 'uint256' },
{ name: 'sendAmount', type: 'uint256' },
{ name: 'receiveAmount', type: 'uint256' },
],
};
const domain = {
name: 'FEEAccount',
version: '1',
chainId: +selectedChainId.toString(),
verifyingContract: channel.address,
};
const claim = {
nonce: channel.latestState.nonce + 1,
amount: channel.latestState.amount,
htlcs: [
...channel.latestState.htlcs.map((htlc) => ({
secretHash: htlc.secretHash.startsWith('0x')
? htlc.secretHash
: '0x' + htlc.secretHash,
timeLock: htlc.timeLock,
sendAmount: htlc.sendAmount,
receiveAmount: htlc.receiveAmount,
})),
paymentRequest,
],
};
return await signer.signTypedData(domain, types, claim);
} catch (error) {
console.error('Failed to sign payment:', error);
throw new Error('Failed to sign payment');
}
};

Comment on lines +30 to +34
test.skip('getStakes', async () => {
const res = await StakeProvider.getStakes(api, account.address);
console.log('stakes', res.val);
expect(res.ok).toBeTruthy();
});
Copy link

Choose a reason for hiding this comment

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

Remove console log and enable the test case.

Remove the console log and enable the test case to ensure it is executed during testing.

-  test.skip('getStakes', async () => {
+  test('getStakes', async () => {
-    console.log('stakes', res.val);
+    // console.log('stakes', res.val);

Committable suggestion was skipped due to low confidence.

Comment on lines +36 to +40
test.skip('getGlobalStakingData', async () => {
const res = await StakeProvider.getGlobalStakingData(api);
console.log('res :', res.val);
expect(res.ok).toBeTruthy();
});
Copy link

Choose a reason for hiding this comment

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

Remove console log and enable the test case.

Remove the console log and enable the test case to ensure it is executed during testing.

-  test.skip('getGlobalStakingData', async () => {
+  test('getGlobalStakingData', async () => {
-    console.log('res :', res.val);
+    // console.log('res :', res.val);
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
test.skip('getGlobalStakingData', async () => {
const res = await StakeProvider.getGlobalStakingData(api);
console.log('res :', res.val);
expect(res.ok).toBeTruthy();
});
test('getGlobalStakingData', async () => {
const res = await StakeProvider.getGlobalStakingData(api);
// console.log('res :', res.val);
expect(res.ok).toBeTruthy();
});

Comment on lines +42 to +67
test.skip('stake and vote', async () => {
const res = await sp.stakeAndVote(2100, 6);
console.log(res.val);
expect(res.ok).toBeTruthy();
expect(res.val).toBeTypeOf('string');
expect(res.error).toBeUndefined();
});

test.skip('unstake', async () => {
const res = await sp.unStake(
'0x8636df0d65073632cc00550818d4e160a3f4fe724c90a1a4d038d3b431d973ab'
);
expect(res.ok).toBeTruthy();
expect(res.val).toBeTypeOf('string');
expect(res.error).toBeUndefined();
});
test.skip('extend', async () => {
const res = await sp.extendStake(
'0x8636df0d65073632cc00550818d4e160a3f4fe724c90a1a4d038d3b431d973ab',
12
);
console.log('res.error :', res.error);
expect(res.ok).toBeTruthy();
expect(res.val).toBeTypeOf('string');
expect(res.error).toBeUndefined();
});
Copy link

Choose a reason for hiding this comment

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

Remove console logs and enable the test cases.

Remove the console logs and enable the test cases to ensure they are executed during testing.

-  test.skip('stake and vote', async () => {
+  test('stake and vote', async () => {
-    console.log(res.val);
+    // console.log(res.val);

-  test.skip('unstake', async () => {
+  test('unstake', async () => {

-  test.skip('extend', async () => {
+  test('extend', async () => {
-    console.log('res.error :', res.error);
+    // console.log('res.error :', res.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
test.skip('stake and vote', async () => {
const res = await sp.stakeAndVote(2100, 6);
console.log(res.val);
expect(res.ok).toBeTruthy();
expect(res.val).toBeTypeOf('string');
expect(res.error).toBeUndefined();
});
test.skip('unstake', async () => {
const res = await sp.unStake(
'0x8636df0d65073632cc00550818d4e160a3f4fe724c90a1a4d038d3b431d973ab'
);
expect(res.ok).toBeTruthy();
expect(res.val).toBeTypeOf('string');
expect(res.error).toBeUndefined();
});
test.skip('extend', async () => {
const res = await sp.extendStake(
'0x8636df0d65073632cc00550818d4e160a3f4fe724c90a1a4d038d3b431d973ab',
12
);
console.log('res.error :', res.error);
expect(res.ok).toBeTruthy();
expect(res.val).toBeTypeOf('string');
expect(res.error).toBeUndefined();
});
test('stake and vote', async () => {
const res = await sp.stakeAndVote(2100, 6);
// console.log(res.val);
expect(res.ok).toBeTruthy();
expect(res.val).toBeTypeOf('string');
expect(res.error).toBeUndefined();
});
test('unstake', async () => {
const res = await sp.unStake(
'0x8636df0d65073632cc00550818d4e160a3f4fe724c90a1a4d038d3b431d973ab'
);
expect(res.ok).toBeTruthy();
expect(res.val).toBeTypeOf('string');
expect(res.error).toBeUndefined();
});
test('extend', async () => {
const res = await sp.extendStake(
'0x8636df0d65073632cc00550818d4e160a3f4fe724c90a1a4d038d3b431d973ab',
12
);
// console.log('res.error :', res.error);
expect(res.ok).toBeTruthy();
expect(res.val).toBeTypeOf('string');
expect(res.error).toBeUndefined();
});

Comment on lines +10 to +28
describe('stake', async () => {
const provider = new ethers.JsonRpcProvider(
'https://sepolia.infura.io/v3/c24c1e1e6de4409485f1a0ca83662575'
);
const api = new Url('https://staking.garden.finance');
//provide a private key which has some SEED tokens
const account = privateKeyToAccount(convertTo0xString(''));

const publicClient = createPublicClient({
chain: sepolia,
transport: http(),
});
const walletClient = createWalletClient({
account,
chain: sepolia,
transport: http(),
});

const sp = StakeProvider.init(walletClient);
Copy link

Choose a reason for hiding this comment

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

Ensure the private key is securely managed.

The private key is currently an empty string. Ensure that the private key is securely managed and not hardcoded in the code.

-  const account = privateKeyToAccount(convertTo0xString(''));
+  // TODO: Replace with a securely managed private key
+  const account = privateKeyToAccount(convertTo0xString(process.env.PRIVATE_KEY || ''));
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
describe('stake', async () => {
const provider = new ethers.JsonRpcProvider(
'https://sepolia.infura.io/v3/c24c1e1e6de4409485f1a0ca83662575'
);
const api = new Url('https://staking.garden.finance');
//provide a private key which has some SEED tokens
const account = privateKeyToAccount(convertTo0xString(''));
const publicClient = createPublicClient({
chain: sepolia,
transport: http(),
});
const walletClient = createWalletClient({
account,
chain: sepolia,
transport: http(),
});
const sp = StakeProvider.init(walletClient);
describe('stake', async () => {
const provider = new ethers.JsonRpcProvider(
'https://sepolia.infura.io/v3/c24c1e1e6de4409485f1a0ca83662575'
);
const api = new Url('https://staking.garden.finance');
//provide a private key which has some SEED tokens
// TODO: Replace with a securely managed private key
const account = privateKeyToAccount(convertTo0xString(process.env.PRIVATE_KEY || ''));
const publicClient = createPublicClient({
chain: sepolia,
transport: http(),
});
const walletClient = createWalletClient({
account,
chain: sepolia,
transport: http(),
});
const sp = StakeProvider.init(walletClient);

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.

1 participant