Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat/predicate iterate #769

Merged
merged 7 commits into from
Oct 7, 2024
Merged

Feat/predicate iterate #769

merged 7 commits into from
Oct 7, 2024

Conversation

ccamel
Copy link
Member

@ccamel ccamel commented Oct 4, 2024

This PR leverages the lazy sequence support for delayed promises introduced in axone-protocol/prolog#10 to refactor the balance-related predicates in the logic module.

bank_balances(X, Y).
bank_spendable_balances(X, Y).
bank_locked_balances(X, Y).

Previously, the implementation fetched all addresses from the blockchain at once, which risked failing due to gas limits. The new approach iterates over addresses as each solution branch is explored, aligning better with Prolog’s natural mechanisms and optimizing resource usage.

Implementation Notes

  • While the addresses are now iterated, the balances for each account are still retrieved in full. Although the token amounts per account are expected to be small, I believe the Zero One Infinity principle should apply, suggesting that balances should also be iterated. However, this would require a more complex implementation, and it’s worth evaluating whether the effort is justified.
  • For simplicity, the iteration leverages the keeper methods originally designed for the gRPC API, effectively making the logic act as a client (consumer). This adds a minor overhead due to the round-trip encoding and decoding of protobufs.

Test

> make chain-init
> make chain-start

> axoned query logic ask --program "get_all_balances(List) :- findall(balance(X, Y), bank_balances(X, Y), List)." "get_all_balances(L)."  --node http://localhost:26657
answer:
  has_more: false
  results:
  - error: ""
    substitutions:
    - expression: '[balance(axone1p8u47en82gmzfm259y6z93r9qe63l25d858vqu,[uaxone-999000000]),balance(axone1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3ka9cd2,[uaxone-1000000]),balance(axone1tygms3xhhs3yv487phx3dw4a95jn7t7lzaefm7,[]),balance(axone10d07y265gmmuvt4z0w9aw880jnsr700jeyljzw,[]),balance(axone1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8yegtaz,[uaxone-1922]),balance(axone1m3h30wlvsf8llruxtpukdvsy0km2kum8tht0na,[]),balance(axone17xpfvakm2amg962yls6f84z3kell8c5lnl0hlq,[])]'
      variable: L
  variables:
  - L
gas_used: "8253"
height: "62"
user_output: ""

> axoned query auth accounts --node http://localhost:26657 --output json | jq -r '.accounts.[].value.address' | xargs -I {} sh -c 'echo "{}:" && axoned query bank balances {} --node http://localhost:26657 --output json | jq "del(.pagination)"'
{
  "balances": [
    {
      "denom": "uaxone",
      "amount": "999000000"
    }
  ]
}
axone1fl48vsnmsdzcv85q5d2q4z5ajdha8yu3ka9cd2:
{
  "balances": [
    {
      "denom": "uaxone",
      "amount": "1000000"
    }
  ]
}
axone1tygms3xhhs3yv487phx3dw4a95jn7t7lzaefm7:
{
  "balances": []
}
axone10d07y265gmmuvt4z0w9aw880jnsr700jeyljzw:
{
  "balances": []
}
axone1jv65s3grqf6v6jl3dp4t6c9t9rk99cd8yegtaz:
{
  "balances": [
    {
      "denom": "uaxone",
      "amount": "1922"
    }
  ]
}
axone1m3h30wlvsf8llruxtpukdvsy0km2kum8tht0na:
{
  "balances": []
}
axone17xpfvakm2amg962yls6f84z3kell8c5lnl0hlq:
{
  "balances": []
}
...

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new AuthQueryService for enhanced account query capabilities.
    • Added mock implementations for testing the AuthQueryService.
    • Enhanced the context management with new keys for InterfaceRegistry and AuthQueryService.
  • Improvements

    • Improved error handling and clarity in the QueryInterpreter function.
    • Updated test cases to cover various scenarios for account and bank functionalities.
  • Bug Fixes

    • Removed outdated methods from mock interfaces to streamline functionality.
  • Documentation

    • Enhanced comments and documentation for clarity in function usage and parameters.

@ccamel ccamel self-assigned this Oct 4, 2024
Copy link
Contributor

coderabbitai bot commented Oct 4, 2024

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Walkthrough

The pull request introduces significant modifications across multiple files, primarily enhancing the build process, mock generation, and application logic. Key changes include the addition of a mock generation command in the Makefile, updates to the App struct for improved codec integration, and the introduction of new mock services for authentication queries. Dependency versions in go.mod are updated for security and compatibility. Additionally, numerous test files have been modified to incorporate new mock services and improve test coverage, particularly around account management and error handling.

Changes

