Skip to content

Refactor: Use new protobuf to compatible with different versions of protocols #458

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

Draft
wants to merge 2 commits into
base: onekey
Choose a base branch
from

Conversation

wabicai
Copy link
Contributor

@wabicai wabicai commented May 6, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced device information extraction and display, including detailed build IDs, firmware, hardware, and secure element (SE) data.
    • Added support for new protocol message versions and expanded device message schemas for improved compatibility.
    • Introduced new utility functions for unified device info parsing and protocol compatibility.
  • Bug Fixes

    • Improved type safety and error handling in device info rendering and feature extraction.
    • Enhanced null and undefined value handling for safer UI rendering.
  • Refactor

    • Centralized and streamlined device reboot, bootloader entry, and version extraction logic.
    • Replaced legacy firmware submodule with a new protocol submodule for better maintainability.
    • Unified device feature retrieval and post-processing to support multiple protocol versions.
  • Chores

    • Updated submodule references and build scripts to use the new protocol source.
    • Expanded test coverage and updated test fixtures for renamed protocol messages.
    • Improved debug logging throughout device initialization and transport configuration.
  • Documentation

    • Extended and clarified type definitions for device messages, protocols, and blockchain operations.

Copy link
Contributor

coderabbitai bot commented May 6, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update removes the old firmware submodule and adds a new onekey-protocol submodule. It refactors device info extraction, unifies feature handling, and updates protobuf message schemas and types. Several classes now use a new base for firmware updates, and device communication uses new message types and commands. Many type definitions are expanded or renamed for clarity and consistency.

Changes

File(s) / Path(s) Change Summary
.gitmodules, submodules/firmware, submodules/onekey-protocol Removed the firmware submodule and added the onekey-protocol submodule, updating paths and URLs accordingly.
packages/hd-transport/scripts/protobuf-build.sh Updated script to use onekey-protocol as the protobuf source. Added logic to copy prebuilt messages if available. Adjusted proto combination for new namespaces.
packages/hd-transport/scripts/protobuf-types.js Added mapping for float protobuf type to JavaScript number.
packages/hd-transport/tests/encode-decode.test.js, packages/hd-transport/tests/messages.test.js Renamed test fixtures and message types from "Initialize" to "StartSession". Updated enums accordingly.
packages/hd-transport/src/serialization/protobuf/decode.ts Improved type checks for field.resolvedType and added explicit handling for null resolved types.
packages/hd-transport/src/types/messages.ts Major expansion and update of message types, enums, and interfaces. Added new device, firmware, blockchain, and protocol types. Renamed and removed deprecated types. Updated many fields to be required.
packages/hd-transport-http/src/index.ts Added debug logging. Changed timeout logic to trigger on "StartSession" instead of "Initialize".
packages/core/src/api/FirmwareUpdateV2.ts, packages/core/src/api/device/DeviceRebootToBoardloader.ts, packages/core/src/api/device/DeviceRebootToBootloader.ts, packages/core/src/api/device/DeviceUpdateReboot.ts Refactored classes to extend FirmwareUpdateBaseMethod. Centralized reboot logic via new reboot method. Removed or updated local bootloader entry/check logic.
packages/core/src/api/FirmwareUpdateV3.ts Disabled bootloader version error, changed firmware update path, and updated device reconnection command from "Initialize" to "StartSession".
packages/core/src/api/GetOnekeyFeatures.ts Replaced legacy feature fetch with conditional logic based on message version. Removed firmware version fix logic.
packages/core/src/api/firmware/FirmwareUpdateBaseMethod.ts Added a new reboot method for device reboots. Refactored enterBootloaderMode to use this method. Made some methods public. Improved error handling and logging.
packages/core/src/api/firmware/bootloaderHelper.ts Updated bootloader version check to use a utility function for version extraction.
packages/core/src/api/firmware/uploadFirmware.ts Changed device session start from "Initialize" with timeout to "StartSession" with parameters. Removed race logic.
packages/core/src/api/test/TestInitializeDeviceDuration.ts Switched device command from "Initialize" to "StartSession".
packages/core/src/data-manager/DataManager.ts Added support for message version 'v2' and included its JSON schema.
packages/core/src/data-manager/MessagesConfig.ts Changed message version mapping for device models to use 'v2' instead of 'latest'.
packages/core/src/data-manager/TransportManager.ts Enhanced debug logging with message version info.
packages/core/src/data/messages/messages_legacy_v1.json Renamed message and enum from "Initialize" to "StartSession".
packages/core/src/device/Device.ts Changed feature retrieval to use "StartSession" with parameters. Added post-processing for features. Improved feature update logic and logging.
packages/core/src/device/utils.ts Added cherryPickFeaturesParams utility for feature request parameters.
packages/core/src/types/api/cardano.ts Changed a property type in CardanoCVoteRegistrationParameters to use the new enum.
packages/core/src/types/api/deviceRebootToBoardloader.ts Changed type alias for parameters from a specific type to object.
packages/core/src/types/api/deviceRecovery.ts Updated recovery type property to use a new enum.
packages/core/src/types/device.ts Changed OnekeyFeatures type alias to reference PROTO.Features.
packages/core/src/utils/deviceFeaturesUtils.ts Added shortcut for message version detection. Improved version fixing logic and type safety.
packages/core/src/utils/deviceInfoUtils.ts Refactored device info extraction to use new utility functions for hardware and firmware info.
packages/core/src/utils/deviceUtils.ts Refactored device info extraction to use consolidated utility functions. Simplified null handling and info retrieval.
packages/core/src/utils/deviceVersionUtils.ts Centralized version extraction using a new utility function. Removed legacy fallback logic.
packages/core/src/utils/findDefectiveBatchDevice.ts Refactored to use new utility functions for serial number and SE version extraction.
packages/core/src/utils/index.ts Added exports for new hardware, firmware, and SE info utility functions.
packages/core/src/utils/onekeyInfoUtils.ts New module providing functions to extract and normalize hardware, firmware, and SE info from features. Added merging logic for old and new feature formats.
packages/connect-examples/expo-example/src/components/BaseTestRunner/Context/TestRunnerProvider.tsx Changed type annotations for device features from a specific type to any. Updated state and context accordingly.
packages/connect-examples/expo-example/src/components/BaseTestRunner/useRunnerTest.ts Removed a TypeScript error suppression comment.
packages/connect-examples/expo-example/src/utils/deviceUtils.ts Refactored device info retrieval to use new consolidated utility functions. Simplified function signatures and logic.
packages/connect-examples/expo-example/src/views/FirmwareScreen/DeviceField.tsx Improved null checks and type assertions. Updated conditional rendering logic for field values.
packages/connect-examples/expo-example/src/views/FirmwareScreen/ExportDeviceInfo.tsx Removed use of secondary features object. Refined type safety and extended SE info keys.
packages/connect-examples/expo-example/src/views/FirmwareScreen/index.tsx Merged feature objects before extracting device info. Appended build IDs to version strings in UI.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant Device
    participant FirmwareUpdateBaseMethod
    participant TransportManager

    App->>Device: StartSession({ ok_dev_info_req })
    Device->>Device: fixFeaturesBetweenProtocol()
    Device->>TransportManager: reconfigure(features)
    Device-->>App: features

    App->>FirmwareUpdateBaseMethod: enterBootloaderMode()
    FirmwareUpdateBaseMethod->>Device: reboot(BootLoader)
    Device-->>FirmwareUpdateBaseMethod: Success/Error (logs error, continues)
    FirmwareUpdateBaseMethod->>Device: check bootloader status
    FirmwareUpdateBaseMethod->>TransportManager: clear device cache
    FirmwareUpdateBaseMethod-->>App: Bootloader mode entered

    App->>FirmwareUpdateBaseMethod: reboot(OneKeyRebootType)
    FirmwareUpdateBaseMethod->>Device: typedCall (command depends on message version)
    Device-->>FirmwareUpdateBaseMethod: Success/Error (logs error, continues)
