-
Notifications
You must be signed in to change notification settings - Fork 147
feat: Add convenient factory methods for Hbar units #1277
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: Add convenient factory methods for Hbar units #1277
Conversation
Signed-off-by: Adityarya11 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. @@ 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:
|
|
Note Other AI code review bot(s) detectedCodeRabbit 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. 📝 WalkthroughWalkthroughAdds six Hbar classmethods — Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Pre-merge checks✅ Passed checks (5 passed)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro 📒 Files selected for processing (1)
⏰ 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)
🔇 Additional comments (1)
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. Comment |
There was a problem hiding this 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
📒 Files selected for processing (4)
CHANGELOG.mdexamples/hbar.pysrc/hiero_sdk_python/hbar.pytests/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_pythonstructure.- 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_pythoncodebase.- Ensure response validation checks
receipt.statusagainstResponseCodeenums (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).namefor clarity.Priority 3 - Naming & Clarity:
- Enforce role-based naming:
operator_id/_key,treasury_account_id/_key,receiver_id/_key.- Use
_idsuffix for AccountId and_keysuffix 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:
- 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).- STRICTLY validate that the import path actually exists in the project structure. Compare against other files in
/examplesor your knowledge of the SDK file tree.- Flag hallucinations immediately (e.g.,
hiero_sdk_python.keysdoes not exist).- Check for
try-exceptblocks withsys.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.
|
@Adityarya11 nice work! The PR looks good to me 👍 |
exploreriii
left a comment
There was a problem hiding this 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
|
Hi, this is MergeConflictBot. Please resolve these conflicts locally and push the changes. To assist you, please read: Thank you for contributing! |
|
Hi @Adityarya11 let me know when this is ready to review |
Signed-off-by: Adityarya11 <[email protected]>
0d9fef6 to
f9a9676
Compare
Signed-off-by: notsogod <[email protected]>
There was a problem hiding this 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(), andfrom_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.
There was a problem hiding this 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
📒 Files selected for processing (4)
CHANGELOG.mdexamples/hbar.pysrc/hiero_sdk_python/hbar.pytests/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_pythoncodebase.- Ensure response validation checks
receipt.statusagainstResponseCodeenums (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).namefor clarity.Priority 3 - Naming & Clarity:
- Enforce role-based naming:
operator_id/_key,treasury_account_id/_key,receiver_id/_key.- Use
_idsuffix for AccountId and_keysuffix 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:
- 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).- STRICTLY validate that the import path actually exists in the project structure. Compare against other files in
/examplesor your knowledge of the SDK file tree.- Flag hallucinations immediately (e.g.,
hiero_sdk_python.keysdoes not exist).- Check for
try-exceptblocks withsys.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_pythonstructure.- 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 (
isinstancechecks)- Edge cases (zero, negative values,
Decimalinputs)- Equivalence verification with the constructor
- Both
to_tinybars()andto_hbars()conversionsThis 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.
exploreriii
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Awesome! LGTM
Description:
This PR improves the developer experience (DX) for
Hbarinstantiation by adding explicit factory methods for various Hbar units. This removes the need for the verboseHbar.of(value, HbarUnit.UNIT)syntax when handling specific denominations.from_microbars,from_millibars,from_hbars,from_kilobars,from_megabars, andfrom_gigabarsfactory methods toHbarclass.examples/hbar.pyto demonstrate the new helper methods.Related issue(s):
Fixes #1272
Checklist