Skip to content

Conversation

@Adityarya11
Copy link
Contributor

Description:
This PR improves the developer experience (DX) for Hbar instantiation by adding explicit factory methods for various Hbar units. This removes the need for the verbose Hbar.of(value, HbarUnit.UNIT) syntax when handling specific denominations.

  • Add from_microbars, from_millibars, from_hbars, from_kilobars, from_megabars, and from_gigabars factory methods to Hbar class.
  • Add unit tests to verify the new factory methods match existing constructor behavior.
  • Update examples/hbar.py to demonstrate the new helper methods.

Related issue(s):

Fixes #1272


Checklist

  • Documented (Code comments, README, etc.)
  • Tested (unit, integration, etc.)

@codecov
Copy link

codecov bot commented Dec 31, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #1277      +/-   ##
==========================================
+ Coverage   91.79%   91.80%   +0.01%     
==========================================
  Files         139      139              
  Lines        8466     8484      +18     
==========================================
+ Hits         7771     7789      +18     
  Misses        695      695              
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@coderabbitai
Copy link

coderabbitai bot commented Dec 31, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Adds six Hbar classmethods — from_microbars(), from_millibars(), from_hbars(), from_kilobars(), from_megabars(), from_gigabars() — plus unit tests, an example demonstrating the helpers, and a changelog entry.

Changes