Loading
sequenceDiagram
    participant App
    participant Device
    participant onekeyInfoUtils

    App->>Device: getFeatures()
    Device->>Device: StartSession({ ok_dev_info_req: { factory, normal } })
    Device->>Device: fixFeaturesBetweenProtocol()
    Device->>onekeyInfoUtils: getHardwareInfoFromFeatures()
    Device->>onekeyInfoUtils: getFirmwareInfoFromFeatures()
    Device->>onekeyInfoUtils: getSeInfoFromFeatures()
    Device-->>App: features (normalized)
Loading
sequenceDiagram
    participant App
    participant DataManager

    App->>DataManager: get messages for version
    DataManager-->>App: messages (latest, v1, or v2)
Loading

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary or Summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@wabicai wabicai marked this pull request as draft May 6, 2025 10:15
@wabicai wabicai changed the title feat: protobuf v1 Refactor: Use new protobuf to compatible with different versions of protocols May 6, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 32

🔭 Outside diff range comments (5)
packages/core/src/types/api/cardano.ts (3)

141-162: 🛠️ Refactor suggestion

Naming inconsistency needs attention

While you updated the format property type, other related names remain inconsistent. The interface is still called CardanoCVoteRegistrationParameters and uses CardanoCVoteRegistrationDelegation. These should be renamed to match the new Governance prefix pattern.

