-
Notifications
You must be signed in to change notification settings - Fork 1
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
dev: update by coderabbit #73
Conversation
Warning Rate limit exceeded@peaceandwhisky has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 9 minutes and 48 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. WalkthroughThe pull request introduces modifications to the Changes
Possibly related PRs
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
Documentation and Community
|
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: 3
🧹 Outside diff range and nitpick comments (7)
test/utils/helpers.go (2)
Line range hint
35-57
: Remove redundant error checksThe function has redundant assertions after proper error handling is already in place. This creates confusion about which error handling approach should be followed.
Remove the redundant assertions:
func ApproveAddressHelper(t *testing.T, taStoreContract *framework.Contract, accountId string, ownerPrivKey *ecdsa.PrivateKey, addressToApprove string) error { validFor := uint64(time.Now().AddDate(1, 0, 0).Unix()) approveSig, err := NewPbTimedSignature(taStoreContract, ownerPrivKey, validFor, common.HexToHash(impl.APPROVE_ADDRESS_FUNCTION_HASH)) if err != nil { return fmt.Errorf("failed to generate timed signature: %w", err) } approveAddressRequest := &pb.ApproveAddressRequest{ Base: &pb.AccountOperationRequest{ AccountId: accountId, Proof: approveSig, }, Address: addressToApprove, } _, resp, err := ApproveAddress(approveAddressRequest) - assert.NoError(t, err, "Failed to approve address") - assert.Equal(t, 200, resp.StatusCode) if err != nil { return fmt.Errorf("failed to approve address: %w", err) } if resp.StatusCode != 200 { return fmt.Errorf("unexpected status code: %d", resp.StatusCode) } return nil }
Line range hint
61-82
: Remove redundant error checksSimilar to ApproveAddressHelper, this function has redundant assertions after proper error handling is already in place.
Remove the redundant assertions:
func UnlockAccountHelper(t *testing.T, taStoreContract *framework.Contract, accountId string, ownerPrivKey *ecdsa.PrivateKey) error { validFor := uint64(time.Now().AddDate(1, 0, 0).Unix()) unlockSig, err := NewPbTimedSignature(taStoreContract, ownerPrivKey, validFor, common.HexToHash(impl.UNLOCK_ACCOUNT_FUNCTION_HASH)) if err != nil { return fmt.Errorf("failed to generate timed signature: %w", err) } unlockAccountRequest := &pb.UnlockAccountRequest{ Base: &pb.AccountOperationRequest{ AccountId: accountId, Proof: unlockSig, }, } _, resp, err := UnlockAccount(unlockAccountRequest) if err != nil { return fmt.Errorf("failed to unlock account: %w", err) } if resp.StatusCode != 200 { return fmt.Errorf("unexpected status code: %d", resp.StatusCode) } - assert.NoError(t, err, "Failed to unlock account") - assert.Equal(t, 200, resp.StatusCode) return nil }test/e2e/e2e_test.go (2)
437-440
: LGTM! Consistent error handling for address approval.The error handling for
ApproveAddressHelper
is well-implemented with clear error messages.Consider adding error scenario test cases.
While the happy path is well tested, consider adding test cases that verify the error handling behavior of these helper functions (e.g., network errors, invalid inputs).
Example test case:
{ name: "Invalid address format", setupFunc: func() (string, string) { accountId, err := testutil.CreateAccountHelper(t, taStoreContract, alicePrivKey) if err != nil { t.Fatalf("Failed to create account: %v", err) } return accountId, "invalid_address_format" }, expectValid: false, },Also applies to: 633-636
Line range hint
1-784
: Consider documenting helper function contracts.The test file makes extensive use of helper functions (
CreateAccountHelper
,UnlockAccountHelper
,ApproveAddressHelper
). Consider adding documentation comments that describe:
- Expected behavior and return values
- Possible error conditions
- Required preconditions
- Side effects
This would make the test cases more maintainable and easier to understand.
Example:
// CreateAccountHelper creates a new account with the given private key. // Returns the account ID and any error encountered. // // Possible errors: // - Network errors during contract interaction // - Invalid private key format // - Contract execution errors func CreateAccountHelper(t *testing.T, contract *framework.Contract, privKey *ecdsa.PrivateKey) (string, error)test/TransferableAccountStore.t.sol (3)
13-14
: Consider using test key generation instead of hardcoded private keys.While converting private keys to constants improves immutability, consider using a deterministic key generation function for test accounts instead of hardcoding private keys, even in tests. This prevents potential misuse if test keys are accidentally used in production.
- uint256 public constant ALICE_PRIVATE_KEY = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; - uint256 public constant BOB_PRIVATE_KEY = 0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; + uint256 public constant ALICE_PRIVATE_KEY = uint256(keccak256("test_key_alice")); + uint256 public constant BOB_PRIVATE_KEY = uint256(keccak256("test_key_bob"));
34-35
: Standardize error naming convention.The error types have inconsistent naming.
AccountLockedError
includes the 'Error' suffix whileAccountLocked
doesn't.- error AccountLocked(); - error AccountLockedError(); + error AccountLockedError(); + error AccountNotLockedError();
Line range hint
37-64
: Add input validation to generateTimedSignature helper.The helper function should validate that
validFor
is not in the past andsigner
is not zero address.function generateTimedSignature( uint64 validFor, address signer, uint256 privateKey, uint64 nonce, bytes32 targetFunctionHash ) internal pure returns (SignatureVerifier.TimedSignature memory) { + require(validFor > block.timestamp, "Invalid validity period"); + require(signer != address(0), "Invalid signer address"); bytes32 messageHash = SignatureVerifier.hashMessage(validFor, signer, nonce, targetFunctionHash);
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (4)
src/solidity/TransferableAccountStore.sol
(9 hunks)test/TransferableAccountStore.t.sol
(18 hunks)test/e2e/e2e_test.go
(10 hunks)test/utils/helpers.go
(4 hunks)
🔇 Additional comments (5)
test/utils/helpers.go (1)
Line range hint 17-82
: Approve improved error handling approach
The changes to return errors instead of failing tests immediately is a good improvement because:
- It allows test cases to handle errors appropriately
- It maintains error context through proper error wrapping
- It provides clear and descriptive error messages
After removing the redundant assertions, this will be a clean and consistent implementation.
src/solidity/TransferableAccountStore.sol (2)
26-26
: Good improvement: Making KEY_FA constant enhances security and reduces gas costs.
Converting the mutable storage variable to a constant is a positive change as it:
- Prevents accidental modifications to a critical storage key
- Reduces gas costs by not using a storage slot
- Makes the contract's intent clearer
115-116
: Verify function hash calculations match their documented signatures.
The function hash declarations have been updated with improved naming conventions. Let's verify that each hash value correctly matches its documented function signature.
Also applies to: 138-139, 174-175, 194-195, 233-234, 254-255, 274-275, 300-301
test/e2e/e2e_test.go (2)
148-151
: LGTM! Consistent error handling for account creation.
The error handling for CreateAccountHelper
is well-implemented across all test cases, with clear error messages that aid in debugging.
Also applies to: 211-214, 280-283, 345-348, 431-434, 519-522, 569-572, 628-631, 644-647, 689-692, 700-703, 741-744, 752-755
217-220
: LGTM! Consistent error handling for account unlocking.
The error handling for UnlockAccountHelper
is well-implemented across all test cases, with clear error messages that aid in debugging.
Also applies to: 525-528, 756-759
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
🧹 Outside diff range and nitpick comments (3)
scripts/utils/generate_function_hash/main.go (2)
19-22
: Consider enhancing the error message.While the empty input validation is good, the error message could be more descriptive to help users understand what went wrong and how to fix it.
- fmt.Fprintln(os.Stderr, "Error: Empty input string") + fmt.Fprintln(os.Stderr, "Error: Function signature cannot be empty")
Line range hint
1-34
: Consider adding batch processing capability.For improved developer workflow, consider adding support for:
- Reading multiple function signatures from a file
- Processing multiple signatures provided as command-line arguments
- JSON output format option for better integration with other tools
This would make the utility more versatile for processing multiple function signatures in one go.
scripts/utils/generate_timed_signature/main.go (1)
71-73
: Consider security improvements for signature generationThe current implementation has several security considerations:
- The hardcoded 24-hour validity period might be too long for sensitive operations like
DeleteAccount
orTransferAccount
- Loading private keys from command line arguments poses a security risk as they could be visible in shell history
Consider these improvements:
- Make the validity duration configurable based on the operation type
- Add support for loading private keys from environment variables or secure files
- Add validation for minimum/maximum validity periods
Would you like me to propose a specific implementation for these security improvements?
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (4)
scripts/utils/generate_function_hash/main.go
(1 hunks)scripts/utils/generate_timed_signature/main.go
(2 hunks)src/solidity/lib/SignatureVerifier.sol
(1 hunks)test/utils/sign.go
(3 hunks)
🔇 Additional comments (5)
scripts/utils/generate_function_hash/main.go (1)
13-14
: LGTM! Improved usage message with clear example.
Good improvement to print usage to stderr and include a practical example of a Solidity function signature format.
src/solidity/lib/SignatureVerifier.sol (1)
17-21
: LGTM! Parameter rename improves semantic clarity.
The rename from sender
to signer
better reflects the parameter's role in signature verification.
Let's verify consistent parameter naming across the codebase:
✅ Verification successful
Parameter rename from 'sender' to 'signer' is consistently applied across the codebase
The verification shows that:
- The term 'signer' is used consistently throughout the SignatureVerifier library and related contracts
- No instances of 'sender' were found in signature verification contexts
- The parameter rename aligns with its usage in all related functions including:
- SignatureVerifier.hashMessage
- SignatureVerifier.verifyTimedSignature
- TransferableAccountStore's signature-related functions
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for any remaining instances of 'sender' that might need updating
# for consistency with the new 'signer' terminology in signature verification contexts
# Search for 'sender' in Solidity files
rg -t sol 'sender' --context 3
Length of output: 58
Script:
#!/bin/bash
# Let's try a different approach using fd to find Solidity files first
# Then use ripgrep without file type specification
# Find all Solidity files and search for 'sender' in them
fd -e sol | xargs rg 'sender' -C 3
# Also search for the new term 'signer' to understand the context
fd -e sol | xargs rg 'signer' -C 3
# Additionally, let's use ast-grep to find function declarations with 'sender' or 'signer' parameters
ast-grep --pattern 'function $FNAME($$$sender$$$) { $$$ }'
ast-grep --pattern 'function $FNAME($$$signer$$$) { $$$ }'
Length of output: 11671
scripts/utils/generate_timed_signature/main.go (2)
23-23
: LGTM! Improved error logging
The enhanced error logging provides better visibility into the root cause of environment loading failures.
71-73
: LGTM! Improved type safety and variable naming
The changes improve the code in two ways:
- Using
uint64
forvalidFor
is more appropriate as validity duration should never be negative - Fixed the spelling from
valdFor
tovalidFor
for better code clarity
Also applies to: 80-80
test/utils/sign.go (1)
27-41
: LGTM! Robust error handling improvements.
The enhanced error handling is well-implemented with specific error messages for each failure case:
- Empty logs check
- AccountId existence verification
- Type assertion validation
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
🧹 Outside diff range and nitpick comments (3)
test/TransferableAccountStore.t.sol (3)
13-14
: Consider security implications of public test keys.While making test private keys public constants improves readability, consider adding a comment to explicitly indicate these are test-only keys to prevent misuse in production.
- uint256 public constant ALICE_PRIVATE_KEY = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; - uint256 public constant BOB_PRIVATE_KEY = 0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb; + // WARNING: These are test-only keys. Never use in production! + uint256 public constant ALICE_PRIVATE_KEY = 0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa; + uint256 public constant BOB_PRIVATE_KEY = 0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;
34-35
: Differentiate error types more clearly.The error types
AccountLocked
andAccountLockedError
are too similar and might cause confusion. Consider renaming for clarity.- error AccountLocked(); - error AccountLockedError(); + error AccountIsLocked(); + error AccountLockStateError();
Line range hint
66-502
: Consider refactoring common test patterns.Many test functions share similar setup patterns (creating accounts, generating signatures). Consider extracting these into helper functions to improve maintainability and reduce code duplication.
Example helper function:
function setupTestAccount( TransferableAccountStore tas, address owner, uint256 privateKey ) internal returns (string memory accountId) { SignatureVerifier.TimedSignature memory sig = generateTimedSignature( uint64(block.timestamp + 86400), owner, privateKey, tas.getNonce(owner), CREATE_ACCOUNT_FUNCTION_HASH ); bytes memory encodedData = tas.createAccount(sig); bytes memory accountData = decodeEncodedData(encodedData); ( SignatureVerifier.TimedSignature memory decodedTimedSignature, ITransferableAccountStore.Account memory decodedAccount ) = abi.decode(accountData, (SignatureVerifier.TimedSignature, ITransferableAccountStore.Account)); return tas.createAccountCallback(decodedTimedSignature, decodedAccount); }
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
📒 Files selected for processing (1)
test/TransferableAccountStore.t.sol
(18 hunks)
🔇 Additional comments (1)
test/TransferableAccountStore.t.sol (1)
414-416
:
Remove unreachable code.
This error check is unreachable as the account is already unlocked at this point (line 407).
- if (isAccountLocked) {
- revert AccountLocked();
- }
Likely invalid or redundant comment.
This reverts commit 29029bb.
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Refactor