Cohort / File(s) Summary
Core Implementation
src/hiero_sdk_python/hbar.py
Added six @classmethod factory constructors (from_microbars, from_millibars, from_hbars, from_kilobars, from_megabars, from_gigabars) accepting amount (`int
Testing
tests/unit/hbar_test.py
Added test_factory_methods() validating all six new factories and their conversions to tinybars/hbars; minor formatting change (extra blank line) in test_comparison.
Examples & Changelog
examples/hbar.py, CHANGELOG.md
Added demonstrate_factory_methods() and call from run_example() in examples/hbar.py; updated CHANGELOG.md with an Unreleased → Added entry documenting the six new factory methods.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks

✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately summarizes the main change: adding factory methods to the Hbar class for convenient instantiation from different units.
Description check ✅ Passed The PR description clearly relates to the changeset, explaining the rationale for adding factory methods and detailing what was added, tested, and updated.
Linked Issues check ✅ Passed The PR fully addresses issue #1272 requirements: implements factory methods for all Hbar units, includes unit tests for validation, updates examples, and follows project conventions with a changelog entry.
Out of Scope Changes check ✅ Passed All changes are directly within scope: factory method implementations for Hbar, example updates demonstrating the methods, unit tests validating behavior, and a minor formatting change in existing tests.
Docstring Coverage ✅ Passed Docstring coverage is 92.31% which is sufficient. The required threshold is 80.00%.

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b924209 and 7c190b3.

📒 Files selected for processing (1)
  • CHANGELOG.md
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: build-and-test (3.13)
  • GitHub Check: build-and-test (3.10)
  • GitHub Check: build-and-test (3.11)
  • GitHub Check: build-and-test (3.12)
  • GitHub Check: run-examples
  • GitHub Check: StepSecurity Harden-Runner
🔇 Additional comments (1)
CHANGELOG.md (1)

76-76: ✓ Changelog entry is well-formatted and accurate.

The entry correctly documents the six new factory methods in the appropriate section with proper formatting, clear description, and a correctly linked issue reference. It aligns with the other entries in the file and provides all necessary information about the feature addition.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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: 2

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0caa232 and 3f0040d.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • examples/hbar.py
  • src/hiero_sdk_python/hbar.py
  • tests/unit/hbar_test.py
🧰 Additional context used
📓 Path-based instructions (2)
tests/unit/**/*

⚙️ CodeRabbit configuration file

tests/unit/**/*: You are acting as a senior maintainer reviewing unit tests for the hiero-sdk-python project. Your goal is to ensure tests are extensive, deterministic, and protect against breaking changes.

CRITICAL PRINCIPLES - Tests Must Fail Loudly & Deterministically:

  • Tests must provide useful error messages when they fail for future debugging.
  • No print() statements - use assertions with descriptive messages.
  • No timing-dependent or unseeded random assertions.
  • No network calls or external dependencies (unit tests are isolated).
  • No unjustified TODOs or skipped tests without tracking issues.

PRIORITY 1 - Protect Against Breaking Changes:

  • Assert public attributes exist (e.g., assert hasattr(obj, 'account_id')).
  • Assert return types where relevant (e.g., assert isinstance(result, AccountId)).
  • Assert fluent setters return self (e.g., assert tx.set_memo("test") is tx).
  • Assert backward-compatible defaults are maintained.
  • If a breaking change is introduced, tests must assert deprecation behavior and test old behavior until removal.

PRIORITY 2 - Constructor & Setter Behavior:

  • Test constructor behavior with valid inputs, edge cases, and invalid inputs.
  • Test setter behavior including method chaining (fluent interface).
  • Verify that setters validate input and raise appropriate exceptions.
  • Test that getters return expected values after construction/setting.

PRIORITY 3 - Comprehensive Coverage:

  • Unit tests should be extensive - test even if we don't expect users to use it currently.
  • Cover happy paths AND unhappy paths/edge cases.
  • Test boundary conditions, null/None values, empty collections, etc.
  • Avoid brittle ordering assertions unless order is part of the contract.

PRIORITY 4 - No Mocks for Non-Existent Modules:

  • All imports must reference actual SDK modules - no hallucinated paths.
  • Validate import paths against the actual src/hiero_sdk_python structure.
  • Mocks should only be used for external de...

Files:

  • tests/unit/hbar_test.py
examples/**/*

⚙️ CodeRabbit configuration file

examples/**/*: You are acting as a senior maintainer reviewing SDK examples. Your goal is to ensure examples work verbatim for users who copy-paste them.

Priority 1 - Correctness:

  • Verify transaction lifecycle chain (construction -> freeze_with -> sign -> execute).
  • Ensure freeze_with(client) is called BEFORE signing.
  • Validate that methods referenced actually exist in the hiero_sdk_python codebase.
  • Ensure response validation checks receipt.status against ResponseCode enums (e.g., ResponseCode.SUCCESS).

Priority 2 - Transaction Lifecycle:

  • Check method chaining logic.
  • Verify correct signing order (especially for multi-sig).
  • Ensure explicit .execute(client) calls.
  • Verify response property extraction (e.g., using .token_id, .account_id, .serial_numbers).
  • Ensure error handling uses ResponseCode(receipt.status).name for clarity.

Priority 3 - Naming & Clarity:

  • Enforce role-based naming: operator_id/_key, treasury_account_id/_key, receiver_id/_key.
  • Use _id suffix for AccountId and _key suffix for PrivateKey variables.
  • Validate negative examples explicitly check for failure codes (e.g., TOKEN_HAS_NO_PAUSE_KEY).
  • Ensure logical top-to-bottom flow without ambiguity.

Priority 4 - Consistency:

  • Verify standard patterns: def main(), if __name__ == "__main__":, load_dotenv().
  • IMPORT RULES:
    1. Accept both top-level imports (e.g., from hiero_sdk_python import PrivateKey) and fully qualified imports (e.g., from hiero_sdk_python.crypto.private_key import PrivateKey).
    2. STRICTLY validate that the import path actually exists in the project structure. Compare against other files in /examples or your knowledge of the SDK file tree.
    3. Flag hallucinations immediately (e.g., hiero_sdk_python.keys does not exist).
  • Check for try-except blocks with sys.exit(1) for critical failures.

Priority 5 - User Experience:

  • Ensure comments explain SDK usage patterns (for users,...

Files:

  • examples/hbar.py
🧬 Code graph analysis (3)
tests/unit/hbar_test.py (1)
src/hiero_sdk_python/hbar.py (9)
  • Hbar (18-207)
  • from_microbars (112-116)
  • to_tinybars (63-65)
  • from_millibars (119-123)
  • from_hbars (126-130)
  • from_kilobars (133-137)
  • to_hbars (67-71)
  • from_megabars (140-144)
  • from_gigabars (147-151)
examples/hbar.py (1)
src/hiero_sdk_python/hbar.py (4)
  • Hbar (18-207)
  • from_gigabars (147-151)
  • from_millibars (119-123)
  • from_hbars (126-130)
src/hiero_sdk_python/hbar.py (1)
src/hiero_sdk_python/hbar_unit.py (1)
  • HbarUnit (3-47)
🪛 Ruff (0.14.10)
src/hiero_sdk_python/hbar.py

112-112: Use X | Y for type annotations

Convert to X | Y

(UP007)


119-119: Use X | Y for type annotations

Convert to X | Y

(UP007)


126-126: Use X | Y for type annotations

Convert to X | Y

(UP007)


133-133: Use X | Y for type annotations

Convert to X | Y

(UP007)


140-140: Use X | Y for type annotations

Convert to X | Y

(UP007)


147-147: Use X | Y for type annotations

Convert to X | Y

(UP007)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: run-examples
  • GitHub Check: build-and-test (3.11)
  • GitHub Check: build-and-test (3.10)
  • GitHub Check: build-and-test (3.12)
  • GitHub Check: build-and-test (3.13)
  • GitHub Check: StepSecurity Harden-Runner
🔇 Additional comments (3)
CHANGELOG.md (1)

74-74: LGTM!

The changelog entry accurately documents all six factory methods and correctly links to the related issue.

examples/hbar.py (1)

163-163: LGTM!

The new helper function is appropriately integrated at the end of the example flow.

src/hiero_sdk_python/hbar.py (1)

111-151: LGTM! Consistent and clean implementation.

All six factory methods follow an identical, straightforward pattern:

  • Delegate to the constructor with the appropriate HbarUnit
  • Accept flexible input types (int, float, Decimal)
  • Include docstrings
  • Return the correct type

This implementation ensures consistent behavior and maintainability.

@manishdait
Copy link
Contributor

@Adityarya11 nice work! The PR looks good to me 👍

manishdait
manishdait previously approved these changes Dec 31, 2025
Copy link
Contributor

@exploreriii exploreriii left a comment

Choose a reason for hiding this comment

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

added my 2 cents but i think it is technically good

@github-actions
Copy link

Hi, this is MergeConflictBot.
Your pull request cannot be merged because it contains merge conflicts.

Please resolve these conflicts locally and push the changes.

To assist you, please read:

Thank you for contributing!

@exploreriii
Copy link
Contributor

Hi @Adityarya11 let me know when this is ready to review

@Adityarya11 Adityarya11 force-pushed the feat/improve-hbar-dx#1272 branch from 0d9fef6 to f9a9676 Compare January 1, 2026 15:10
@Adityarya11 Adityarya11 marked this pull request as ready for review January 1, 2026 15:25
Copilot AI review requested due to automatic review settings January 1, 2026 15:25
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR enhances the developer experience for the Hbar class by introducing convenient factory methods for creating Hbar instances with specific unit denominations, eliminating the need for the more verbose Hbar(value, unit=HbarUnit.UNIT) syntax.

Key Changes:

  • Added six new factory methods: from_microbars(), from_millibars(), from_hbars(), from_kilobars(), from_megabars(), and from_gigabars()
  • Comprehensive unit tests verify correctness of the new factory methods across various input types (int, float, Decimal) and edge cases (zero, negative values)
  • Updated example code to demonstrate the new factory methods

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.

File Description
src/hiero_sdk_python/hbar.py Adds six new factory class methods for creating Hbar instances from different unit denominations (microbars through gigabars)
tests/unit/hbar_test.py Adds comprehensive test function test_factory_methods() with assertions validating the new factory methods against expected tinybar conversions and constructor equivalence
examples/hbar.py Adds demonstrate_factory_methods() function showcasing usage of the new factory methods and integrates it into the example execution flow
CHANGELOG.md Documents the addition of the new factory methods in the "Added" section with appropriate issue reference

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

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: 1

♻️ Duplicate comments (1)
examples/hbar.py (1)

9-27: Factory methods demonstration is functional and clear.

The inline comments effectively explain each factory method's conversion, addressing previous feedback. The example runs correctly and follows the established pattern.

📚 Consider demonstrating all six factory methods

For completeness, consider adding the remaining three factory methods (from_microbars, from_kilobars, from_megabars) so users have a comprehensive reference:

 def demonstrate_factory_methods():
     """
     Demonstrates creating Hbar values using the convenient factory methods.
     """
     print("\n=== Creating Hbar Using Factory Methods ===")

+    # Creates an Hbar object representing 1000 Microbars (0.00001 ℏ)
+    h_micro = Hbar.from_microbars(1000)
+    
     # Creates an Hbar object representing 1 Gigabar (1,000,000,000 ℏ)
     h_giga = Hbar.from_gigabars(1)
     
     # Creates an Hbar object representing 500 Millibars (0.5 ℏ)
     h_milli = Hbar.from_millibars(500)

     # Creates an Hbar object representing 10.5 Hbars (10.5 ℏ)
     h_standard = Hbar.from_hbars(10.5)
+    
+    # Creates an Hbar object representing 2 Kilobars (2,000 ℏ)
+    h_kilo = Hbar.from_kilobars(2)
+    
+    # Creates an Hbar object representing 0.5 Megabars (500,000 ℏ)
+    h_mega = Hbar.from_megabars(0.5)

+    print(f"Hbar.from_microbars(1000): {h_micro}")
     print(f"Hbar.from_gigabars(1): {h_giga}")
     print(f"Hbar.from_millibars(500): {h_milli}")
     print(f"Hbar.from_hbars(10.5): {h_standard}")
+    print(f"Hbar.from_kilobars(2): {h_kilo}")
+    print(f"Hbar.from_megabars(0.5): {h_mega}")

This provides users with complete coverage of all factory methods in one place.

Based on coding guidelines for examples.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a4545b0 and b924209.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • examples/hbar.py
  • src/hiero_sdk_python/hbar.py
  • tests/unit/hbar_test.py
🧰 Additional context used
📓 Path-based instructions (2)
examples/**/*

⚙️ CodeRabbit configuration file

examples/**/*: You are acting as a senior maintainer reviewing SDK examples. Your goal is to ensure examples work verbatim for users who copy-paste them.

Priority 1 - Correctness:

  • Verify transaction lifecycle chain (construction -> freeze_with -> sign -> execute).
  • Ensure freeze_with(client) is called BEFORE signing.
  • Validate that methods referenced actually exist in the hiero_sdk_python codebase.
  • Ensure response validation checks receipt.status against ResponseCode enums (e.g., ResponseCode.SUCCESS).

Priority 2 - Transaction Lifecycle:

  • Check method chaining logic.
  • Verify correct signing order (especially for multi-sig).
  • Ensure explicit .execute(client) calls.
  • Verify response property extraction (e.g., using .token_id, .account_id, .serial_numbers).
  • Ensure error handling uses ResponseCode(receipt.status).name for clarity.

Priority 3 - Naming & Clarity:

  • Enforce role-based naming: operator_id/_key, treasury_account_id/_key, receiver_id/_key.
  • Use _id suffix for AccountId and _key suffix for PrivateKey variables.
  • Validate negative examples explicitly check for failure codes (e.g., TOKEN_HAS_NO_PAUSE_KEY).
  • Ensure logical top-to-bottom flow without ambiguity.

Priority 4 - Consistency:

  • Verify standard patterns: def main(), if __name__ == "__main__":, load_dotenv().
  • IMPORT RULES:
    1. Accept both top-level imports (e.g., from hiero_sdk_python import PrivateKey) and fully qualified imports (e.g., from hiero_sdk_python.crypto.private_key import PrivateKey).
    2. STRICTLY validate that the import path actually exists in the project structure. Compare against other files in /examples or your knowledge of the SDK file tree.
    3. Flag hallucinations immediately (e.g., hiero_sdk_python.keys does not exist).
  • Check for try-except blocks with sys.exit(1) for critical failures.

Priority 5 - User Experience:

  • Ensure comments explain SDK usage patterns (for users,...

Files:

  • examples/hbar.py
tests/unit/**/*

⚙️ CodeRabbit configuration file

tests/unit/**/*: You are acting as a senior maintainer reviewing unit tests for the hiero-sdk-python project. Your goal is to ensure tests are extensive, deterministic, and protect against breaking changes.

CRITICAL PRINCIPLES - Tests Must Fail Loudly & Deterministically:

  • Tests must provide useful error messages when they fail for future debugging.
  • No print() statements - use assertions with descriptive messages.
  • No timing-dependent or unseeded random assertions.
  • No network calls or external dependencies (unit tests are isolated).
  • No unjustified TODOs or skipped tests without tracking issues.

PRIORITY 1 - Protect Against Breaking Changes:

  • Assert public attributes exist (e.g., assert hasattr(obj, 'account_id')).
  • Assert return types where relevant (e.g., assert isinstance(result, AccountId)).
  • Assert fluent setters return self (e.g., assert tx.set_memo("test") is tx).
  • Assert backward-compatible defaults are maintained.
  • If a breaking change is introduced, tests must assert deprecation behavior and test old behavior until removal.

PRIORITY 2 - Constructor & Setter Behavior:

  • Test constructor behavior with valid inputs, edge cases, and invalid inputs.
  • Test setter behavior including method chaining (fluent interface).
  • Verify that setters validate input and raise appropriate exceptions.
  • Test that getters return expected values after construction/setting.

PRIORITY 3 - Comprehensive Coverage:

  • Unit tests should be extensive - test even if we don't expect users to use it currently.
  • Cover happy paths AND unhappy paths/edge cases.
  • Test boundary conditions, null/None values, empty collections, etc.
  • Avoid brittle ordering assertions unless order is part of the contract.

PRIORITY 4 - No Mocks for Non-Existent Modules:

  • All imports must reference actual SDK modules - no hallucinated paths.
  • Validate import paths against the actual src/hiero_sdk_python structure.
  • Mocks should only be used for external de...

Files:

  • tests/unit/hbar_test.py
🧬 Code graph analysis (3)
examples/hbar.py (1)
src/hiero_sdk_python/hbar.py (4)
  • Hbar (18-213)
  • from_gigabars (152-157)
  • from_millibars (120-125)
  • from_hbars (128-133)
tests/unit/hbar_test.py (2)
src/hiero_sdk_python/hbar.py (9)
  • Hbar (18-213)
  • from_microbars (112-117)
  • to_tinybars (63-65)
  • from_millibars (120-125)
  • from_hbars (128-133)
  • from_kilobars (136-141)
  • to_hbars (67-71)
  • from_megabars (144-149)
  • from_gigabars (152-157)
src/hiero_sdk_python/hbar_unit.py (1)
  • HbarUnit (3-47)
src/hiero_sdk_python/hbar.py (1)
src/hiero_sdk_python/hbar_unit.py (1)
  • HbarUnit (3-47)
🪛 Ruff (0.14.10)
src/hiero_sdk_python/hbar.py

112-112: Use X | Y for type annotations

Convert to X | Y

(UP007)


120-120: Use X | Y for type annotations

Convert to X | Y

(UP007)


128-128: Use X | Y for type annotations

Convert to X | Y

(UP007)


136-136: Use X | Y for type annotations

Convert to X | Y

(UP007)


144-144: Use X | Y for type annotations

Convert to X | Y

(UP007)


152-152: Use X | Y for type annotations

Convert to X | Y

(UP007)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Agent
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: build-and-test (3.11)
  • GitHub Check: build-and-test (3.13)
  • GitHub Check: build-and-test (3.12)
  • GitHub Check: build-and-test (3.10)
  • GitHub Check: run-examples
  • GitHub Check: StepSecurity Harden-Runner
🔇 Additional comments (2)
tests/unit/hbar_test.py (1)

154-203: Excellent test coverage for factory methods!

The test comprehensively validates all six factory methods with:

  • Return type assertions (isinstance checks)
  • Edge cases (zero, negative values, Decimal inputs)
  • Equivalence verification with the constructor
  • Both to_tinybars() and to_hbars() conversions

This addresses all the concerns raised in the previous review and follows unit testing best practices for protecting against breaking changes.

Based on coding guidelines for unit tests.

CHANGELOG.md (1)

76-76: LGTM! Changelog entry is clear and complete.

The entry properly documents all six factory methods and includes the issue reference.

Copy link
Contributor

@exploreriii exploreriii left a comment

Choose a reason for hiding this comment

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

Awesome! LGTM

@exploreriii exploreriii merged commit 753fae7 into hiero-ledger:main Jan 1, 2026
20 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Intermediate]: Improve developer experience for hbar handling

4 participants