File Path Change Summary
Makefile Added command for generating mocks for interface_registry.go; updated release-assets target for Docker.
app/app.go Updated LogicKeeper constructor; added provideFS method for virtual file system; modified WasmKeeper.
go.mod Updated dependency versions for github.com/ichiban/prolog, github.com/golang-jwt/jwt/v4, and github.com/gin-gonic/gin.
x/logic/keeper/features_test.go Added authQueryService to testCase struct; updated newQueryClient function to include new service.
x/logic/keeper/grpc_query_ask_test.go Removed bank balance test case; added mock authQueryService in test setup.
x/logic/keeper/grpc_query_params_test.go Added mock AuthQueryService for TestGRPCParams; updated NewKeeper instantiation.
x/logic/keeper/interpreter.go Enhanced enhanceContext method to include types.InterfaceRegistryContextKey.
x/logic/keeper/keeper.go Added interfaceRegistry and authQueryService fields to Keeper; updated NewKeeper method signature.
x/logic/keeper/msg_server_test.go Updated TestUpdateParams to include authQueryService in keeper.NewKeeper.
x/logic/predicate/bank.go Renamed parameters for clarity; refactored fetchBalances function.
x/logic/predicate/bank_test.go Expanded test cases for account-related queries; enhanced error handling.
x/logic/predicate/util.go Added new functions for account iteration; updated existing functions to accept context.
x/logic/predicate/util_test.go Introduced unit tests for Accounts function, validating behavior under various scenarios.
x/logic/prolog/context.go Added ContextValue function for retrieving context values.
x/logic/prolog/error.go Introduced ResourceContextValue function for context resource retrieval.
x/logic/testutil/expected_keepers_mocks.go Added MockAuthQueryService; removed GetAccountsBalances from MockBankKeeper.
x/logic/testutil/interface_registry_mocks.go Generated mocks for AnyUnpacker and InterfaceRegistry interfaces.
x/logic/testutil/keeper_mocks.go Added mock functions for AuthQueryService to simulate account retrieval and error scenarios.
x/logic/types/context.go Added InterfaceRegistryContextKey and AuthQueryServiceContextKey constants.
x/logic/types/expected_keepers.go Introduced AuthQueryService interface with Accounts method; removed GetAccountsBalances from BankKeeper.
x/logic/util/prolog.go Streamlined error handling in QueryInterpreter function.

Poem

In the meadow where rabbits play,
New mocks and tests come out to stay.
With each change, our code does bloom,
Enhancing logic, dispelling gloom.
Hops of joy as we build anew,
In the world of code, there's much to do! 🐇✨


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?

❤️ Share
🪧 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.

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

Documentation and Community

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

Copy link

codecov bot commented Oct 4, 2024

Codecov Report

Attention: Patch coverage is 80.16529% with 24 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
x/logic/util/prolog.go 0.00% 15 Missing ⚠️
x/logic/prolog/context.go 0.00% 5 Missing ⚠️
x/logic/predicate/bank.go 95.55% 2 Missing ⚠️
x/logic/prolog/error.go 0.00% 2 Missing ⚠️

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #769      +/-   ##
==========================================
+ Coverage   54.89%   54.98%   +0.09%     
==========================================
  Files          73       73              
  Lines        2940     2966      +26     
==========================================
+ Hits         1614     1631      +17     
- Misses       1230     1241      +11     
+ Partials       96       94       -2     
Files with missing lines Coverage Δ
x/logic/keeper/interpreter.go 92.92% <100.00%> (+0.06%) ⬆️
x/logic/keeper/keeper.go 64.70% <100.00%> (+4.70%) ⬆️
x/logic/predicate/util.go 100.00% <100.00%> (ø)
x/logic/predicate/bank.go 96.00% <95.55%> (+4.10%) ⬆️
x/logic/prolog/error.go 0.00% <0.00%> (ø)
x/logic/prolog/context.go 0.00% <0.00%> (ø)
x/logic/util/prolog.go 0.00% <0.00%> (ø)

@ccamel ccamel force-pushed the feat/predicate-iterate branch 2 times, most recently from fee8a85 to bfe7d11 Compare October 4, 2024 19:23
@ccamel ccamel marked this pull request as ready for review October 4, 2024 19:45
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: 18

🧹 Outside diff range and nitpick comments (18)
x/logic/types/expected_keepers.go (2)

15-17: LGTM: New AuthQueryService interface added.

The new AuthQueryService interface with the Accounts method aligns well with the PR objectives. It provides a way to query accounts, which can be used to iterate over addresses as mentioned in the PR summary.

Consider adding a brief comment explaining the purpose of this interface, similar to the comments for other interfaces in this file.


Line range hint 1-33: Summary: Changes align well with PR objectives

The modifications in this file effectively support the transition from bulk retrieval to iterative querying of account balances:

  1. The new AuthQueryService interface provides a mechanism for querying accounts, enabling iteration over addresses.
  2. Removal of GetAccountsBalances from BankKeeper reinforces the move away from retrieving all balances at once.
  3. Import changes reflect the shift in dependencies from bank to auth types.

These changes are consistent with the PR's goal of enhancing the handling of balance-related predicates and optimizing resource usage.

As the PR summary mentions, consider evaluating the effort required to iterate over balances as well. This could further optimize resource usage, especially for accounts with numerous balance entries.