-export interface CardanoCVoteRegistrationDelegation {
+export interface CardanoGovernanceRegistrationDelegation {
   votePublicKey: string;
   weight: number;
 }

-export interface CardanoCVoteRegistrationParameters {
+export interface CardanoGovernanceRegistrationParameters {
   votePublicKey?: string;
   stakingPath: string | number[];
   paymentAddressParameters: CardanoAddressParameters;
   nonce: string;
   format?: PROTO.CardanoGovernanceRegistrationFormat;
-  delegations?: CardanoCVoteRegistrationDelegation[];
+  delegations?: CardanoGovernanceRegistrationDelegation[];
   votingPurpose?: number;
   paymentAddress?: string;
 }

164-167: 🛠️ Refactor suggestion

Additional naming update needed

Update this interface to use the new governance naming pattern.

 export interface CardanoAuxiliaryData {
   hash?: string;
-  cVoteRegistrationParameters?: CardanoCVoteRegistrationParameters;
+  governanceRegistrationParameters?: CardanoGovernanceRegistrationParameters;
 }

202-206: 🛠️ Refactor suggestion

Rename field to match naming pattern

Update cVoteRegistrationSignature to governanceRegistrationSignature for consistency.

 export interface CardanoAuxiliaryDataSupplement {
   type: PROTO.CardanoTxAuxiliaryDataSupplementType;
   auxiliaryDataHash: string;
-  cVoteRegistrationSignature?: string;
+  governanceRegistrationSignature?: string;
 }
packages/core/src/device/Device.ts (1)

360-384: 🧹 Nitpick (assertive)

Swap console.error for the project logger

Raw console.error calls pollute stdout and can hurt performance on mobile. Use Log.debug/Log.error (already imported) or remove the statement.

-console.error('======> StartSession', options);
+Log.debug('StartSession', options);
packages/core/src/api/FirmwareUpdateV2.ts (1)

126-166: ⚠️ Potential issue

Undeclared methods – compile will fail

_promptDeviceInBootloaderForWebDevice and _checkDeviceInBootloaderMode no longer exist after the refactor to FirmwareUpdateBaseMethod.
Calls here will break the build.

-            const confirmed = await this._promptDeviceInBootloaderForWebDevice();
+            const confirmed = await this.promptDeviceInBootloaderForWebDevice();

...
-          await this._checkDeviceInBootloaderMode(connectId, intervalTimer, timeoutTimer);
+          await this.checkDeviceInBootloaderMode(connectId, intervalTimer, timeoutTimer);

Do the same replacement for the call in the else branch below.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b0cba7 and b3ee0be.

📒 Files selected for processing (43)
  • .gitmodules (1 hunks)
  • packages/connect-examples/expo-example/src/components/BaseTestRunner/Context/TestRunnerProvider.tsx (3 hunks)
  • packages/connect-examples/expo-example/src/components/BaseTestRunner/useRunnerTest.ts (0 hunks)
  • packages/connect-examples/expo-example/src/utils/deviceUtils.ts (4 hunks)
  • packages/connect-examples/expo-example/src/views/FirmwareScreen/DeviceField.tsx (3 hunks)
  • packages/connect-examples/expo-example/src/views/FirmwareScreen/ExportDeviceInfo.tsx (6 hunks)
  • packages/connect-examples/expo-example/src/views/FirmwareScreen/index.tsx (2 hunks)
  • packages/core/src/api/FirmwareUpdateV2.ts (7 hunks)
  • packages/core/src/api/FirmwareUpdateV3.ts (3 hunks)
  • packages/core/src/api/GetOnekeyFeatures.ts (2 hunks)
  • packages/core/src/api/device/DeviceRebootToBoardloader.ts (2 hunks)
  • packages/core/src/api/device/DeviceRebootToBootloader.ts (2 hunks)
  • packages/core/src/api/device/DeviceUpdateBootloader.ts (1 hunks)
  • packages/core/src/api/device/DeviceUpdateReboot.ts (1 hunks)
  • packages/core/src/api/firmware/FirmwareUpdateBaseMethod.ts (5 hunks)
  • packages/core/src/api/firmware/bootloaderHelper.ts (2 hunks)
  • packages/core/src/api/firmware/uploadFirmware.ts (2 hunks)
  • packages/core/src/api/test/TestInitializeDeviceDuration.ts (2 hunks)
  • packages/core/src/data-manager/DataManager.ts (3 hunks)
  • packages/core/src/data-manager/MessagesConfig.ts (1 hunks)
  • packages/core/src/data-manager/TransportManager.ts (2 hunks)
  • packages/core/src/data/messages/messages_legacy_v1.json (2 hunks)
  • packages/core/src/device/Device.ts (6 hunks)
  • packages/core/src/device/utils.ts (1 hunks)
  • packages/core/src/types/api/cardano.ts (1 hunks)
  • packages/core/src/types/api/deviceRebootToBoardloader.ts (1 hunks)
  • packages/core/src/types/api/deviceRecovery.ts (2 hunks)
  • packages/core/src/types/device.ts (1 hunks)
  • packages/core/src/utils/deviceFeaturesUtils.ts (3 hunks)
  • packages/core/src/utils/deviceInfoUtils.ts (3 hunks)
  • packages/core/src/utils/deviceVersionUtils.ts (2 hunks)
  • packages/core/src/utils/findDefectiveBatchDevice.ts (1 hunks)
  • packages/core/src/utils/index.ts (1 hunks)
  • packages/core/src/utils/onekeyInfoUtils.ts (1 hunks)
  • packages/hd-transport-http/src/index.ts (2 hunks)
  • packages/hd-transport/__tests__/encode-decode.test.js (1 hunks)
  • packages/hd-transport/__tests__/messages.test.js (3 hunks)
  • packages/hd-transport/scripts/protobuf-build.sh (3 hunks)
  • packages/hd-transport/scripts/protobuf-types.js (1 hunks)
  • packages/hd-transport/src/serialization/protobuf/decode.ts (2 hunks)
  • packages/hd-transport/src/types/messages.ts (75 hunks)
  • submodules/firmware (0 hunks)
  • submodules/onekey-protocol (1 hunks)
💤 Files with no reviewable changes (2)
  • packages/connect-examples/expo-example/src/components/BaseTestRunner/useRunnerTest.ts
  • submodules/firmware
🧰 Additional context used
🧬 Code Graph Analysis (13)
packages/hd-transport-http/src/index.ts (3)
packages/hd-transport/src/serialization/send.ts (1)
  • buildOne (13-22)
packages/shared/src/HardwareError.ts (1)
  • HardwareErrorCode (46-402)
packages/hd-transport/src/serialization/receive.ts (1)
  • receiveOne (8-18)
packages/core/src/api/firmware/bootloaderHelper.ts (2)
packages/core/src/utils/deviceVersionUtils.ts (1)
  • getDeviceBoardloaderVersion (52-58)
packages/core/src/utils/index.ts (1)
  • getDeviceBoardloaderVersion (15-15)
packages/core/src/types/device.ts (1)
packages/hd-transport/src/types/messages.ts (1)
  • Features (2406-2463)
packages/core/src/api/GetOnekeyFeatures.ts (4)
packages/core/src/utils/deviceFeaturesUtils.ts (1)
  • getSupportMessageVersion (14-56)
packages/core/src/types/device.ts (1)
  • Features (79-79)
packages/hd-transport/src/types/messages.ts (2)
  • Features (2406-2463)
  • MessageKey (5028-5028)
packages/core/src/device/utils.ts (1)
  • cherryPickFeaturesParams (4-25)
packages/hd-transport/scripts/protobuf-build.sh (2)
packages/hd-transport/__tests__/messages.test.js (1)
  • json (8-58)
packages/hd-transport/scripts/protobuf-types.js (1)
  • json (9-9)
packages/core/src/utils/findDefectiveBatchDevice.ts (3)
packages/core/src/types/device.ts (1)
  • Features (79-79)
packages/hd-transport/src/types/messages.ts (1)
  • Features (2406-2463)
packages/core/src/utils/onekeyInfoUtils.ts (2)
  • getHardwareInfoFromFeatures (148-169)
  • getSeInfoFromFeatures (171-280)
packages/core/src/utils/deviceFeaturesUtils.ts (1)
packages/core/src/data-manager/DataManager.ts (1)
  • DataManager (33-357)
packages/connect-examples/expo-example/src/views/FirmwareScreen/DeviceField.tsx (2)
packages/connect-examples/expo-example/src/views/FirmwareScreen/DeviceFieldContext.ts (1)
  • useDeviceFieldContext (17-19)
packages/connect-examples/expo-example/src/provider/MediaProvider.tsx (1)
  • useMedia (20-20)
packages/connect-examples/expo-example/src/views/FirmwareScreen/index.tsx (3)
packages/connect-examples/expo-example/src/utils/deviceUtils.ts (1)
  • getDeviceBasicInfo (50-99)
packages/hd-transport/src/types/messages.ts (1)
  • Features (2406-2463)
packages/connect-examples/expo-example/src/views/FirmwareScreen/DeviceField.tsx (1)
  • DeviceField (74-77)
packages/core/src/device/utils.ts (2)
packages/core/src/device/Device.ts (1)
  • IFeaturesType (55-58)
packages/hd-transport/src/types/messages.ts (2)
  • OneKeyInfoTargets (3612-3621)
  • OneKeyInfoTypes (3624-3629)
packages/core/src/utils/deviceInfoUtils.ts (3)
packages/core/src/utils/onekeyInfoUtils.ts (2)
  • getHardwareInfoFromFeatures (148-169)
  • getFirmwareInfoFromFeatures (69-147)
packages/core/src/types/device.ts (1)
  • Features (79-79)
packages/hd-transport/src/types/messages.ts (1)
  • Features (2406-2463)
packages/core/src/api/device/DeviceUpdateReboot.ts (3)
packages/core/src/api/firmware/FirmwareUpdateBaseMethod.ts (1)
  • FirmwareUpdateBaseMethod (32-451)
packages/hd-transport/src/types/messages.ts (1)
  • DeviceBackToBoot (827-827)
packages/core/src/events/ui-request.ts (1)
  • UI_REQUEST (8-44)
packages/connect-examples/expo-example/src/utils/deviceUtils.ts (3)
packages/core/src/types/device.ts (1)
  • Features (79-79)
packages/hd-transport/src/types/messages.ts (1)
  • Features (2406-2463)
packages/core/src/utils/onekeyInfoUtils.ts (3)
  • getFirmwareInfoFromFeatures (69-147)
  • getHardwareInfoFromFeatures (148-169)
  • getSeInfoFromFeatures (171-280)
🪛 Biome (1.9.4)
packages/core/src/data-manager/TransportManager.ts

[error] 62-62: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

packages/connect-examples/expo-example/src/views/FirmwareScreen/DeviceField.tsx

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

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

packages/hd-transport/src/types/messages.ts

[error] 143-143: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 245-245: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 788-788: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 824-824: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 827-827: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 830-830: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 887-887: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 1586-1586: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 1589-1589: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 2466-2466: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 2695-2695: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 2714-2714: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 2717-2717: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 2870-2870: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 3119-3119: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 3179-3179: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)


[error] 4388-4388: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

🪛 Shellcheck (0.10.0)
packages/hd-transport/scripts/protobuf-build.sh

[info] 46-46: Double quote to prevent globbing and word splitting.

(SC2086)


[info] 47-47: Double quote to prevent globbing and word splitting.

(SC2086)


[info] 50-50: Double quote to prevent globbing and word splitting.

(SC2086)


[info] 58-58: Double quote to prevent globbing and word splitting.

(SC2086)


[info] 70-70: Double quote to prevent globbing and word splitting.

(SC2086)


[info] 70-70: Double quote to prevent globbing and word splitting.

(SC2086)


[info] 71-71: Double quote to prevent globbing and word splitting.

(SC2086)

🔇 Additional comments (64)
packages/core/src/types/api/cardano.ts (1)

158-158: Type update looks good

The change from PROTO.CardanoCVoteRegistrationFormat to PROTO.CardanoGovernanceRegistrationFormat aligns with the broader renaming of Cardano governance types mentioned in the PR summary.

submodules/onekey-protocol (1)

1-1: Pin onekey-protocol submodule to correct commit
The subproject file now references commit 8f7a537fc0950866d43da08d4fca76f4635ccdd3, matching the updated .gitmodules.

packages/core/src/api/device/DeviceUpdateBootloader.ts (1)

9-9: Imports reduced to only what's needed.

Good job simplifying the import statement to include only the necessary checkBootloaderLength function. This improves code clarity and reduces bundle size.

packages/hd-transport/scripts/protobuf-types.js (1)

24-24: Support for protobuf float type added.

Adding the float to number mapping completes the protobuf primitive type conversion set. This enables proper handling of floating-point values in protobuf definitions.

packages/hd-transport/__tests__/encode-decode.test.js (1)

94-97: Message name updated from "Initialize" to "StartSession".

The fixture update aligns with the protocol-level message rename. This change maintains consistency across the codebase.

packages/hd-transport/__tests__/messages.test.js (3)

10-10: Protocol message renamed from "Initialize" to "StartSession"

The message schema has been renamed to improve clarity about its purpose - starting a session rather than general initialization.


54-54: MessageType enum value updated to match renamed message

Consistent renaming of the enum value to match the message type name change.


63-63: Test case updated to use new message name

Test case properly updated to use the new message name.

packages/core/src/types/api/deviceRecovery.ts (2)

1-1: Import updated to use the new RecoveryType

Import correctly updated to use the new type name.


11-11: Type definition updated to match imported type

Parameter type properly updated to use RecoveryType.

packages/core/src/utils/index.ts (1)

38-42:

✅ Verification successful

New utility functions exported for device info extraction

Good addition of utility functions that centralize device feature extraction.


🏁 Script executed:

#!/bin/bash
# Check if the onekeyInfoUtils file exists
cat packages/core/src/utils/onekeyInfoUtils.ts | head -20

Length of output: 576


🏁 Script executed:

#!/bin/bash
set -e
file="packages/core/src/utils/onekeyInfoUtils.ts"
echo "Searching for utility function definitions in $file"
grep -n "getHardwareInfoFromFeatures" $file || echo "getHardwareInfoFromFeatures not found"
grep -n "getFirmwareInfoFromFeatures" $file || echo "getFirmwareInfoFromFeatures not found"
grep -n "getSeInfoFromFeatures" $file || echo "getSeInfoFromFeatures not found"

Length of output: 872


Verification Complete – Exports Match Definitions
All three utilities—getHardwareInfoFromFeatures, getFirmwareInfoFromFeatures, and getSeInfoFromFeatures—are defined in onekeyInfoUtils.ts and correctly re-exported in utils/index.ts. No further action needed.

packages/hd-transport-http/src/index.ts (1)

121-121: Protocol update from 'Initialize' to 'StartSession'.

The timeout condition correctly reflects the protocol update where 'Initialize' was renamed to 'StartSession'.

packages/core/src/api/test/TestInitializeDeviceDuration.ts (1)

18-18: Protocol update from 'Initialize' to 'StartSession'.

The command name update is correct, and the empty object parameter matches the new API signature.

packages/core/src/data-manager/MessagesConfig.ts (1)

13-13: Explicit version labeling improves clarity.

Changing from 'latest' to 'v2' makes the version requirements more explicit and less ambiguous.

Also applies to: 17-17

packages/core/src/data/messages/messages_legacy_v1.json (2)

4831-4849: Great rename of Initialize to StartSession.
You’ve preserved the original numeric ID (0) and deprecated the old field. The structure is concise and clear.


9235-9236:

✅ Verification successful

Verify no leftover Initialize references.
Ensure all code and tests now use StartSession. Run this script to catch any stray mentions:


🏁 Script executed:

#!/bin/bash
# Find any remaining "Initialize" in the repo
rg -n '"Initialize\b"'

Length of output: 24


No leftover “Initialize” references found
RG returned no matches. All code and tests now use StartSession.

packages/core/src/data-manager/DataManager.ts (3)

6-6: Import added for the new v2 legacy messages.

This import brings in the new protobuf message definitions needed for the v2 protocol support.


31-31: Type definition updated to include the new v2 message version.

The MessageVersion type now correctly includes 'v2' alongside existing options.


68-68: Added v2 message version to the static messages dictionary.

Good implementation - follows the existing pattern for message version support.

packages/hd-transport/src/serialization/protobuf/decode.ts (4)

48-49: Improved type safety for enum fields.

Added explicit property check before accessing valuesById on field.resolvedType.


50-51: Enhanced type check for message fields.

The code now verifies that field.resolvedType exists and has a 'fields' property before attempting to access it.


59-60: Better type checking for enum resolution.

Similar to the repeated fields section, this improves safety when handling enum types.


63-66: Added comprehensive type checks and null handling.

This change improves error prevention by:

  1. Checking for the existence of resolvedType and its fields property
  2. Adding explicit handling for null resolved types

Good defensive programming that prevents potential runtime errors.

packages/core/src/api/firmware/uploadFirmware.ts (2)

27-28: Added imports for new feature parameter utilities.

These utility functions support the updated device session initialization.


245-247: Replaced race pattern with direct StartSession call.

This change:

  1. Replaces the Initialize command with the new StartSession command
  2. Removes the timeout-based race pattern
  3. Explicitly requests specific features with cherryPickFeaturesParams

The code is now cleaner and uses the modern protocol command.

packages/core/src/utils/findDefectiveBatchDevice.ts (3)

2-2: Updated imports to use the new utility functions.

Good move to import the centralized feature extraction utilities.


6-7: Refactored to use utility functions instead of direct property access.

Now uses getHardwareInfoFromFeatures and getSeInfoFromFeatures to extract device data. This approach better handles differences between protocol versions.


11-11: Updated condition to use extracted SE version property.

Now references se01Version from the utility function rather than directly accessing feature properties.

packages/core/src/api/firmware/bootloaderHelper.ts (1)

4-4: Good move: centralizing version parsing

Switching to getDeviceBoardloaderVersion and getDeviceType keeps all version/feature parsing logic in one place, which cuts duplication and future‐proofs maintenance.

packages/core/src/api/device/DeviceRebootToBootloader.ts (3)

1-2: Import updates align with new class inheritance

The imports now include OneKeyRebootType for specifying reboot types and FirmwareUpdateBaseMethod as the new parent class.


5-5: Class now extends FirmwareUpdateBaseMethod

The class inheritance change unifies reboot handling with other firmware update methods, improving consistency.


23-23: Standardized reboot method call

Using the base class's reboot method with OneKeyRebootType.BootLoader centralizes reboot logic and improves maintainability.

packages/hd-transport/scripts/protobuf-build.sh (3)

9-10: Updated source path to use onekey-protocol

The source directory correctly points to the new submodule path.


33-42: Added optimization to reuse existing messages.json

Smart performance improvement that checks if a pre-built messages.json already exists in the submodule.


82-82: Added completion message

Helpful confirmation for users that the build process finished.

packages/core/src/utils/deviceFeaturesUtils.ts (3)

23-28: Added shortcut for new protocol version detection

Smart optimization that returns the latest message version immediately when the device supports the new protocol.


231-232: Enhanced version fallback handling

The fixVersion function now safely handles undefined inputs by returning a default version.


257-259: Consistent version normalization for onekey_version

Same fix applied to the onekey_version field for complete consistency.

packages/connect-examples/expo-example/src/views/FirmwareScreen/DeviceField.tsx (3)

13-17: Strengthened empty value detection

The isNil function now checks both null and undefined values, and safely calls trim() only when available.


24-24: Safer type casting for features access

Using unknown as an intermediate type offers better type safety when accessing dynamic feature properties.


58-58: Added null fallback for text rendering

Using fieldValue ?? '' ensures we always render a valid string, preventing rendering issues.

packages/connect-examples/expo-example/src/views/FirmwareScreen/ExportDeviceInfo.tsx (8)

2-2: Great addition of explicit type import.

Adding the Features type import improves type safety throughout the component.


8-9: Uncommented first array entry properly.

Fixed the previously commented-out device_id and label fields in deviceInfoKeys.


28-62: Good expansion of device SE info keys.

Adding the type fields (onekey_se0X_type) to each SE device array improves the completeness of exported device information.


82-82: Simplified device context usage.

Removing reliance on separate onekeyFeatures object streamlines the code.


84-84: Improved type safety with keyof operator.

The getFieldValue function now accepts keys strictly of type keyof Features, preventing potential runtime errors.


96-96: Simplified API call.

Updated getDeviceBasicInfo call to only use features parameter, aligning with the unified feature handling approach.


134-135: Added necessary type casting.

Proper type casting ensures type safety when accessing dynamic properties from the features object.


147-148: Consistent type casting approach.

Maintaining the same type casting pattern for SE info keys as used for device info keys.

packages/core/src/device/utils.ts (2)

1-3: Good imports for feature parameter building.

Importing the necessary types for feature parameter cherry-picking.


4-25:

✅ Verification successful

Well-structured feature parameter builder.

The cherryPickFeaturesParams function cleanly builds feature request parameters based on the factory flag:

  • Always includes basic targets (status, hw, fw, bt) and types (version, specific)
  • Conditionally adds advanced targets (SE devices) and types (build_id, hash) when in factory mode

This supports the new protocol's selective feature request approach.


🏁 Script executed:

#!/bin/bash
# Check usage of this function to verify proper integration
rg -A 3 "cherryPickFeaturesParams" --type ts

Length of output: 2614


🏁 Script executed:

#!/bin/bash
# Locate the definition of IFeaturesType
rg -n "IFeaturesType" --type ts

Length of output: 291


🏁 Script executed:

#!/bin/bash
# Show full IFeaturesType definition
rg -A10 -B2 "export interface IFeaturesType" --type ts packages/core/src/device/Device.ts

Length of output: 345


✅ Approve cherryPickFeaturesParams integration

The function correctly builds feature request parameters:

  • Always includes basic targets: status, hw, fw, bt
  • Always includes basic types: version, specific
  • Adds SE targets (se1se4) and extra types (build_id, hash) when factory = true

We verified its usage in Device.ts, GetOnekeyFeatures.ts, and uploadFirmware.ts. No issues found.

packages/core/src/utils/deviceInfoUtils.ts (4)

6-6: Good import of centralized utility functions.

Importing the helper functions from onekeyInfoUtils centralizes feature extraction logic.


16-17: Improved hardware info extraction.

Refactored to use the centralized getHardwareInfoFromFeatures helper instead of direct property access, supporting both legacy and new feature formats.


86-88: Simplified BLE name retrieval.

Refactored to use getFirmwareInfoFromFeatures, which handles both old and new property formats consistently.


95-96: Streamlined device UUID extraction.

Using the centralized helper function improves maintainability and ensures consistent handling of both old and new serial number formats.

packages/core/src/api/device/DeviceUpdateReboot.ts (4)

1-3: Good imports for reboot functionality.

Added OneKeyRebootType enum and switched to FirmwareUpdateBaseMethod for centralized reboot handling.


6-6: Improved class inheritance.

Extending FirmwareUpdateBaseMethod gives access to centralized firmware update utilities.


10-10: Better UI control with BOOTLOADER restriction.

Adding UI_REQUEST.BOOTLOADER to notAllowDeviceMode prevents using this method when device is already in bootloader mode.


14-14: Simplified reboot implementation.

Using the base class's reboot method with OneKeyRebootType.BootLoader parameter:

  • Supports different message versions
  • Provides better error handling
  • Follows the unified device reboot pattern

This is more robust than directly calling device commands.

packages/connect-examples/expo-example/src/views/FirmwareScreen/index.tsx (1)

402-405: Check merge order of feature objects

You spread features first and onekeyFeatures second, so any overlapping keys from OneKey will silently override the original features. This is probably fine, but please double-check that this is the intended precedence – especially for critical flags such as bootloader_mode.

packages/core/src/utils/deviceVersionUtils.ts (1)

1-58: Looks good

Refactor to getFirmwareInfoFromFeatures removes duplication and increases consistency.

packages/core/src/api/FirmwareUpdateV3.ts (1)

388-395: Ensure every device firmware supports StartSession

Older firmware used Initialize. Swapping to StartSession unconditionally may break reconnect on legacy devices. Consider a feature-based fallback.

await Promise.race([
  typedCall(supportsStartSession ? 'StartSession' : 'Initialize', 'Features', {}),
  // …
]);
packages/core/src/device/Device.ts (1)

381-384: Check for undefined before asking for message version

getSupportMessageVersion(this.features) receives undefined on the very first call to initialize, which may break inside that helper. Guard with a null-check or default.

Would you confirm that getSupportMessageVersion handles undefined safely? If not, wrap the call:

const { messageVersion } = getSupportMessageVersion(this.features ?? ({} as any));
packages/core/src/utils/onekeyInfoUtils.ts (1)

148-170: Guard empty hardware version

oldHardwareVersion is set to an empty string, then passed into fixVersion.
If fixVersion('') returns "0.0.0" it may overwrite a valid new-protocol version with a bogus default.

Consider:

const rawVersion = newHardwareVersion ?? oldHardwareVersion;
hardwareVersion: rawVersion ? fixVersion(rawVersion) : undefined,

@@ -59,7 +59,7 @@ export default class TransportManager {
} else {
await this.transport.init(HttpLogger);
}
Log.debug('Configuring transports');
Log.debug('Configuring transports', this.messageVersion);
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Enhanced logging with message version information.

Logging the message version provides helpful context for debugging transport configuration issues.

Use the class name instead of this in static methods:

-      Log.debug('Configuring transports', this.messageVersion);
+      Log.debug('Configuring transports', TransportManager.messageVersion);
📝 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
Log.debug('Configuring transports', this.messageVersion);
Log.debug('Configuring transports', TransportManager.messageVersion);
🧰 Tools
🪛 Biome (1.9.4)

[error] 62-62: Using this in a static context can be confusing.

this refers to the class.
Unsafe fix: Use the class name instead.

(lint/complexity/noThisInStatic)

🤖 Prompt for AI Agents (early access)
In packages/core/src/data-manager/TransportManager.ts at line 62, the logging statement uses 'this.messageVersion' inside a static method, which is incorrect. Replace 'this.messageVersion' with the class name followed by '.messageVersion' to correctly reference the static property and improve logging context.

@@ -74,6 +74,7 @@ export default class TransportManager {
Log.debug(`Begin reconfiguring transports`);
const { messageVersion, messages } = getSupportMessageVersion(features);

console.error('caikaisheng reconfigure', messageVersion);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove debugging console.error statement.

This appears to be leftover debugging code that includes a developer identifier.

-    console.error('caikaisheng reconfigure', messageVersion);

Or if this message is needed for debugging, use the standard logging approach:

-    console.error('caikaisheng reconfigure', messageVersion);
+    Log.debug(`Reconfiguring message version: ${messageVersion}`);
🤖 Prompt for AI Agents (early access)
In packages/core/src/data-manager/TransportManager.ts at line 77, remove the console.error statement used for debugging that includes a developer identifier. If logging this message is necessary, replace it with the project's standard logging mechanism instead of using console.error directly.

Comment on lines +1 to +3
[submodule "submodules/onekey-protocol"]
path = submodules/onekey-protocol
url = git@github.com:OneKeyHQ/onekey-protocol.git
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

New onekey-protocol submodule replaces firmware submodule

The change replaces the old firmware submodule with the new onekey-protocol submodule. This aligns with the protocol update mentioned in the PR.

However, SSH URLs may cause issues in some CI environments. Consider using HTTPS URL instead.


🏁 Script executed:

#!/bin/bash
# Check if the submodule exists and is properly configured
git submodule status | grep onekey-protocol

Length of output: 114


Update .gitmodules submodule URL for CI compatibility

The old firmware submodule is now replaced by submodules/onekey-protocol. That aligns with the protocol update in this PR.

However, the SSH URL in .gitmodules can fail in some CI environments. Please switch:

  • From: git@github.com:OneKeyHQ/onekey-protocol.git
  • To: https://github.com/OneKeyHQ/onekey-protocol.git

.fix in .gitmodules at lines 1–3.

🤖 Prompt for AI Agents (early access)
In the .gitmodules file at lines 1 to 3, the submodule URL uses an SSH format which can cause issues in some CI environments. Change the URL from the SSH format git@github.com:OneKeyHQ/onekey-protocol.git to the HTTPS format https://github.com/OneKeyHQ/onekey-protocol.git to ensure compatibility.

Comment on lines +81 to +82
// TODO: 打补丁
export type OnekeyFeatures = PROTO.Features;
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

OnekeyFeatures type now points to unified Features type

The change updates OnekeyFeatures to use the unified Features type, which simplifies type management.

However, the TODO comment in Chinese ("打补丁" meaning "apply patch") should be in English for consistency, and it needs to be more specific about what patch is needed.

-// TODO: 打补丁
+// TODO: Apply patch to handle legacy OnekeyFeatures compatibility
📝 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: 打补丁
export type OnekeyFeatures = PROTO.Features;
// TODO: Apply patch to handle legacy OnekeyFeatures compatibility
export type OnekeyFeatures = PROTO.Features;
🤖 Prompt for AI Agents (early access)
In packages/core/src/types/device.ts at lines 81 to 82, replace the TODO comment "打补丁" with a clear and specific English comment explaining what patch or fix is intended. This improves code clarity and maintains consistency in language for all developers.

@@ -111,17 +112,19 @@ export default class HttpTransport {
this.Log.debug('call-', ' name: ', name, ' data: ', data);
}

console.error('caikaisheng call', name, data);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove console debugging statements.

These console.error logs contain personal identifiers and expose internal data. Replace with structured logging if needed.

-    console.error('caikaisheng call', name, data);
+    // Consider using this.Log for consistent logging if needed

-    console.error('caikaisheng call resData', jsonData);
+    // Consider using this.Log for consistent logging if needed

Also applies to: 127-127

🤖 Prompt for AI Agents (early access)
In packages/hd-transport-http/src/index.ts at lines 115 and 127, remove the console.error debugging statements as they expose personal identifiers and internal data. Replace these with structured logging using the existing logging framework or a secure logger that masks or omits sensitive information, ensuring no personal data is logged directly.

Comment on lines +207 to +250
async reboot(rebootType: OneKeyRebootType) {
const typedCall = this.device.getCommands().typedCall.bind(this.device.getCommands());
const { messageVersion } = getSupportMessageVersion(this.device.features);
// TODO: fix it
if (messageVersion === 'latest') {
try {
return await typedCall('OneKeyReboot', 'Success', {
reboot_type: rebootType,
});
} catch (e) {
Log.error('FirmwareUpdateBaseMethod [reboot] OneKeyReboot failed: ', e);
return {
type: 'Success',
message: 'reboot success',
};
}
}

switch (rebootType) {
case OneKeyRebootType.BootLoader:
return typedCall('DeviceBackToBoot', 'Success', {
reboot_type: OneKeyRebootType.BootLoader,
});
// On Touch devices, messsage code 904 is RebootToBoardloader
// so BininOutMessageSE message code 904 is used here
case OneKeyRebootType.Boardloader:
return typedCall('BixinOutMessageSE', 'Success');
case OneKeyRebootType.Normal: {
try {
return await typedCall('OneKeyReboot', 'Success', {
reboot_type: OneKeyRebootType.Normal,
});
} catch (e) {
Log.error('FirmwareUpdateBaseMethod [reboot] OneKeyReboot failed: ', e);
return {
type: 'Success',
message: 'reboot success',
};
}
}
default:
throw new Error('Invalid reboot type');
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Do not swallow reboot errors

reboot() catches every failure and returns a fake “success”, masking real issues and forcing callers to guess. Let errors propagate or return a discriminated union.

-      } catch (e) {
-        Log.error('FirmwareUpdateBaseMethod [reboot] OneKeyReboot failed: ', e);
-        return {
-          type: 'Success',
-          message: 'reboot success',
-        };
-      }
+      } catch (e) {
+        Log.error('FirmwareUpdateBaseMethod [reboot] OneKeyReboot failed: ', e);
+        throw e;
+      }
🤖 Prompt for AI Agents (early access)
In packages/core/src/api/firmware/FirmwareUpdateBaseMethod.ts between lines 207 and 250, the reboot method catches all errors and returns a fake success response, which hides real failures. To fix this, remove the catch blocks that swallow errors and instead let the errors propagate naturally or refactor the method to return a discriminated union that clearly indicates success or failure, ensuring callers can handle errors properly.

};

export const fixFeaturesBetweenProtocol = (oldFeatures: Features, features: Features) => {
console.log('======> fixFeaturesBetweenProtocol', oldFeatures);
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Remove hard-coded console.log

console.log in shared utilities clutters production logs and leaks internal objects.
Pipe debug output through the project logger or guard it with an env flag.

-  console.log('======> fixFeaturesBetweenProtocol', oldFeatures);
+  // logger.debug('fixFeaturesBetweenProtocol', oldFeatures);
📝 Committable suggestion

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

Suggested change
console.log('======> fixFeaturesBetweenProtocol', oldFeatures);
- console.log('======> fixFeaturesBetweenProtocol', oldFeatures);
+ // logger.debug('fixFeaturesBetweenProtocol', oldFeatures);
🤖 Prompt for AI Agents (early access)
In packages/core/src/utils/onekeyInfoUtils.ts at line 304, replace the hard-coded console.log statement with a call to the project’s logger utility or wrap it in a conditional check that only logs when a specific environment debug flag is enabled. This prevents cluttering production logs and leaking internal data.

Comment on lines 283 to 299
const oldLable = (features as any)?.label;
const newLable = features?.ok_dev_info_resp?.status?.lable;

const oldInitState = (features as any)?.init_state;
const newInitState = features?.ok_dev_info_resp?.status?.init_states;

const oldLanguage = (features as any)?.language;
const newLanguage = features?.ok_dev_info_resp?.status?.language;

const oldPassphraseProtection = (features as any)?.passphrase_protection;
const newPassphraseProtection = features?.ok_dev_info_resp?.status?.passphrase_protection;

return {
label: oldLable || newLable,
init_state: oldInitState || newInitState,
language: oldLanguage || newLanguage,
passphrase_protection: oldPassphraseProtection || newPassphraseProtection,
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo “Lable” → “Label” and align new-protocol key

The helper misspells both the temporary variables and the key coming from the new protocol.
As written, newLable will always be undefined and the return object will fall back to oldLable, masking data for new-firmware devices.

-const oldLable = (features as any)?.label;
-const newLable = features?.ok_dev_info_resp?.status?.lable;
+const oldLabel = (features as any)?.label;
+// new protocol still uses “label”
+const newLabel = features?.ok_dev_info_resp?.status?.label;
...
-  return {
-    label: oldLable || newLable,
+  return {
+    label: oldLabel || newLabel,
📝 Committable suggestion

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

Suggested change
const oldLable = (features as any)?.label;
const newLable = features?.ok_dev_info_resp?.status?.lable;
const oldInitState = (features as any)?.init_state;
const newInitState = features?.ok_dev_info_resp?.status?.init_states;
const oldLanguage = (features as any)?.language;
const newLanguage = features?.ok_dev_info_resp?.status?.language;
const oldPassphraseProtection = (features as any)?.passphrase_protection;
const newPassphraseProtection = features?.ok_dev_info_resp?.status?.passphrase_protection;
return {
label: oldLable || newLable,
init_state: oldInitState || newInitState,
language: oldLanguage || newLanguage,
passphrase_protection: oldPassphraseProtection || newPassphraseProtection,
const oldLabel = (features as any)?.label;
// new protocol still uses “label”
const newLabel = features?.ok_dev_info_resp?.status?.label;
const oldInitState = (features as any)?.init_state;
const newInitState = features?.ok_dev_info_resp?.status?.init_states;
const oldLanguage = (features as any)?.language;
const newLanguage = features?.ok_dev_info_resp?.status?.language;
const oldPassphraseProtection = (features as any)?.passphrase_protection;
const newPassphraseProtection = features?.ok_dev_info_resp?.status?.passphrase_protection;
return {
label: oldLabel || newLabel,
init_state: oldInitState || newInitState,
language: oldLanguage || newLanguage,
passphrase_protection: oldPassphraseProtection || newPassphraseProtection,
};
🤖 Prompt for AI Agents (early access)
In packages/core/src/utils/onekeyInfoUtils.ts lines 283 to 299, fix the typo by renaming all instances of "Lable" to "Label" in both the temporary variables and the new protocol key. Also, correct the new protocol key from "lable" to "label" to properly access the data. This ensures the newLabel variable is correctly assigned and used in the return object, preventing fallback to oldLabel when new firmware data is present.

Comment on lines 178 to 186
isEnteredManuallyBoot(features: Features) {
const deviceType = getDeviceType(features);
const isMini = deviceType === EDeviceType.Mini;
const bootloaderVersion = getDeviceBootloaderVersion(features).join('.');
const isBoot183ClassicUpBle =
this.params.updateType === 'firmware' &&
deviceType === EDeviceType.Classic &&
features.bootloader_version === '1.8.3';
bootloaderVersion === '1.8.3';
return isMini || isBoot183ClassicUpBle;
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Minor: join on already-joined string

getDeviceBootloaderVersion(features).join('.') returns a string, yet you join it again when comparing:

const bootloaderVersion = getDeviceBootloaderVersion(features).join('.');
...
bootloaderVersion === '1.8.3'

join('.') is executed twice each polling cycle. Cache it once or compare the array directly.

🤖 Prompt for AI Agents (early access)
In packages/core/src/api/FirmwareUpdateV2.ts around lines 178 to 186, the code calls join('.') on the result of getDeviceBootloaderVersion(features) twice per polling cycle, which is inefficient. To fix this, call getDeviceBootloaderVersion(features) once, store the resulting array in a variable, then either join it once and reuse the joined string for comparison or compare the array directly without joining multiple times.

Comment on lines 140 to +160
};

// BenchmarkListNames
export type BenchmarkListNames = {};

// BenchmarkNames
export type BenchmarkNames = {
names: string[];
};

// BenchmarkRun
export type BenchmarkRun = {
name?: string;
};

// BenchmarkResult
export type BenchmarkResult = {
value?: string;
unit?: string;
};

Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Avoid banned {} type in generated declarations

Biome flags the empty-object type eight times (example below).
Either replace with Record<string, never> or suppress the rule for generated files:

// @ts-expect-error generated code – intentional empty object
export type BenchmarkListNames = Record<string, never>;

Alternatively, add /* biome-ignore lint/complexity/noBannedTypes */ above each occurrence and document that this file is auto-generated.

🧰 Tools
🪛 Biome (1.9.4)

[error] 143-143: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

🤖 Prompt for AI Agents (early access)
In packages/hd-transport/src/types/messages.ts between lines 140 and 160, the empty object type {} is used, which is banned by Biome lint rules. Replace each occurrence of {} with Record<string, never> to explicitly represent an empty object type, or alternatively, add a comment above each such type declaration to suppress the lint rule using /* biome-ignore lint/complexity/noBannedTypes */ and document that the file is auto-generated.

@wabicai wabicai force-pushed the feat/new-protobuf branch from a6e6590 to 586371c Compare May 7, 2025 13:27
@wabicai wabicai force-pushed the feat/new-protobuf branch from 586371c to 46d9348 Compare May 8, 2025 06:59
Copy link

Warning

Review the following alerts detected in dependencies.

According to your organization's Security Policy, it is recommended to resolve "Warn" alerts. Learn more about Socket for GitHub.

Action Severity Alert (click for details)
Warn Critical
elliptic@6.5.4 has a Critical CVE.

CVE: GHSA-vjh7-7g9h-fjfh Elliptic's private key extraction in ECDSA upon signing a malformed input (e.g. a string) (CRITICAL)

Affected versions: <= 6.6.0

Patched version: 6.6.1

From: packages/connect-examples/expo-example/package.jsonnpm/elliptic@6.5.4

ℹ Read more on: This package | This alert | What is a critical CVE?

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

Suggestion: Remove or replace dependencies that include known critical CVEs. Consumers can use dependency overrides or npm audit fix --force to remove vulnerable dependencies.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/elliptic@6.5.4. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn Critical
elliptic@6.5.5 has a Critical CVE.

CVE: GHSA-vjh7-7g9h-fjfh Elliptic's private key extraction in ECDSA upon signing a malformed input (e.g. a string) (CRITICAL)

Affected versions: <= 6.6.0

Patched version: 6.6.1

From: packages/connect-examples/expo-example/yarn.locknpm/browserify-sign@4.2.3npm/elliptic@6.5.5

ℹ Read more on: This package | This alert | What is a critical CVE?

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

Suggestion: Remove or replace dependencies that include known critical CVEs. Consumers can use dependency overrides or npm audit fix --force to remove vulnerable dependencies.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/elliptic@6.5.5. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn High
@polkadot/util-crypto@13.1.1 has Obfuscated code.

Confidence: 0.91

Location: Package overview

From: packages/connect-examples/expo-example/package.jsonnpm/@polkadot/util-crypto@13.1.1

ℹ Read more on: This package | This alert | What is obfuscated code?

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

Suggestion: Packages should not obfuscate their code. Consider not using packages with obfuscated code.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/@polkadot/util-crypto@13.1.1. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn High
es5-ext@0.10.64 is Protestware or potentially unwanted behavior.

Note: This package prints a protestware console message on install regarding Ukraine for users with Russian language locale

From: packages/connect-examples/expo-example/yarn.locknpm/es5-ext@0.10.64

ℹ Read more on: This package | This alert | What is protestware?

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

Suggestion: Consider that consuming this package may come along with functionality unrelated to its primary purpose.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/es5-ext@0.10.64. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

Warn High
es5-ext@0.10.64 is Protestware or potentially unwanted behavior.

Note: The script attempts to run a local post-install script, which could potentially contain malicious code. The error handling suggests that it is designed to fail silently, which is a common tactic in malicious scripts.

From: packages/connect-examples/expo-example/yarn.locknpm/es5-ext@0.10.64

ℹ Read more on: This package | This alert | What is protestware?

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

Suggestion: Consider that consuming this package may come along with functionality unrelated to its primary purpose.

Mark the package as acceptable risk. To ignore this alert only in this pull request, reply with the comment @SocketSecurity ignore npm/es5-ext@0.10.64. You can also ignore all packages with @SocketSecurity ignore-all. To ignore an alert for all future pull requests, use Socket's Dashboard to change the triage state of this alert.

View full report

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