x/logic/prolog/context.go (2)

26-35: LGTM: New ContextValue function implemented correctly.

The new ContextValue function is well-implemented and aligns with the PR objectives. It uses generics for type-safe retrieval of context values and handles error cases appropriately.

A minor suggestion for improved clarity:

Consider adding a comment explaining the zero V variable:

 var zero V
+// zero is the zero value for type V, returned when the key is not found in the context
 return zero, engine.ResourceError(ResourceContextValue(string(key)), env)

This addition would make the purpose of the zero variable more explicit for future readers of the code.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 28-30: x/logic/prolog/context.go#L28-L30
Added lines #L28 - L30 were not covered by tests


[warning] 33-34: x/logic/prolog/context.go#L33-L34
Added lines #L33 - L34 were not covered by tests


28-35: Consider adding unit tests for the new ContextValue function.

The static analysis tools indicate that the new ContextValue function is not covered by tests. While this doesn't necessarily indicate a problem with the implementation, adding unit tests would improve the overall quality and maintainability of the codebase.

Would you like assistance in generating unit tests for the ContextValue function? These tests could cover both the successful retrieval of a value and the error case when a value is not found in the context.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 28-30: x/logic/prolog/context.go#L28-L30
Added lines #L28 - L30 were not covered by tests


[warning] 33-34: x/logic/prolog/context.go#L33-L34
Added lines #L33 - L34 were not covered by tests

x/logic/testutil/keeper_mocks.go (2)

17-73: Consider improving error handling and pagination.

The function MockAuthQueryServiceWithAddresses is well-implemented overall, but there are two areas for potential improvement:

  1. Error Handling: Instead of panicking on errors, consider returning them to allow for better error management in tests.

  2. Pagination: The current implementation using lo.Slice might not accurately represent real pagination behavior. Consider implementing pagination that more closely mimics the actual service.

Here's a suggested refactor for error handling and pagination:

 func MockAuthQueryServiceWithAddresses(mock *MockAuthQueryService, addresses []string) {
 	mock.
 		EXPECT().
 		Accounts(gomock.Any(), gomock.Any()).
 		AnyTimes().
-		DoAndReturn(func(_ context.Context, req *authtypes.QueryAccountsRequest) (*authtypes.QueryAccountsResponse, error) {
+		DoAndReturn(func(_ context.Context, req *authtypes.QueryAccountsRequest) (*authtypes.QueryAccountsResponse, error) {
 			start := 0
-			limit := 5
-			toCursor := func(idx int) []byte { return []byte(fmt.Sprintf("%d", idx)) }
-			fromCursor := func(k []byte) int {
-				idx, err := strconv.Atoi(string(k))
-				if err != nil {
-					panic(err)
-				}
-
-				return idx
-			}
+			limit := query.DefaultLimit
+			
+			if req.Pagination != nil {
+				if req.Pagination.Offset > 0 {
+					start = int(req.Pagination.Offset)
+				}
+				if req.Pagination.Limit > 0 {
+					limit = int(req.Pagination.Limit)
+				}
+			}
 
-			if req.Pagination != nil {
-				if req.Pagination.Key != nil {
-					start = fromCursor(req.Pagination.Key)
-				}
-				if req.Pagination.Limit != 0 {
-					limit = int(req.Pagination.GetLimit())
-				}
+			end := start + limit
+			if end > len(addresses) {
+				end = len(addresses)
 			}
-			accounts := lo.Map(
-				lo.Slice(addresses, start, start+limit),
-				func(acc string, _ int) *codectypes.Any {
-					addr, err := sdk.AccAddressFromBech32(acc)
-					if err != nil {
-						panic(err)
-					}
 
-					accI := authtypes.ProtoBaseAccount()
-					err = accI.SetAddress(addr)
-					if err != nil {
-						panic(err)
-					}
+			accounts := make([]*codectypes.Any, 0, end-start)
+			for _, acc := range addresses[start:end] {
+				addr, err := sdk.AccAddressFromBech32(acc)
+				if err != nil {
+					return nil, fmt.Errorf("invalid address %s: %w", acc, err)
+				}
 
-					anyV, err := codectypes.NewAnyWithValue(accI)
-					if err != nil {
-						panic(err)
-					}
+				accI := authtypes.ProtoBaseAccount()
+				if err := accI.SetAddress(addr); err != nil {
+					return nil, fmt.Errorf("failed to set address: %w", err)
+				}
 
-					return anyV
-				})
+				anyV, err := codectypes.NewAnyWithValue(accI)
+				if err != nil {
+					return nil, fmt.Errorf("failed to create Any value: %w", err)
+				}
+
+				accounts = append(accounts, anyV)
+			}
 
 			return &authtypes.QueryAccountsResponse{
 				Accounts: accounts,
 				Pagination: &query.PageResponse{
-					NextKey: toCursor(start + 1),
-					Total:   0,
+					NextKey: nil,
+					Total:   uint64(len(addresses)),
 				},
 			}, nil
 		})
 }

This refactor improves error handling by returning errors instead of panicking, and implements pagination more accurately by using offset and limit directly.

Despite these suggestions, the overall implementation is solid and well-structured.


1-83: Overall assessment: Well-implemented mock functions with minor improvement suggestions.

This new file keeper_mocks.go successfully introduces mock implementations for the AuthQueryService, aligning with the PR objectives of enhancing balance-related predicate handling. The two main functions, MockAuthQueryServiceWithAddresses and MockAuthQueryServiceWithError, provide valuable tools for testing scenarios.

Key points:

  1. The mock implementations are well-structured and use appropriate libraries (gomock, lo).
  2. Error scenarios are properly accounted for with MockAuthQueryServiceWithError.
  3. The MockAuthQueryServiceWithAddresses function handles pagination and address transformation, though there's room for improvement in error handling and pagination implementation.

These mocks will facilitate testing of components that depend on account queries, supporting the PR's goal of optimizing resource usage and aligning with Prolog's natural mechanisms.

Consider implementing similar mocking strategies for other keeper methods that might be used in the refactored predicates (bank_balances, bank_spendable_balances, bank_locked_balances) to ensure comprehensive test coverage of the new lazy sequence approach.

x/logic/keeper/msg_server_test.go (1)

Line range hint 1-93: Overall assessment: Changes align with PR objectives

The modifications to this test file are consistent with the PR objectives of enhancing the handling of balance-related predicates. The introduction of the authQueryService mock and the updates to the NewKeeper function signature support this goal.

However, it's worth noting that these changes are focused on setting up the test environment. To fully validate the PR objectives:

  1. Consider adding specific test cases that exercise the new lazy sequence support for delayed promises in balance-related predicates.
  2. Ensure that the test cases cover the iteration over addresses as each solution branch is explored, as mentioned in the PR objectives.

These additions would provide more comprehensive coverage of the new functionality and help verify that the implementation meets the stated goals of the PR.

x/logic/keeper/grpc_query_params_test.go (1)

62-62: LGTM! Consider a minor naming improvement.

The addition of the AuthQueryService mock aligns well with the PR objectives. This change supports the enhanced handling of balance-related predicates as described in the PR summary.

Consider using a more descriptive variable name, such as mockAuthQueryService, to clearly indicate that it's a mock object:

-authQueryService := logictestutil.NewMockAuthQueryService(ctrl)
+mockAuthQueryService := logictestutil.NewMockAuthQueryService(ctrl)
x/logic/predicate/util_test.go (1)

67-91: LGTM with suggestion: Good error handling test, but consider making it more robust.

This test case effectively verifies the behavior of the Accounts function when encountering an error:

  • Sets up a mock interface registry that always returns an error
  • Checks that the function handles the error gracefully
  • Verifies the returned error matches the expected one

However, there's room for improvement:

Consider making the error checking more robust by verifying the error type or using a partial match on the error message, rather than an exact string match. This would make the test less brittle in case the exact error message changes. For example:

So(result.B, ShouldBeError)
So(result.B.Error(), ShouldContainSubstring, "not to unpack")
x/logic/prolog/error.go (1)

90-93: LGTM! Consider adding documentation and tests.

The implementation of ResourceContextValue looks correct and consistent with other similar functions in the file. However, there are a couple of suggestions for improvement:

  1. Add documentation to explain the purpose and usage of this function, similar to other functions in the file.
  2. Include unit tests to cover this new function, as indicated by the static analysis tool.

Here's a suggestion for documentation:

// ResourceContextValue returns a term representing the context resource with the given key.
// It creates a compound term using AtomResourceContext and the provided key as an atom.

Would you like assistance in generating unit tests for this function?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 91-92: x/logic/prolog/error.go#L91-L92
Added lines #L91 - L92 were not covered by tests

x/logic/keeper/interpreter.go (2)

41-45: LGTM. Consider updating documentation.

The addition of types.InterfaceRegistryContextKey to the enhanced context is a good improvement. This change aligns with the PR objectives and likely supports the new functionality for handling balance-related predicates.

Consider updating the method's documentation to reflect this new addition, explaining its purpose and potential impact on the system.


Line range hint 1-290: Overall assessment: Changes look good and align with PR objectives.

The modifications to the enhanceContext and execute methods are well-implemented and consistent. They support the PR's goal of enhancing the handling of balance-related predicates by providing access to the interface registry. No other significant changes or issues were observed in the file.

However, there are a couple of points to consider:

  1. As mentioned in the PR objectives, the implementation still retrieves all balances for each account at once. Consider evaluating the effort required to iterate over balances as well, which could further optimize resource usage.
  2. The PR objectives mention using keeper methods originally designed for the gRPC API, which introduces a minor overhead. It might be worth exploring ways to reduce this overhead in future iterations.
x/logic/keeper/features_test.go (2)

60-67: LGTM: Addition of authQueryService to testCase struct

The addition of authQueryService to the testCase struct is a good improvement, aligning with the PR objectives to enhance balance-related predicate handling. Using a mock service for authentication queries in tests is a good practice.

Consider adding a comment above the testCase struct to briefly explain its purpose and the role of each field, especially the newly added authQueryService. This would improve code readability and maintainability.


Add Test Cases for Authentication Queries

The inclusion of authQueryService in the test setup is a positive step towards enhancing functionality. However, the current test files do not contain explicit test cases that utilize authQueryService to validate authentication queries. To ensure comprehensive coverage and reliability of the new authentication query functionality, please consider adding dedicated test cases that exercise and verify the behavior of authQueryService.

  • Implement test scenarios that specifically use authQueryService to test authentication queries.
🔗 Analysis chain

Line range hint 1-334: Consider adding test cases for authentication queries

The changes to include the authQueryService in the test setup are good and align with the PR objectives. However, I don't see any new test cases that specifically exercise this new functionality.

To ensure comprehensive test coverage for the new authentication query functionality, consider adding specific test cases. You can verify the current test coverage for authentication queries using the following command:

If the command doesn't return any results, it indicates that additional test cases for authentication queries might be beneficial.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for test cases related to authentication queries
# Expected result: New test cases utilizing authQueryService

rg -i 'test.*auth.*query' x/logic/keeper/

Length of output: 449

x/logic/keeper/grpc_query_ask_test.go (2)

394-394: LGTM: Addition of authQueryService mock

The introduction of the authQueryService mock enhances the testing framework to accommodate authentication-related queries, which is consistent with the PR objectives.

Consider adding a brief comment explaining the purpose of this mock service to improve code readability:

+// Mock auth query service for testing authentication-related queries
authQueryService := logictestutil.NewMockAuthQueryService(ctrl)

400-409: LGTM: Updates to logicKeeper constructor

The updates to the NewKeeper function call, including the explicit addition of encCfg.InterfaceRegistry and authQueryService as parameters, are consistent with the PR objectives and enhance the testing setup.

To improve readability, consider breaking the NewKeeper function call into multiple lines:

logicKeeper := keeper.NewKeeper(
	encCfg.Codec,
	encCfg.InterfaceRegistry,
	key,
	key,
	authtypes.NewModuleAddress(govtypes.ModuleName),
	accountKeeper,
	authQueryService,
	bankKeeper,
	func(_ gocontext.Context) fs.FS {
		return fsProvider
	},
)
Makefile (1)

382-384: LGTM! Consider adding a comment for clarity.

The addition of mock generation for the interface registry is a good enhancement. It aligns with the PR objectives and follows the existing pattern for mock generation.

Consider adding a brief comment explaining the purpose of this mock, for example:

+# Generate mock for interface registry to support testing of balance-related predicates
 @mockgen -source "$$(go list -f '{{.Dir}}' github.com/cosmos/cosmos-sdk/codec/types)/interface_registry.go" \
     -package testutil \
     -destination x/logic/testutil/interface_registry_mocks.go
x/logic/predicate/util.go (1)

94-96: Correct the function comment for LockedCoinsSorted

The comment for LockedCoinsSorted incorrectly states that it returns "spendable coins." It should be "locked coins."

Apply this diff to correct the comment:

-// LockedCoinsSorted returns the list of spendable coins for the given address, sorted by coin denomination.
+// LockedCoinsSorted returns the list of locked coins for the given address, sorted by coin denomination.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between fc17f96 and bfe7d11.

⛔ Files ignored due to path filters (4)
  • docs/predicate/bank_balances_2.md is excluded by !docs/predicate/**/*.md
  • docs/predicate/bank_locked_balances_2.md is excluded by !docs/predicate/**/*.md
  • docs/predicate/bank_spendable_balances_2.md is excluded by !docs/predicate/**/*.md
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (21)
  • Makefile (1 hunks)
  • app/app.go (1 hunks)
  • go.mod (1 hunks)
  • x/logic/keeper/features_test.go (2 hunks)
  • x/logic/keeper/grpc_query_ask_test.go (1 hunks)
  • x/logic/keeper/grpc_query_params_test.go (1 hunks)
  • x/logic/keeper/interpreter.go (1 hunks)
  • x/logic/keeper/keeper.go (3 hunks)
  • x/logic/keeper/msg_server_test.go (1 hunks)
  • x/logic/predicate/bank.go (5 hunks)
  • x/logic/predicate/bank_test.go (10 hunks)
  • x/logic/predicate/util.go (2 hunks)
  • x/logic/predicate/util_test.go (1 hunks)
  • x/logic/prolog/context.go (2 hunks)
  • x/logic/prolog/error.go (1 hunks)
  • x/logic/testutil/expected_keepers_mocks.go (2 hunks)
  • x/logic/testutil/interface_registry_mocks.go (1 hunks)
  • x/logic/testutil/keeper_mocks.go (1 hunks)
  • x/logic/types/context.go (1 hunks)
  • x/logic/types/expected_keepers.go (1 hunks)
  • x/logic/util/prolog.go (2 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
x/logic/predicate/bank.go

[warning] 163-164: x/logic/predicate/bank.go#L163-L164
Added lines #L163 - L164 were not covered by tests

x/logic/prolog/context.go

[warning] 28-30: x/logic/prolog/context.go#L28-L30
Added lines #L28 - L30 were not covered by tests


[warning] 33-34: x/logic/prolog/context.go#L33-L34
Added lines #L33 - L34 were not covered by tests

x/logic/prolog/error.go

[warning] 91-92: x/logic/prolog/error.go#L91-L92
Added lines #L91 - L92 were not covered by tests

x/logic/util/prolog.go

[warning] 56-57: x/logic/util/prolog.go#L56-L57
Added lines #L56 - L57 were not covered by tests


[warning] 61-61: x/logic/util/prolog.go#L61
Added line #L61 was not covered by tests


[warning] 65-73: x/logic/util/prolog.go#L65-L73
Added lines #L65 - L73 were not covered by tests


[warning] 75-77: x/logic/util/prolog.go#L75-L77
Added lines #L75 - L77 were not covered by tests

🔇 Additional comments (32)
x/logic/types/context.go (3)

7-8: LGTM: Addition of InterfaceRegistryContextKey

The addition of InterfaceRegistryContextKey is well-implemented. It follows the existing naming conventions, uses the ContextKey type for type safety, and includes a clear descriptive comment. This new constant aligns with the PR objectives for enhancing the handling of balance-related predicates.


11-12: LGTM: Addition of AuthQueryServiceContextKey

The addition of AuthQueryServiceContextKey is well-implemented. It maintains consistency with the existing code style, uses the ContextKey type for type safety, and includes a clear descriptive comment. This new constant supports the PR objectives for refactoring balance-related predicates.


7-12: Verify usage of new context keys

The additions of InterfaceRegistryContextKey and AuthQueryServiceContextKey look good. To ensure these changes are fully integrated:

  1. Verify that these new context keys are being used correctly in other parts of the codebase.
  2. Check if any documentation needs to be updated to reflect these additions.

Run the following script to check the usage of these new context keys:

✅ Verification successful

Context Keys Usage Verified

All usages of InterfaceRegistryContextKey and AuthQueryServiceContextKey have been confirmed across the codebase. No issues found regarding their implementation or integration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check usage of new context keys in the codebase

echo "Checking usage of InterfaceRegistryContextKey:"
rg --type go "InterfaceRegistryContextKey"

echo "\nChecking usage of AuthQueryServiceContextKey:"
rg --type go "AuthQueryServiceContextKey"

Length of output: 1970

x/logic/types/expected_keepers.go (2)

7-7: LGTM: Import change aligns with new interface.

The change from bank to auth import is consistent with the introduction of the AuthQueryService interface and the removal of bank-specific methods.


Line range hint 20-26: LGTM: Removed GetAccountsBalances method from BankKeeper.

The removal of the GetAccountsBalances method from the BankKeeper interface is consistent with the PR objectives. This change supports the shift from bulk retrieval to iterative querying of account balances.

Please ensure that all implementations and usages of the BankKeeper interface have been updated to reflect this change. Run the following script to verify:

If any results are found, they may indicate places where the code needs to be updated to align with this interface change.

x/logic/prolog/context.go (1)

10-10: LGTM: Import statement added correctly.

The new import for the types package is necessary and correctly placed for the ContextKey type used in the new ContextValue function.

x/logic/testutil/keeper_mocks.go (2)

3-15: LGTM: Import statements are well-organized and appropriate.

The import statements are properly grouped and include all necessary packages for the implemented functionality. There are no unused imports, which is good for code cleanliness.


75-83: LGTM: Error mocking function is well-implemented.

The MockAuthQueryServiceWithError function is concise and effectively serves its purpose of mocking error scenarios for the Accounts method. It correctly uses gomock and provides a simple way to test error handling in the calling code.

x/logic/keeper/msg_server_test.go (3)

60-60: LGTM: Addition of authQueryService mock

The introduction of the authQueryService mock is consistent with the PR objectives and aligns with the changes mentioned in the AI-generated summary. This addition will likely support the enhanced handling of balance-related predicates.


73-75: LGTM: Minor refactoring of fsProvider function

The inline definition of the fsProvider function within the NewKeeper call is a minor refactoring that doesn't change the functionality. While not directly related to the PR objectives, this change improves code readability by keeping the function definition close to its usage.


66-66: LGTM: Updates to NewKeeper function call, with a minor query

The changes to the NewKeeper function call, including the addition of encCfg.InterfaceRegistry and authQueryService as parameters, are consistent with the PR objectives and the AI-generated summary.

However, could you please clarify the specific need for adding encCfg.InterfaceRegistry as a parameter? This wasn't explicitly mentioned in the PR objectives, and understanding its role would be beneficial.

To verify the consistency of these changes across the codebase, please run the following script:

Also applies to: 71-71

✅ Verification successful

LGTM: Updates to NewKeeper function call, with a minor query

The changes to the NewKeeper function call, including the addition of encCfg.InterfaceRegistry and authQueryService as parameters, are consistent with the PR objectives and the AI-generated summary.

However, could you please clarify the specific need for adding encCfg.InterfaceRegistry as a parameter? This wasn't explicitly mentioned in the PR objectives, and understanding its role would be beneficial.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent updates to NewKeeper calls across the codebase

# Search for NewKeeper function calls
echo "Searching for NewKeeper function calls:"
rg --type go "NewKeeper\(" -A 10

Length of output: 16164

x/logic/keeper/grpc_query_params_test.go (3)

75-77: LGTM! Improved code formatting.

The adjustment to the fsProvider function's indentation enhances code readability without affecting functionality.


62-77: Overall changes align well with PR objectives.

The updates to the test setup and keeper initialization in this file effectively support the enhanced handling of balance-related predicates, as outlined in the PR objectives. The addition of the AuthQueryService mock and the corresponding updates to the NewKeeper call are particularly noteworthy.

These changes improve the test coverage and ensure that the new functionality related to balance predicates is properly tested. The modifications are well-implemented and contribute to the overall goal of optimizing resource usage through iterative address handling.


68-68: LGTM! Verify NewKeeper method signature.

The updates to the NewKeeper call, including the addition of encCfg.InterfaceRegistry and authQueryService, are consistent with the PR objectives and the earlier mock creation.

Please ensure that the NewKeeper method signature in the actual implementation matches these changes. Run the following script to verify:

Also applies to: 73-73

x/logic/predicate/util_test.go (3)

1-24: LGTM: Imports and package declaration are appropriate.

The package declaration and imports are well-organized and relevant for testing the Accounts function in the Axone protocol. They include necessary testing libraries (gomock, goconvey), Cosmos SDK packages, and Axone-specific imports.


26-40: LGTM: Comprehensive test setup and mock configuration.

The test setup is well-structured and follows best practices for testing Cosmos SDK modules:

  • Uses goconvey for BDD-style testing
  • Sets up mock controller and auth query service
  • Configures SDK's Bech32 prefix
  • Prepares encoding config and state store

This setup provides a controlled environment for testing the Accounts function.


41-65: LGTM: Thorough testing of the happy path scenario.

This test case effectively verifies the behavior of the Accounts function with a properly mocked context:

  • Checks that all expected addresses are returned in the correct order
  • Verifies that next() returns false after all addresses have been iterated
  • Uses an efficient loop structure to test multiple calls to next()

The test provides good coverage of the expected behavior of the Accounts function.

x/logic/prolog/error.go (1)

90-93: Verify the usage of ResourceContextValue in the context of balance predicate refactoring.

While this new function looks good, it's not directly related to the balance predicate refactoring mentioned in the PR objectives. Could you please clarify how this function is intended to be used in the context of the balance-related changes?

To help understand the usage of this new function, let's search for its occurrences in the codebase:

This will help us verify if and how the function is being used in the refactored balance predicates or other related code.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 91-92: x/logic/prolog/error.go#L91-L92
Added lines #L91 - L92 were not covered by tests

x/logic/keeper/interpreter.go (1)

Line range hint 52-52: LGTM. Consistent use of enhanced context.

The use of k.enhanceContext(ctx) ensures that the new interpreter has access to all necessary context values, including the newly added interface registry. This change is consistent with the modifications in the enhanceContext method and aligns with the PR objectives.

x/logic/keeper/features_test.go (1)

295-307: LGTM: Inclusion of authQueryService in NewKeeper call

The addition of tc.authQueryService to the NewKeeper function call is correct and consistent with the changes made to the testCase struct. This modification ensures that the mock authentication query service is properly injected into the keeper during test setup, allowing for comprehensive testing of scenarios involving authentication queries.

x/logic/testutil/interface_registry_mocks.go (4)

17-52: LGTM: MockAnyUnpacker implementation

The MockAnyUnpacker implementation follows the standard gomock pattern and correctly mocks the AnyUnpacker interface. The implementation includes a constructor, EXPECT method, and UnpackAny method, which are all correctly implemented.


54-248: LGTM: MockInterfaceRegistry implementation

The MockInterfaceRegistry implementation is comprehensive and correctly mocks all methods of the InterfaceRegistry interface. It follows the standard gomock pattern and includes the necessary mustEmbedInterfaceRegistry method for interface embedding.


250-285: LGTM: MockUnpackInterfacesMessage implementation

The MockUnpackInterfacesMessage implementation correctly mocks the UnpackInterfacesMessage interface. It follows the standard gomock pattern and includes all necessary methods.


1-285: LGTM: Generated mock implementations

This file contains correctly generated mock implementations for AnyUnpacker, InterfaceRegistry, and UnpackInterfacesMessage interfaces. The mocks follow the standard gomock pattern and appear to be complete and correct. These mock implementations will be useful for unit testing components that depend on these interfaces.

A few points to note:

  1. This file is generated and should not be manually edited.
  2. The mocks cover all methods of the respective interfaces.
  3. The implementation includes necessary methods for gomock functionality (EXPECT, constructors).

To ensure the mocks are up-to-date with the latest interface definitions, run the following command:

x/logic/keeper/grpc_query_ask_test.go (2)

Line range hint 1-1: LGTM: Removal of banktypes import and associated test case

The removal of the banktypes import and the associated test case for bank balances aligns with the PR objectives of refactoring balance-related predicates. This change effectively streamlines the test suite by removing unnecessary dependencies.


Line range hint 1-489: Overall assessment: Changes enhance test setup and align with PR objectives

The modifications to this test file effectively support the PR's goal of refactoring balance-related predicates and enhancing authentication-related query handling. The removal of unnecessary dependencies, addition of the authQueryService mock, and updates to the logicKeeper constructor collectively improve the test suite's focus and coverage.

These changes contribute to a more streamlined and targeted testing approach, which should facilitate easier maintenance and future enhancements of the logic module.

go.mod (1)

79-79: Approved: Crucial update for PR objectives

The update to the Prolog interpreter dependency is essential for implementing the lazy sequence support for delayed promises, as mentioned in the PR objectives. This change aligns well with the goal of optimizing the handling of balance-related predicates.

To ensure this change doesn't introduce any breaking changes or compatibility issues, please run the following verification script:

✅ Verification successful

Verification Successful: No Compatibility Issues Found

The dependency update to github.com/ichiban/prolog is correctly replaced by github.com/axone-protocol/prolog. All relevant files continue to reference the original import path, and the go.mod replacement ensures that the new Prolog interpreter is utilized without introducing compatibility issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of the Prolog interpreter update

# Test: Check if there are any compatibility issues or errors related to the Prolog interpreter
rg -i 'prolog|ichiban' --type go -C 5

Length of output: 116930

x/logic/keeper/keeper.go (2)

19-29: Addition of interfaceRegistry and authQueryService enhances the Keeper struct

The inclusion of interfaceRegistry cdctypes.InterfaceRegistry and authQueryService types.AuthQueryService into the Keeper struct increases the modularity and potential functionality of the module. This allows for better interface handling and authorization queries within the keeper logic.


43-51: Initialization of new fields in NewKeeper is correct

The new fields interfaceRegistry and authQueryService are properly initialized within the NewKeeper function, ensuring that the Keeper instance is correctly set up with all necessary dependencies.

x/logic/testutil/expected_keepers_mocks.go (1)

53-90: LGTM!

The implementation of MockAuthQueryService follows standard gomock patterns and correctly mocks the AuthQueryService interface.

x/logic/predicate/bank_test.go (1)

556-812: TestAccount function enhances test coverage

The newly added TestAccount function provides comprehensive test cases for the account predicate, covering various scenarios, including successful queries and error conditions.

app/app.go (1)

571-571: Ensure interfaceRegistry is correctly integrated

The addition of app.interfaceRegistry to the NewKeeper function suggests a need for interfaceRegistry within the Logic Keeper. Verify that interfaceRegistry is required and properly utilized inside the Logic Keeper to manage interfaces as intended.

x/logic/predicate/util_test.go Outdated Show resolved Hide resolved
x/logic/keeper/keeper.go Show resolved Hide resolved
x/logic/predicate/util.go Show resolved Hide resolved
x/logic/predicate/util.go Outdated Show resolved Hide resolved
x/logic/predicate/util.go Outdated Show resolved Hide resolved
x/logic/testutil/expected_keepers_mocks.go Show resolved Hide resolved
x/logic/predicate/bank_test.go Show resolved Hide resolved
x/logic/predicate/bank_test.go Show resolved Hide resolved
app/app.go Show resolved Hide resolved
app/app.go Show resolved Hide resolved
@ccamel
Copy link
Member Author

ccamel commented Oct 5, 2024

@coderabbitai pause

Copy link
Contributor

coderabbitai bot commented Oct 5, 2024

✅ Actions performed

Reviews paused.

@ccamel
Copy link
Member Author

ccamel commented Oct 6, 2024

@coderabbitai resolve

I’ve applied the changes we talked about.

Copy link
Contributor

coderabbitai bot commented Oct 6, 2024

@ccamel: I'm glad you've applied the changes we discussed! I'll resolve the review comments.

(^•^)/


If you found this review helpful, would you consider giving us a shout-out on X?
Thank you for using CodeRabbit!

✅ Actions performed

Comments resolved.

Copy link
Member

@amimart amimart left a comment

Choose a reason for hiding this comment

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

Nice one thanks!

@ccamel ccamel merged commit 274bf3b into main Oct 7, 2024
20 checks passed
@ccamel ccamel deleted the feat/predicate-iterate branch October 7, 2024 11:17
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.

2 participants