-
Notifications
You must be signed in to change notification settings - Fork 64
Update xcclookup #1920
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
Update xcclookup #1920
Conversation
WalkthroughThis update introduces a major refactor to the Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant HTTPHandler
participant Service
participant CacheManager
participant ClaimsService
participant Logger
User->>HTTPHandler: HTTP Request (e.g., /assets/{address})
HTTPHandler->>Logger: Log request received
HTTPHandler->>Service: GetAssets(address)
Service->>CacheManager: GetConnections()
Service->>ClaimsService: OsmosisClaim/UmeeClaim/LiquidClaim()
ClaimsService->>CacheManager: (if needed) Get relevant cache
Service->>Logger: Log claim results/errors
Service-->>HTTPHandler: Aggregated assets, errors
HTTPHandler->>Logger: Log response
HTTPHandler-->>User: HTTP Response (JSON, headers set)
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (8)
🚧 Files skipped from review as they are similar to previous changes (8)
⏰ 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). (6)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
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: 30
🔭 Outside diff range comments (2)
Dockerfile (1)
17-20: Alpine version mismatch between stagesBuilder:
alpine3.21→ Final:alpine:3.20.
If the binary is not fully static, this can introduce musl‐libc incompatibilities.-FROM alpine:3.20 +FROM alpine:3.21icq-relayer/.golangci.yml (1)
110-138: Remove duplicate configuration sectionsThe
formatterssection contains duplicateexclusionsconfiguration that should be removed.custom-order: true - exclusions: - generated: lax - paths: - - third-party-chains - - third_party$ - - builtin$ - - examples$
♻️ Duplicate comments (3)
xcclookup/pkgs/types/output.go (1)
23-25: Address non-deterministic map iteration.The iteration over the errors map may produce non-deterministic results due to Go's map iteration order. This could lead to inconsistent error message ordering.
Consider sorting the keys before iteration:
if len(errors) > 0 { var err error + // Sort keys for deterministic error ordering + keys := make([]string, 0, len(errors)) + for key := range errors { + keys = append(keys, key) + } + sort.Strings(keys) + for _, key := range keys { + e := errors[key] - for key, e := range errors { err = multierr.Append(err, fmt.Errorf("%s: %w", key, e)) }xcclookup/pkgs/types/mapped_address_test.go (1)
41-41: Tests intentionally use localhost URLs for error simulation.The security warnings about localhost usage are not applicable here as these URLs are deliberately invalid to test error handling paths. The tests expect these connections to fail.
Also applies to: 54-54, 87-87, 361-361, 378-378, 404-404
xcclookup/pkgs/claims/osmosis.go (1)
427-568: Collected errors are never returned or used.Similar to
GetOsmosisClaim, this function collects errors in theerrsmap but never returns or aggregates them.
🧹 Nitpick comments (31)
xcclookup/tools/tools.go (1)
12-17: Good implementation of the tools pattern with a minor formatting issue.The tool selection and build constraints are appropriate for managing development dependencies. However, there's inconsistent indentation on line 14.
Fix the indentation inconsistency:
import ( _ "github.com/client9/misspell/cmd/misspell" - _ "github.com/golangci/golangci-lint/v2/cmd/golangci-lint" + _ "github.com/golangci/golangci-lint/v2/cmd/golangci-lint" _ "golang.org/x/tools/cmd/goimports" _ "mvdan.cc/gofumpt" )proto/Dockerfile (1)
2-2: Pin base image by digest for reproducible builds
golang:1.24.5-alpine3.22is still a moving tag (new patch rebuilds may be pushed). Consider pinning by digest to guarantee identical layers across CI runs.-FROM golang:1.24.5-alpine3.22 +FROM golang@sha256:<digest>-alpine3.22(Swap
<digest>for the actual value –docker pullwill show it).xcclookup/Dockerfile.local (1)
1-4: Add explicit entrypoint & non-root userThe container currently lands the binary but leaves execution semantics implicit and runs as root. A minimal hardening pass:
FROM alpine +RUN adduser -S -D xcc +USER xcc COPY xcc /xcc +ENTRYPOINT ["/xcc"]This keeps the image non-root and self-documenting.
icq-relayer/Dockerfile (1)
1-1: Pin image digests & drop unneeded runtime packagesGreat to see the upgrade, but two small follow-ups:
- Reproducibility – pin both stages by digest (same rationale as other Dockerfiles).
- Runtime layer installs
jqandcurl; if they’re only used in CI scripts rather than at container start-up, removing them drops ~8 MB.-FROM golang:1.24.5-alpine3.22 as build +FROM golang@sha256:<digest>-alpine3.22 as build … -FROM alpine:3.22 +FROM alpine@sha256:<digest> -RUN apk add --no-cache ca-certificates jq curl +RUN apk add --no-cache ca-certificatesAlso applies to: 19-19
.github/workflows/buildtest.yaml (1)
38-39: Centralise Go version to eliminate triple-maintenanceThe same
go-version: "1.24.5"string appears in three jobs (and other workflows). Duplicated literals drift easily.
Consider a repository secret/variable or a reusable workflow that sets up Go, e.g.:# .github/workflows/.variables.yml (example) env: GO_VERSION: "1.24.5"Then reference
${{ env.GO_VERSION }}everywhere.Also applies to: 71-72, 124-125
.github/workflows/devskim.yml (1)
19-19: Consider pinning to a specific Ubuntu image for deterministic builds
ubuntu-latestis an alias that can jump to a new LTS without warning (e.g., 24.04). DevSkim versions or other tooling may break silently when the image advances. Pinning (ubuntu-22.04orubuntu-24.04) and bumping intentionally keeps CI reproducible.xcclookup/Dockerfile (2)
2-4:ARG VERSIONandARG COMMITare unusedBuild args increase cognitive load and invalidate the Docker layer cache.
Drop them or use them (e.g.,LABEL org.opencontainers.image.revision=$COMMIT).
11-11: Build context may be larger than necessary
make buildcompiles every Quicksilver binary, inflating build time and image size.
If thexcclookupMakefile supports a narrow target, consider:-RUN make build +RUN make -C xcclookup buildThis keeps the builder cache small and avoids unnecessary module downloads.
.github/workflows/icq-relayer-build-test.yml (1)
22-24: Cache key limited togo.sumpath – misses top-levelgo.modchangesBecause
icq-relayer/go.modgoverns the module graph, touching it will not invalidate the cache. Add it tocache-dependency-path:cache-dependency-path: | icq-relayer/go.sum icq-relayer/go.modxcclookup/README.md (2)
19-27: Add language specification to YAML code blockThe configuration example should specify the language for better syntax highlighting and tooling support.
-``` +```yaml source_chain: quicktest-1 source_lcd: https://lcd.dev.quicksilver.zone chains: quickgaia-1: http://172.17.0.1:21401 quickstar-1: http://172.17.0.1:22401 quickosmo-1: http://172.17.0.1:23101--- `38-51`: **Add language specification to Docker Compose code block** The docker-compose example should specify the language for better syntax highlighting and tooling support. ```diff -``` +```yaml version: '3.7' services: xcclookup: image: quicksilverzone/xcclookup:v0.3.0 volumes: - /data/xcclookup:/config ports: - 8090:8090 command: - /xcc - -f - /config/config.yaml</blockquote></details> <details> <summary>xcclookup/pkgs/types/version.go (1)</summary><blockquote> `24-27`: **Optimize the legacy function to avoid repeated allocations.** The legacy function creates a new VersionService instance on every call, which is inefficient. Consider using a package-level singleton or making it a pure function call. ```diff +var defaultVersionService = &VersionService{} + func GetVersion() ([]byte, error) { - vs := &VersionService{} - return vs.GetVersion() + return defaultVersionService.GetVersion() }xcclookup/Makefile (2)
1-1: Add missing standard phony targets for completeness.The static analysis tool correctly identifies missing standard phony targets. Consider adding these for better Makefile completeness:
-.PHONY: build +.PHONY: all build clean test docker docker-push + +all: build + +clean: + go clean + +test: + go test ./...Also applies to: 31-31, 37-37
34-36: Consider consolidating the formatting commands for better maintainability.The formatting target runs three separate find commands with identical patterns. This could be consolidated for better maintainability:
format: - @find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/docs/statik/statik.go" -not -name '*.pb.go' -not -name '*.gw.go' | xargs go run mvdan.cc/gofumpt -w . - @find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/docs/statik/statik.go" -not -name '*.pb.go' -not -name '*.gw.go' | xargs go run github.com/client9/misspell/cmd/misspell -w - @find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/docs/statik/statik.go" -not -name '*.pb.go' -not -name '*.gw.go' | xargs go run golang.org/x/tools/cmd/goimports -w -local github.com/quicksilver-zone/quicksilver/xcclookup + @GO_FILES=$$(find . -name '*.go' -type f -not -path "./vendor*" -not -path "*.git*" -not -path "./client/docs/statik/statik.go" -not -name '*.pb.go' -not -name '*.gw.go'); \ + echo "$$GO_FILES" | xargs go run mvdan.cc/gofumpt -w .; \ + echo "$$GO_FILES" | xargs go run github.com/client9/misspell/cmd/misspell -w; \ + echo "$$GO_FILES" | xargs go run golang.org/x/tools/cmd/goimports -w -local github.com/quicksilver-zone/quicksilver/xcclookupxcclookup/config.yaml (1)
24-66: Consider moving mock examples to documentation or separate file.The large commented-out mocks section with detailed example data might be better placed in:
- A separate example configuration file
- Documentation or README
- Test fixtures directory
This would keep the main config file cleaner and more focused on actual configuration.
xcclookup/pkgs/types/output.go (1)
41-41: Optimize JSON output writing.The string conversion is unnecessary when writing JSON bytes to the response writer.
- fmt.Fprint(w, string(jsonOut)) + w.Write(jsonOut)xcclookup/TESTING.md (1)
76-78: Clarify the test runner script pathThe script path
./run_tests.shassumes execution from the xcclookup directory. Consider clarifying the full path for consistency.-./run_tests.sh +cd xcclookup && ./run_tests.shxcclookup/pkgs/types/config.go (1)
39-47: Consider pre-allocating slice capacity for better performance.The slice is initialized with 0 capacity and then appended to. For better performance, consider pre-allocating with the maximum possible capacity.
func (i Ignores) GetIgnoresForType(ignoreType string) Ignores { - out := make(Ignores, 0) + out := make(Ignores, 0, len(i)) for _, ignore := range i { if ignore.Type == ignoreType { out = append(out, ignore) } } return out }xcclookup/pkgs/claims/umee.go (1)
27-160: Consider refactoring this function for better maintainability.The function is 133 lines long with complex nested logic. Consider breaking it down into smaller, more focused functions.
Consider extracting the following into separate functions:
- Address conversion logic (lines 38-47)
- Client creation and configuration lookup (lines 49-61)
- Leverage balance query logic (lines 66-82)
- Token processing loop (lines 101-156)
This would improve readability, testability, and maintainability.
xcclookup/xcc.go (3)
79-80: Consider dependency injection for cache manager.The global
cacheMgrvariable makes testing more difficult and creates hidden dependencies. Consider passing it as a parameter or creating it within main().
116-150: Refactor repetitive cache initialization.The cache initialization code is repetitive and could be simplified using a slice of cache configurations.
type cacheConfig struct { cache interface{} endpoint string dataType string expiration time.Duration } cacheConfigs := []cacheConfig{ {&types.Cache[prewards.ConnectionProtocolData]{}, "/quicksilver/participationrewards/v1/protocoldata/ProtocolDataTypeConnection/", types.DataTypeProtocolData, time.Minute * 5}, {&types.Cache[prewards.OsmosisParamsProtocolData]{}, "/quicksilver/participationrewards/v1/protocoldata/ProtocolDataTypeOsmosisParams/", types.DataTypeProtocolData, time.Hour * 24}, // ... other caches } for _, cc := range cacheConfigs { if err := cacheMgr.Add(ctx, cc.cache, cfg.SourceLcd+cc.endpoint, cc.dataType, cc.expiration); err != nil { log.Error("Failed to add cache", "endpoint", cc.endpoint, "error", err) return } }
189-198: Add additional server timeouts for better resilience.Consider adding WriteTimeout and IdleTimeout to prevent resource exhaustion.
server := &http.Server{ Addr: fmt.Sprintf(":%d", bindPort), Handler: r, ReadHeaderTimeout: 10 * time.Second, + WriteTimeout: 30 * time.Second, + IdleTimeout: 60 * time.Second, } if err := server.ListenAndServe(); err != nil { log.Error("Server error", "error", err.Error()) - return + os.Exit(1) }xcclookup/pkgs/types/mapped_address.go (1)
52-62: Optimize chain ID lookup with a map.The nested loop for finding matching connections could be optimized using a map for O(1) lookups instead of O(n).
+ // Build a map for faster lookups + connectionMap := make(map[string]prewards.ConnectionProtocolData) + for _, conn := range connections { + connectionMap[conn.ChainID] = conn + } addressMap := map[string]string{} for chain, addrBytes := range maResponse.RemoteAddressMap { - for _, connection := range connections { - if connection.ChainID == chain { - addressMap[chain], err = addressutils.EncodeAddressToBech32(connection.Prefix, sdk.AccAddress(addrBytes)) - if err != nil { - errs = multierr.Append(errs, fmt.Errorf("addressMap:%s: %w", chain, err)) - } - } - } + if connection, found := connectionMap[chain]; found { + addressMap[chain], err = addressutils.EncodeAddressToBech32(connection.Prefix, sdk.AccAddress(addrBytes)) + if err != nil { + errs = multierr.Append(errs, fmt.Errorf("addressMap:%s: %w", chain, err)) + } + } }xcclookup/.golangci.yml (1)
79-87: Remove arguments from disabled rule.The
unhandled-errorrule is disabled, so the arguments configuration is unnecessary and could be confusing.- name: unhandled-error - arguments: - - b.WriteString - - respJSON.Write - - fmt.Printf - - fmt.Print - - fmt.Println - - fmt.Fprintf disabled: truexcclookup/pkgs/services/claims_service.go (1)
28-42: Extract repeated type casting logicThe cache manager type casting pattern is repeated in all three methods. Consider extracting this to reduce duplication.
Add a helper method:
+// getConcreteCacheManager returns the concrete cache manager or an error +func (c *ClaimsService) getConcreteCacheManager() (*types.CacheManager, error) { + if concreteCacheMgr, ok := c.cacheMgr.(*types.CacheManager); ok { + return concreteCacheMgr, nil + } + return nil, types.ErrUnsupportedCacheManager +} // OsmosisClaim implements ClaimsServiceInterface func (c *ClaimsService) OsmosisClaim(ctx context.Context, address, submitAddress, chain string, height int64) (types.OsmosisResult, error) { - // For now, we'll need to cast the cache manager to the concrete type - // This is a limitation of the current design - we need to refactor the claims package - // to use interfaces instead of concrete types - if concreteCacheMgr, ok := c.cacheMgr.(*types.CacheManager); ok { + concreteCacheMgr, err := c.getConcreteCacheManager() + if err != nil { + return types.OsmosisResult{}, err + } result := claims.OsmosisClaim(ctx, c.cfg, concreteCacheMgr, address, submitAddress, chain, height) return types.OsmosisResult{ Err: result.Err, OsmosisPool: types.OsmosisPool(result.OsmosisPool), OsmosisClPool: types.OsmosisClPool(result.OsmosisClPool), }, nil - } - return types.OsmosisResult{}, types.ErrUnsupportedCacheManager }xcclookup/pkgs/types/output_test.go (1)
398-428: Clarify or implement JSON marshaling error testThe test comment mentions testing JSON marshaling failure, but the actual test doesn't trigger a marshaling error. Either update the comment to reflect what's being tested or implement a proper JSON marshaling error test.
To properly test JSON marshaling errors, you could use a type that can't be marshaled:
func TestOutputResponseJSONMarshalError(t *testing.T) { // Create a response with a channel that can't be marshaled type unmarshalable struct { Channel chan int } // Mock the response type or use reflection to inject unmarshalable data // This would require modifying the output function to return errors // or testing the error handling path differently }Or update the comment to reflect the actual test:
- // Test error handling when JSON marshaling fails - // This is a bit tricky to test, but we can test the error path - // Mock the json.Marshal to fail - // Since we can't easily mock json.Marshal, we'll test the error handling - // by creating a response that should work normally + // Test that successful responses return 200 OK with proper headersxcclookup/pkgs/services/assets_service.go (2)
108-226: Consider error key uniqueness in concurrent scenariosMultiple goroutines might overwrite the same error keys (e.g., "OsmosisClaim", "UmeeClaim") when processing different addresses. Consider making error keys more specific.
// Use more specific error keys errs[fmt.Sprintf("OsmosisClaim:%s", claimAddress)] = err // or errs[fmt.Sprintf("OsmosisClaim:original")] = err errs[fmt.Sprintf("OsmosisClaim:mapped")] = err
106-268: Add context cancellation handling in goroutinesThe goroutines should check for context cancellation to allow graceful shutdown.
go func() { defer wg.Done() select { case <-ctx.Done(): errsMutex.Lock() errs["OsmosisClaim"] = ctx.Err() errsMutex.Unlock() return default: // existing claim processing logic } }()xcclookup/pkgs/claims/liquid.go (2)
66-66: Fix typo in comment- // explitly don't use quick prefix here, as mapped accounts may have a different prefix + // explicitly don't use quick prefix here, as mapped accounts may have a different prefix
156-160: Clean up debug logging and commentsThe debug log might be too verbose if there are many tokens, and there's an incomplete comment.
) - log.Debug("Querying for value (liquid tokens)", "chain", chain, "address", address, "denom", tuple.denom) - // 7: if err != nil { + log.Error("Failed to query liquid token balance", "chain", chain, "address", address, "denom", tuple.denom, "error", err) return nil, nil, fmt.Errorf("%w [ABCIQueryWithOptions/gamm_tokens]", err) } + log.Debug("Successfully queried liquid token balance", "chain", chain, "address", address, "denom", tuple.denom)xcclookup/pkgs/types/mapped_address_test.go (1)
122-149: Consider implementing RPC client mocking for more comprehensive testing.While the current test verifies basic error handling, implementing an RPC client mock would allow testing successful paths and specific error scenarios more thoroughly.
Would you like me to generate an RPC client mock implementation for more comprehensive testing?
…or and replace with ubers library; add headers to output
4c4d5b5 to
c145efb
Compare
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 comments (1)
xcclookup/go.mod (1)
13-17: Duplicatego.uber.org/multierrentry will breakgo mod tidy / go build.
go.uber.org/multierrappears as a direct dependency at lines 13-14 and again as an indirect dependency at lines 280-281.
Go disallows duplicaterequiredirectives – even when the versions match – and will error with:go: duplicate requirement: go.uber.org/multierrKeep a single occurrence (preferably the direct one) and run
go mod tidyto drop the redundant indirect stanza.@@ - go.uber.org/multierr v1.11.0 @@ -go.uber.org/multierr v1.11.0 // indirectAlso applies to: 280-281
♻️ Duplicate comments (9)
xcclookup/pkgs/types/version.go (1)
14-14: Consider making the version configurable via build flags.The hardcoded version "1.0.0" should ideally be injected at build time to ensure version consistency across releases.
xcclookup/pkgs/types/mapped_address_test.go (2)
431-431: Performance test timeout assertions may cause flaky tests.The hardcoded 10ms timeout assertion could fail on slower CI systems or under load. Consider using a more lenient timeout.
456-456: Performance test timeout assertions may cause flaky tests.The hardcoded 10ms timeout assertion could fail on slower CI systems or under load. Consider using a more lenient timeout.
xcclookup/pkgs/handlers/cache.go (1)
25-32: Improve error handling and HTTP response formatting.The error handling has several issues:
- No proper HTTP status code is set for errors (should be 500 for internal errors)
- Missing Content-Type header for JSON responses
- Error response format is inconsistent (plain text vs JSON)
xcclookup/pkgs/handlers/cache_handler_test.go (1)
46-51: Handler should set appropriate HTTP status code on errors.The comment indicates that the handler doesn't set status code on error, returning 200 OK even when there's an error. This violates HTTP semantics - errors should return appropriate status codes.
xcclookup/pkgs/handlers/assets_handler_test.go (1)
21-105: Enhance test coverage by verifying service interactions.The test mocks the output function but doesn't verify it's called with the expected parameters. Consider capturing and asserting the actual output as suggested in the previous review.
xcclookup/pkgs/types/cache.go (3)
49-52: AddMocks function still has safety issues.The function doesn't check if the cache exists before type assertion, which could cause a panic.
Apply this diff to add safety checks:
func AddMocks[T prewards.ConnectionProtocolData | prewards.OsmosisParamsProtocolData | prewards.OsmosisPoolProtocolData | prewards.OsmosisClPoolProtocolData | prewards.LiquidAllowedDenomProtocolData | prewards.UmeeParamsProtocolData | icstypes.Zone](ctx context.Context, mgr *CacheManager, mocks []T) { - cache, _ := mgr.Data[new(Cache[T]).Type()].(*Cache[T]) - cache.SetMock(mocks) + if mgr != nil && mgr.Data != nil { + if elem, ok := mgr.Data[new(Cache[T]).Type()]; ok { + if cache, ok := elem.(*Cache[T]); ok { + cache.SetMock(mocks) + } + } + } }
104-108: AddMocks method is still not implemented.This stub implementation continues to not actually add mocks, as noted in previous reviews.
This method should either be properly implemented or removed if not needed:
// AddMocks implements CacheManagerInterface func (m *CacheManager) AddMocks(ctx context.Context, mocks interface{}) error { - // This is a simplified implementation - in practice you'd need to handle different types - return nil + return fmt.Errorf("AddMocks is not implemented - use type-specific AddMocks function instead") }
205-205: Correct use of pointer receiver for state modification.The pointer receiver ensures proper state updates when the cache is modified.
However, the thread-safety issue from previous reviews still needs to be addressed. The Cache struct is not thread-safe and could lead to race conditions when accessed concurrently.
Consider adding synchronization:
+import "sync" type Cache[T any] struct { + mu sync.RWMutex dataType int url string cache []T lastUpdated time.Time duration time.Duration mockData []T }And protect access in the Get method:
func (c *Cache[T]) Get(ctx context.Context) ([]T, error) { + c.mu.RLock() + needsUpdate := time.Now().After(c.lastUpdated.Add(c.duration)) + c.mu.RUnlock() + + if needsUpdate { - if time.Now().After(c.lastUpdated.Add(c.duration)) { err := c.Fetch(ctx) if err != nil { return nil, err } } + + c.mu.RLock() + defer c.mu.RUnlock() return append(c.cache, c.mockData...), nil }
🧹 Nitpick comments (4)
xcclookup/pkgs/handlers/cache_handler_test.go (1)
127-127: Use t.Context() instead of context.Background() in tests.The static analysis correctly suggests using
t.Context()for better test lifecycle management and automatic cleanup.Apply this diff:
- handlerFunc := GetCacheHandler(context.Background(), cfg, mockCacheManager) + handlerFunc := GetCacheHandler(t.Context(), cfg, mockCacheManager)xcclookup/pkgs/handlers/assets_handler_test.go (1)
129-129: Use t.Context() instead of context.Background() in tests.The static analysis correctly identifies that
t.Context()should be used instead ofcontext.Background()in tests for better test lifecycle management and cancellation support.Apply this diff:
- handlerFunc := GetAssetsHandler(context.Background(), cfg, mockCacheManager, mockClaimsService, heights, outputFunc) + handlerFunc := GetAssetsHandler(t.Context(), cfg, mockCacheManager, mockClaimsService, heights, outputFunc)xcclookup/pkgs/services/assets_service_test.go (1)
160-160: Use t.Context() instead of context.Background() in tests.The static analysis correctly identifies that
t.Context()should be used instead ofcontext.Background()in tests for better test lifecycle management.Apply this diff:
- response, errs := service.GetAssets(context.Background(), tt.address) + response, errs := service.GetAssets(t.Context(), tt.address)xcclookup/pkgs/types/cache.go (1)
39-46: Excellent defensive programming with nil checks and error handling.The added nil check and explicit error handling for missing cache types significantly improves robustness.
However, address the static analysis hint:
- return nil, fmt.Errorf("cache manager is nil") + return nil, errors.New("cache manager is nil")Don't forget to add the
errorsimport at the top of the file.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (39)
tools/tools.go(0 hunks)xcclookup/README.md(1 hunks)xcclookup/TESTING.md(1 hunks)xcclookup/config.yaml(2 hunks)xcclookup/go.mod(1 hunks)xcclookup/pkgs/claims/liquid.go(6 hunks)xcclookup/pkgs/claims/liquid_test.go(1 hunks)xcclookup/pkgs/claims/osmosis.go(2 hunks)xcclookup/pkgs/claims/umee.go(7 hunks)xcclookup/pkgs/handlers/assets.go(1 hunks)xcclookup/pkgs/handlers/assets_handler_test.go(1 hunks)xcclookup/pkgs/handlers/cache.go(1 hunks)xcclookup/pkgs/handlers/cache_handler_test.go(1 hunks)xcclookup/pkgs/handlers/version.go(1 hunks)xcclookup/pkgs/handlers/version_handler_test.go(1 hunks)xcclookup/pkgs/integration/handlers_integration_test.go(1 hunks)xcclookup/pkgs/logger/logger.go(1 hunks)xcclookup/pkgs/mocks/mock_cache_manager.go(1 hunks)xcclookup/pkgs/mocks/mock_claims_service.go(1 hunks)xcclookup/pkgs/mocks/mock_version_service.go(1 hunks)xcclookup/pkgs/services/assets_service.go(1 hunks)xcclookup/pkgs/services/assets_service_test.go(1 hunks)xcclookup/pkgs/services/cache_service.go(1 hunks)xcclookup/pkgs/services/cache_service_test.go(1 hunks)xcclookup/pkgs/services/claims_service.go(1 hunks)xcclookup/pkgs/services/version_service.go(1 hunks)xcclookup/pkgs/services/version_service_test.go(1 hunks)xcclookup/pkgs/types/cache.go(5 hunks)xcclookup/pkgs/types/cache_test.go(1 hunks)xcclookup/pkgs/types/config.go(2 hunks)xcclookup/pkgs/types/interfaces.go(1 hunks)xcclookup/pkgs/types/mapped_address.go(3 hunks)xcclookup/pkgs/types/mapped_address_test.go(1 hunks)xcclookup/pkgs/types/output.go(1 hunks)xcclookup/pkgs/types/output_test.go(1 hunks)xcclookup/pkgs/types/rpc.go(3 hunks)xcclookup/pkgs/types/version.go(1 hunks)xcclookup/run_tests.sh(1 hunks)xcclookup/xcc.go(5 hunks)
💤 Files with no reviewable changes (1)
- tools/tools.go
✅ Files skipped from review due to trivial changes (5)
- xcclookup/README.md
- xcclookup/pkgs/claims/umee.go
- xcclookup/pkgs/claims/osmosis.go
- xcclookup/pkgs/claims/liquid.go
- xcclookup/pkgs/types/mapped_address.go
🚧 Files skipped from review as they are similar to previous changes (21)
- xcclookup/pkgs/mocks/mock_version_service.go
- xcclookup/pkgs/types/config.go
- xcclookup/run_tests.sh
- xcclookup/pkgs/types/rpc.go
- xcclookup/pkgs/services/version_service.go
- xcclookup/pkgs/handlers/version_handler_test.go
- xcclookup/config.yaml
- xcclookup/pkgs/services/cache_service_test.go
- xcclookup/pkgs/mocks/mock_claims_service.go
- xcclookup/xcc.go
- xcclookup/pkgs/services/cache_service.go
- xcclookup/pkgs/services/version_service_test.go
- xcclookup/pkgs/mocks/mock_cache_manager.go
- xcclookup/pkgs/services/claims_service.go
- xcclookup/pkgs/handlers/version.go
- xcclookup/pkgs/types/output_test.go
- xcclookup/pkgs/types/output.go
- xcclookup/pkgs/services/assets_service.go
- xcclookup/pkgs/claims/liquid_test.go
- xcclookup/pkgs/types/interfaces.go
- xcclookup/pkgs/handlers/assets.go
🧰 Additional context used
🧠 Learnings (9)
xcclookup/go.mod (1)
Learnt from: joe-bowman
PR: quicksilver-zone/quicksilver#1821
File: icq-relayer/go.mod:214-214
Timestamp: 2025-02-16T19:50:23.555Z
Learning: The icq-relayer daemon in the Quicksilver project requires using the local version of the quicksilver module (`../`) via the `replace` directive in its go.mod, as it needs to always use the current version from the same repository.
xcclookup/TESTING.md (1)
Learnt from: arhamchordia
PR: quicksilver-zone/quicksilver#1803
File: x/supply/keeper/keeper_test.go:31-66
Timestamp: 2025-01-28T19:03:57.668Z
Learning: Avoid suggesting test cases that duplicate functionality already tested in msg_server_test.go, particularly for module account operations and balance transfers. Focus on unique keeper functionality instead.
xcclookup/pkgs/types/cache_test.go (1)
Learnt from: arhamchordia
PR: quicksilver-zone/quicksilver#1803
File: x/supply/keeper/keeper_test.go:31-66
Timestamp: 2025-01-28T19:03:57.668Z
Learning: Avoid suggesting test cases that duplicate functionality already tested in msg_server_test.go, particularly for module account operations and balance transfers. Focus on unique keeper functionality instead.
xcclookup/pkgs/types/mapped_address_test.go (1)
Learnt from: arhamchordia
PR: quicksilver-zone/quicksilver#1803
File: x/supply/keeper/keeper_test.go:31-66
Timestamp: 2025-01-28T19:03:57.668Z
Learning: Avoid suggesting test cases that duplicate functionality already tested in msg_server_test.go, particularly for module account operations and balance transfers. Focus on unique keeper functionality instead.
xcclookup/pkgs/handlers/assets_handler_test.go (1)
Learnt from: arhamchordia
PR: quicksilver-zone/quicksilver#1803
File: x/supply/keeper/keeper_test.go:31-66
Timestamp: 2025-01-28T19:03:57.668Z
Learning: Avoid suggesting test cases that duplicate functionality already tested in msg_server_test.go, particularly for module account operations and balance transfers. Focus on unique keeper functionality instead.
xcclookup/pkgs/handlers/cache_handler_test.go (1)
Learnt from: arhamchordia
PR: quicksilver-zone/quicksilver#1803
File: x/supply/keeper/keeper_test.go:31-66
Timestamp: 2025-01-28T19:03:57.668Z
Learning: Avoid suggesting test cases that duplicate functionality already tested in msg_server_test.go, particularly for module account operations and balance transfers. Focus on unique keeper functionality instead.
xcclookup/pkgs/integration/handlers_integration_test.go (1)
Learnt from: arhamchordia
PR: quicksilver-zone/quicksilver#1803
File: x/supply/keeper/keeper_test.go:31-66
Timestamp: 2025-01-28T19:03:57.668Z
Learning: Avoid suggesting test cases that duplicate functionality already tested in msg_server_test.go, particularly for module account operations and balance transfers. Focus on unique keeper functionality instead.
xcclookup/pkgs/services/assets_service_test.go (1)
Learnt from: arhamchordia
PR: quicksilver-zone/quicksilver#1803
File: x/supply/keeper/keeper_test.go:31-66
Timestamp: 2025-01-28T19:03:57.668Z
Learning: Avoid suggesting test cases that duplicate functionality already tested in msg_server_test.go, particularly for module account operations and balance transfers. Focus on unique keeper functionality instead.
xcclookup/pkgs/types/cache.go (1)
Learnt from: arhamchordia
PR: quicksilver-zone/quicksilver#1803
File: x/supply/keeper/keeper_test.go:31-66
Timestamp: 2025-01-28T19:03:57.668Z
Learning: Avoid suggesting test cases that duplicate functionality already tested in msg_server_test.go, particularly for module account operations and balance transfers. Focus on unique keeper functionality instead.
🧬 Code Graph Analysis (4)
xcclookup/pkgs/types/version.go (2)
xcclookup/pkgs/services/version_service.go (1)
VersionService(8-10)xcclookup/xcc.go (1)
Version(45-45)
xcclookup/pkgs/handlers/cache.go (2)
xcclookup/pkgs/services/cache_service.go (2)
CacheService(22-24)NewCacheService(27-31)xcclookup/pkgs/types/interfaces.go (1)
CacheManagerInterface(24-33)
xcclookup/pkgs/handlers/assets_handler_test.go (6)
xcclookup/pkgs/types/rpc.go (1)
Response(57-61)xcclookup/pkgs/mocks/mock_cache_manager.go (1)
MockCacheManager(13-22)x/participationrewards/types/protocol_data.go (1)
ConnectionProtocolData(65-71)xcclookup/pkgs/mocks/mock_claims_service.go (1)
MockClaimsService(14-18)xcclookup/pkgs/services/assets_service.go (1)
NewAssetsService(23-35)xcclookup/pkgs/handlers/assets.go (2)
NewAssetsHandler(20-25)GetAssetsHandler(42-53)
xcclookup/pkgs/types/cache.go (5)
x/participationrewards/types/protocol_data.go (1)
ConnectionProtocolData(65-71)x/participationrewards/types/submodule_osmosis.go (1)
OsmosisPoolProtocolData(25-33)x/participationrewards/types/submodule_osmosis_cl.go (1)
OsmosisClPoolProtocolData(23-31)x/participationrewards/types/submodule_liquid.go (1)
LiquidAllowedDenomProtocolData(9-18)xcclookup/pkgs/logger/logger.go (1)
FromContext(88-94)
🪛 GitHub Check: devskim
xcclookup/pkgs/types/cache_test.go
[notice] 144-144: Accessing localhost could indicate debug code, or could hinder scaling.
Do not leave debug code in production
[notice] 158-158: Accessing localhost could indicate debug code, or could hinder scaling.
Do not leave debug code in production
[warning] 367-367: An HTTP-based URL without TLS was detected.
Insecure URL
xcclookup/pkgs/integration/handlers_integration_test.go
[warning] 135-135: An HTTP-based URL without TLS was detected.
Insecure URL
[warning] 136-136: An HTTP-based URL without TLS was detected.
Insecure URL
xcclookup/pkgs/services/assets_service_test.go
[warning] 144-144: An HTTP-based URL without TLS was detected.
Insecure URL
[warning] 145-145: An HTTP-based URL without TLS was detected.
Insecure URL
[warning] 146-146: An HTTP-based URL without TLS was detected.
Insecure URL
[warning] 281-281: An HTTP-based URL without TLS was detected.
Insecure URL
[warning] 282-282: An HTTP-based URL without TLS was detected.
Insecure URL
[warning] 283-283: An HTTP-based URL without TLS was detected.
Insecure URL
🪛 GitHub Check: lint-xcclookup
xcclookup/pkgs/handlers/assets_handler_test.go
[failure] 129-129:
context.Background() could be replaced by t.Context() in TestGetAssetsHandler (usetesting)
xcclookup/pkgs/handlers/cache_handler_test.go
[failure] 127-127:
context.Background() could be replaced by t.Context() in TestGetCacheHandler (usetesting)
xcclookup/pkgs/logger/logger.go
[failure] 71-71:
Error return value of (github.com/go-kit/log.Logger).Log is not checked (errcheck)
[failure] 66-66:
Error return value of (github.com/go-kit/log.Logger).Log is not checked (errcheck)
[failure] 61-61:
Error return value of (github.com/go-kit/log.Logger).Log is not checked (errcheck)
[failure] 56-56:
Error return value of (github.com/go-kit/log.Logger).Log is not checked (errcheck)
xcclookup/pkgs/services/assets_service_test.go
[failure] 160-160:
context.Background() could be replaced by t.Context() in TestAssetsService_GetAssets (usetesting)
[failure] 5-5:
File is not properly formatted (gci)
xcclookup/pkgs/types/cache.go
[failure] 40-40:
use-errors-new: replace fmt.Errorf by errors.New (revive)
⏰ 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). (6)
- GitHub Check: lint
- GitHub Check: test quicksilver (darwin, arm64)
- GitHub Check: test quicksilver (amd64, windows)
- GitHub Check: test quicksilver (amd64, linux)
- GitHub Check: Analyze
- GitHub Check: build (1.24.5, macos-latest)
🔇 Additional comments (28)
xcclookup/pkgs/types/version.go (3)
3-6: Import statements correctly updated for new functionality.The added imports for
encoding/jsonandruntimeare appropriate for the newVersionServiceimplementation.
8-9: Clean service struct definition.The
VersionServicestruct follows Go naming conventions and aligns with the service pattern introduced in this refactoring.
23-27: Good backward compatibility approach.The legacy function maintains backward compatibility while transitioning to the new service pattern. This is a clean migration strategy.
xcclookup/pkgs/types/mapped_address_test.go (4)
1-13: Well-organized test imports.The imports are appropriately structured and include all necessary dependencies for comprehensive testing.
14-120: Comprehensive test coverage with good structure.The test cases cover various scenarios including valid requests, empty connections, nil config, and invalid configurations. The table-driven approach is well-implemented.
151-346: Excellent coverage of height-related functions.The tests for
GetHeightsandGetZeroHeightsinclude comprehensive edge cases and consistency checks between related functions.
348-414: Valuable edge case testing.The edge case tests for empty addresses, nil connections, and context timeouts help ensure robust error handling.
xcclookup/pkgs/handlers/cache.go (2)
8-22: Well-structured handler implementation.The
CacheHandlerstruct and constructor follow the service pattern introduced in this refactoring, providing good separation of concerns.
34-43: Good dependency injection pattern.The
GetCacheHandlerfunction properly creates the service and handler dependencies, following good dependency injection practices.xcclookup/pkgs/integration/handlers_integration_test.go (4)
1-50: Well-structured integration test for version handler.The version handler integration test properly verifies HTTP responses, status codes, and content-type headers with appropriate mocking.
52-88: Comprehensive cache handler integration test.The cache handler test includes thorough mock setup and proper assertions for the cache service integration.
90-172: Comprehensive assets handler integration test.The assets handler test includes complex mocking scenarios and verifies proper integration between multiple services.
135-136: HTTP URLs in test configuration are acceptable.The HTTP URLs in the test configuration are for localhost mock services, which is standard practice in integration tests. The static analysis warning is not applicable in test context.
xcclookup/pkgs/handlers/cache_handler_test.go (2)
1-27: Well-organized test structure.The test imports and table-driven test structure follow Go testing best practices with appropriate mocking setup.
54-112: Solid test execution with proper mocking.The test execution includes comprehensive mock setup and appropriate assertions for both success and error scenarios.
xcclookup/TESTING.md (1)
1-219: Excellent comprehensive testing documentation!This documentation provides a thorough overview of the testing framework and architectural changes. It clearly explains the refactoring from monolithic to interface-based design, covers all major components, and provides practical examples. The coverage goals, best practices, and maintenance guidelines are well-defined and will help maintain code quality.
xcclookup/pkgs/services/assets_service_test.go (2)
21-183: Excellent comprehensive test coverage!The tests thoroughly cover the
AssetsServicefunctionality including successful scenarios, error handling, and edge cases. The use of mocks to isolate dependencies and the table-driven test structure are well-implemented.
185-323: Well-implemented mapped addresses test!This test effectively verifies that the service correctly uses both original and mapped addresses for claims while ensuring the submit address remains the original address. The concurrent tracking of addresses used in different protocols demonstrates good test design.
xcclookup/pkgs/types/cache_test.go (5)
17-23: Good basic constructor test.The test properly verifies the cache manager initialization and basic properties.
25-55: Excellent type system verification.This test effectively verifies that the generic cache type system works correctly for different data types.
283-355: Comprehensive HTTP fetch testing.The tests cover all important HTTP scenarios including success cases, server errors, and invalid responses. The use of
httptest.NewServeris appropriate for testing HTTP interactions.
409-435: Good concurrency safety test.This test properly verifies that cache operations are safe for concurrent access, which is important for a caching system.
524-579: Excellent end-to-end TTL refresh test.This test effectively verifies the TTL-based refresh behavior with realistic scenarios. The request counting mechanism and verification of data updates demonstrate thorough testing.
xcclookup/pkgs/types/cache.go (5)
16-16: Good addition of structured logging support.The logger package import enables structured logging throughout the cache operations, improving observability.
64-67: Clean simplification of the Add method.Directly returning the Init result makes the code more concise and readable.
69-102: Excellent addition of typed getter methods.These methods provide a clean, type-safe abstraction for accessing different types of cached data. The consistent implementation and proper delegation to the generic
GetCachefunction is well-designed.
154-154: Good improvement to error handling.The explicit error message for unknown data types provides better debugging information.
185-200: Excellent addition of structured logging.The context-aware logging with debug and error messages significantly improves observability and debugging capabilities. The explicit assignment of cache data and proper error logging are well-implemented.
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #1920 +/- ##
==========================================
+ Coverage 57.61% 57.70% +0.09%
==========================================
Files 171 171
Lines 15275 15251 -24
==========================================
Hits 8800 8800
+ Misses 5709 5685 -24
Partials 766 766
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
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: 0
♻️ Duplicate comments (2)
xcclookup/pkgs/services/assets_service_test.go (2)
142-146: Use HTTPS URLs for security.The configuration contains HTTP URLs that pose security risks. While these are test URLs, using HTTPS is a better practice.
Consider using HTTPS URLs even in tests:
cfg := types.Config{ SourceChain: "quicksilver-1", Chains: map[string]string{ - "quicksilver-1": "http://quicksilver:26657", - "osmosis-1": "http://osmosis:26657", - "umee-1": "http://umee:26657", + "quicksilver-1": "https://quicksilver:26657", + "osmosis-1": "https://osmosis:26657", + "umee-1": "https://umee:26657", }, }
279-283: Use HTTPS URLs for security.Same security concern as the previous test case.
Consider using HTTPS URLs:
Chains: map[string]string{ - "quicksilver-1": "http://quicksilver:26657", - "osmosis-1": "http://osmosis:26657", - "umee-1": "http://umee:26657", + "quicksilver-1": "https://quicksilver:26657", + "osmosis-1": "https://osmosis:26657", + "umee-1": "https://umee:26657", },
🧹 Nitpick comments (4)
xcclookup/pkgs/services/assets_service_test.go (3)
159-159: Use t.Context() instead of context.Background().Using
t.Context()provides better test cancellation and timeout handling.-response, errs := service.GetAssets(context.Background(), tt.address) +response, errs := service.GetAssets(t.Context(), tt.address)
161-167: Consider removing debug logging.The debug logging statements should be removed or converted to conditional debug output to keep test output clean.
-// Debug: print out any errors -if len(errs) > 0 { - t.Logf("Generated errors: %+v", errs) - for key, err := range errs { - t.Logf("Error key: %s, Error: %v", key, err) - } -}
298-298: Use t.Context() instead of context.Background().Same improvement as the previous test case.
-response, errs := service.GetAssets(context.Background(), originalAddress) +response, errs := service.GetAssets(t.Context(), originalAddress)x/interchainstaking/types/msgs.go (1)
63-70: Consider optimizing the helper function for better performance.The
errorMapToSlicefunction works correctly but could be optimized for better performance and memory allocation.Apply this diff for a more efficient implementation:
-// helper function to convert error map to slice for multierr -func errorMapToSlice(errs map[string]error) []error { - var errList []error - for _, err := range errs { - errList = append(errList, err) - } - return errList -} +// helper function to convert error map to slice for multierr +func errorMapToSlice(errs map[string]error) []error { + errList := make([]error, 0, len(errs)) + for _, err := range errs { + errList = append(errList, err) + } + return errList +}This pre-allocates the slice capacity to avoid repeated allocations during appends.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (15)
x/claimsmanager/types/claimsmanager.go(2 hunks)x/claimsmanager/types/genesis.go(2 hunks)x/claimsmanager/types/msgs.go(2 hunks)x/interchainstaking/keeper/intent.go(2 hunks)x/interchainstaking/types/error_test.go(1 hunks)x/interchainstaking/types/msgs.go(7 hunks)x/participationrewards/types/genesis.go(2 hunks)x/participationrewards/types/msgs.go(2 hunks)x/participationrewards/types/protocol_data.go(2 hunks)x/participationrewards/types/submodule_osmosis.go(3 hunks)x/participationrewards/types/submodule_osmosis_cl.go(2 hunks)xcclookup/pkgs/logger/logger.go(1 hunks)xcclookup/pkgs/services/assets_service_test.go(1 hunks)xcclookup/pkgs/types/cache.go(6 hunks)xcclookup/pkgs/types/config.go(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- xcclookup/pkgs/types/config.go
- xcclookup/pkgs/logger/logger.go
- xcclookup/pkgs/types/cache.go
🧰 Additional context used
🧠 Learnings (3)
x/interchainstaking/types/error_test.go (1)
Learnt from: arhamchordia
PR: quicksilver-zone/quicksilver#1803
File: x/supply/keeper/keeper_test.go:31-66
Timestamp: 2025-01-28T19:03:57.668Z
Learning: Avoid suggesting test cases that duplicate functionality already tested in msg_server_test.go, particularly for module account operations and balance transfers. Focus on unique keeper functionality instead.
x/participationrewards/types/genesis.go (1)
Learnt from: joe-bowman
PR: quicksilver-zone/quicksilver#1894
File: third-party-chains/gaia-types/liquid/types/params.go:13-16
Timestamp: 2025-06-23T13:33:14.342Z
Learning: When reviewing code that imports types from upstream blockchain projects (like Gaia/Cosmos Hub types), do not suggest modifications to their default parameter values or behaviors, as these should remain consistent with the upstream chain's specifications.
xcclookup/pkgs/services/assets_service_test.go (1)
Learnt from: arhamchordia
PR: quicksilver-zone/quicksilver#1803
File: x/supply/keeper/keeper_test.go:31-66
Timestamp: 2025-01-28T19:03:57.668Z
Learning: Avoid suggesting test cases that duplicate functionality already tested in msg_server_test.go, particularly for module account operations and balance transfers. Focus on unique keeper functionality instead.
🧬 Code Graph Analysis (1)
x/participationrewards/types/genesis.go (1)
x/participationrewards/types/participationrewards.pb.go (6)
Params(142-147)Params(150-150)Params(151-153)ProtocolData(235-238)ProtocolData(242-242)ProtocolData(243-245)
🪛 GitHub Check: lint-xcclookup
xcclookup/pkgs/services/assets_service_test.go
[failure] 298-298:
context.Background() could be replaced by t.Context() in TestAssetsService_GetAssets_WithMappedAddresses (usetesting)
[failure] 159-159:
context.Background() could be replaced by t.Context() in TestAssetsService_GetAssets (usetesting)
⏰ 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). (5)
- GitHub Check: test quicksilver (amd64, windows)
- GitHub Check: test quicksilver (amd64, linux)
- GitHub Check: test quicksilver (darwin, arm64)
- GitHub Check: lint
- GitHub Check: Analyze
🔇 Additional comments (36)
xcclookup/pkgs/services/assets_service_test.go (8)
1-18: Package structure and imports look good.The imports are well-organized with proper grouping of standard library, third-party, and local packages. The test setup follows Go conventions.
20-32: Good practice mocking the global function.The test properly saves and restores the original
GetMappedAddressesfunction, ensuring test isolation. The mock implementation is clean and appropriate for the test scope.
33-100: Comprehensive test case structure.The test cases cover both success and error scenarios effectively. The struct-based approach makes the tests readable and maintainable. The test data includes realistic mock values for different blockchain protocols.
184-202: Good address mapping test setup.The test properly mocks the address mapping functionality and sets up realistic mapped addresses for different chains.
204-206: Proper concurrency handling for tracking addresses.The use of mutexes to track addresses used in concurrent operations is well-implemented and necessary for thread safety.
309-321: Excellent verification of address mapping logic.The test thoroughly verifies that both original and mapped addresses are used appropriately for different chains, and that the submit address is always the original address. This is crucial for ensuring the address mapping feature works correctly.
324-337: Simple but effective constructor test.The constructor test covers the basic functionality of
NewAssetsServiceand verifies that all fields are properly initialized.
20-337: Comprehensive test coverage with room for improvement.Overall, this test file provides excellent coverage of the AssetsService functionality. The tests are well-structured, use proper mocking, and cover both success and error scenarios. The address mapping test is particularly thorough.
Minor improvements suggested:
- Use
t.Context()instead ofcontext.Background()- Use HTTPS URLs in test configurations
- Remove debug logging statements
- Consider adding more error scenario tests
The test file demonstrates good understanding of Go testing practices and proper separation of concerns.
x/interchainstaking/keeper/intent.go (2)
7-7: LGTM: Import updated to use Uber's multierr packageThe import change from the custom multierror library to
go.uber.org/multierraligns with the PR objectives to standardize error handling and improve serialization support.
249-253: LGTM: Error aggregation correctly migrated to multierr.CombineThe error aggregation logic has been properly updated to use the new pattern:
- Errors are collected into a slice from the map
multierr.Combineis used to combine the errors- Functional behavior remains identical while using the standardized library
x/claimsmanager/types/claimsmanager.go (2)
4-6: LGTM: Imports updated for improved error handlingThe addition of the
fmtimport and replacement of the custom multierror library withgo.uber.org/multierrsupports the improved error aggregation pattern.
19-34: LGTM: Efficient error aggregation with improved formattingThe new error handling approach using
multierr.Appendis more efficient than the map-based approach used in other files. The error messages now include field names for better context, improving debugging and user experience.x/participationrewards/types/msgs.go (2)
9-9: LGTM: Import updated to use Uber's multierr packageThe import change aligns with the codebase-wide standardization of error handling libraries.
94-98: LGTM: Error aggregation correctly migrated to multierr.CombineThe error aggregation follows the consistent pattern used throughout the codebase refactoring:
- Errors collected from the map into a slice
- Combined using
multierr.Combine- Maintains identical validation behavior
x/interchainstaking/types/error_test.go (2)
7-7: LGTM: Test updated to use Uber's multierr packageThe import change aligns with the codebase-wide library migration.
11-22: LGTM: Test logic correctly updated for new error libraryThe test has been properly updated to work with the new multierr library:
- Errors are directly created in a slice
multierr.Combineis used to combine them- The test continues to verify deterministic error string representation
x/participationrewards/types/protocol_data.go (2)
8-8: LGTM: Import updated to use Uber's multierr packageThe import change is consistent with the codebase-wide standardization effort.
93-97: LGTM: Error aggregation correctly migrated to multierr.CombineThe error aggregation pattern has been properly updated:
- Errors from the map are collected into a slice
multierr.Combineis used to combine them- Validation behavior remains identical
x/claimsmanager/types/genesis.go (2)
6-6: Clean import update to Uber's multierr package.The import change aligns with the PR objective to replace the multierror library with Uber's maintained version that supports serialization.
37-41: Proper error aggregation logic conversion.The error aggregation has been correctly updated to work with Uber's multierr package. The conversion from map values to slice before combining maintains the same functionality while using the new API.
x/claimsmanager/types/msgs.go (2)
3-3: Consistent import update across modules.The import change to
go.uber.org/multierris consistent with the broader refactoring effort.
31-35: Consistent error aggregation pattern.The error handling conversion follows the same pattern as other files in this refactoring, maintaining functionality while using the new multierr API.
x/participationrewards/types/submodule_osmosis.go (3)
8-8: Import update aligns with codebase refactoring.The import change to Uber's multierr package is consistent with the broader refactoring effort across the codebase.
113-117: Proper error aggregation in OsmosisPoolProtocolData.ValidateBasic().The error handling conversion maintains the same validation logic while using the new multierr API.
153-157: Consistent error aggregation in OsmosisParamsProtocolData.ValidateBasic().The error handling follows the same pattern as other methods in this refactoring, ensuring consistency across the codebase.
x/participationrewards/types/submodule_osmosis_cl.go (2)
8-8: Import change consistent with codebase refactoring.The update to
go.uber.org/multierraligns with the systematic refactoring across the codebase.
81-85: Consistent error aggregation conversion.The error handling conversion in OsmosisClPoolProtocolData.ValidateBasic() follows the established pattern and maintains the same validation functionality.
x/participationrewards/types/genesis.go (3)
6-6: Import update completes the codebase refactoring.The change to
go.uber.org/multierris consistent with the systematic refactoring across all validation methods.
23-23: Good variable naming improvement.Renaming from
errorstoerrsavoids potential confusion with the built-inerrorspackage and improves code clarity.
36-41: Consistent error aggregation pattern.The error handling conversion follows the established pattern across all files in this refactoring, maintaining validation functionality while using the new multierr API.
x/interchainstaking/types/msgs.go (6)
10-10: Good migration to industry standard library.The replacement of the custom multierror library with Uber's
multierris a solid architectural decision that improves maintainability and leverages a well-tested, industry-standard solution.
102-102: LGTM: Proper error aggregation using multierr.The migration from the custom multierror to
multierr.Combinewith the helper function maintains the existing validation logic while adopting the new library correctly.
149-149: LGTM: Consistent error handling pattern.The error aggregation follows the same pattern as other ValidateBasic methods and correctly uses the helper function with
multierr.Combine.
193-193: LGTM: Consistent implementation across validation methods.The error handling migration is implemented consistently with other ValidateBasic methods in the file.
249-249: LGTM: Proper error aggregation for UpdateRedemption validation.The error handling follows the established pattern and correctly integrates with the multierr library.
349-349: LGTM: Consistent error handling in SignalIntent validation.The migration maintains consistency with other ValidateBasic methods and properly handles the error map conversion.
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
🧹 Nitpick comments (5)
utils/error.go (1)
8-13: Rename loop variable & pre-allocate slice.Using
erras the map-key variable is confusing (it’s a string, not an error).
Also, you can avoid one re-allocation by pre-allocating the slice.-func ErrorMapToSlice(errs map[string]error) []error { - var errList []error - for _, err := range Keys(errs) { - errList = append(errList, fmt.Errorf("%s: %w", err, errs[err])) +func ErrorMapToSlice(errs map[string]error) []error { + errList := make([]error, 0, len(errs)) + for _, key := range Keys(errs) { + errList = append(errList, fmt.Errorf("%s: %w", key, errs[key])) } return errList }x/participationrewards/types/proposals.go (1)
59-61: Good switch tomultierr.Combine, but mind map-key variable naming.
multierr.Combine(utils.ErrorMapToSlice(errors)...)is correct and now returns a single aggregated error.Small tidy-up: consider renaming the local
errorsmap toerrsto avoid shadowing the standarderrorspackage in future edits.x/participationrewards/types/submodule_liquid.go (1)
37-39: Aggregation looks good; apply same naming clean-up.
multierr.Combinecorrectly replaces the custom multierror.
For consistency, rename localerrs/errorsmap if it shadows std imports elsewhere.x/participationrewards/keeper/distribution.go (1)
184-186: Return value ordering is correct; consider zero-value instead ofnil.When an error is returned, you currently return
nilforTokenValues.
Returning the zero value (TokenValues{}) avoids a potentialnil-map dereference if callers forget the error check but still inspect the map.- if len(errs) > 0 { - return nil, multierr.Combine(utils.ErrorMapToSlice(errs)...) + if len(errs) > 0 { + return TokenValues{}, multierr.Combine(utils.ErrorMapToSlice(errs)...) }x/participationrewards/types/participationrewards.go (1)
51-53: Non-deterministic error ordering may cause flaky tests/logs
utils.ErrorMapToSlicebuilds the slice from a map; unlessutils.Keysreturns the keys in a stable order, the combined error string produced bymultierr.Combinecan vary run-to-run.
If you compare error strings in tests, consider sorting the keys before slicing:-for _, err := range Keys(errs) { +for _, err := range slices.Sort(Keys(errs)) { // or any stable sort helperNot critical for functionality, but helpful for reproducible output.
Also applies to: 77-79, 108-110
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (4)
go.sumis excluded by!**/*.sumgo.work.sumis excluded by!**/*.sumicq-relayer/go.sumis excluded by!**/*.sumxcclookup/go.sumis excluded by!**/*.sum
📒 Files selected for processing (12)
go.mod(1 hunks)utils/error.go(1 hunks)utils/multierror/multierror.go(0 hunks)x/claimsmanager/types/genesis.go(2 hunks)x/claimsmanager/types/msgs.go(2 hunks)x/interchainstaking/types/msgs.go(6 hunks)x/participationrewards/keeper/distribution.go(2 hunks)x/participationrewards/types/genesis.go(2 hunks)x/participationrewards/types/participationrewards.go(3 hunks)x/participationrewards/types/proposals.go(2 hunks)x/participationrewards/types/submodule_liquid.go(2 hunks)xcclookup/go.mod(2 hunks)
💤 Files with no reviewable changes (1)
- utils/multierror/multierror.go
🚧 Files skipped from review as they are similar to previous changes (5)
- x/participationrewards/types/genesis.go
- x/claimsmanager/types/genesis.go
- x/claimsmanager/types/msgs.go
- x/interchainstaking/types/msgs.go
- xcclookup/go.mod
🧰 Additional context used
🧠 Learnings (3)
x/participationrewards/types/submodule_liquid.go (1)
Learnt from: joe-bowman
PR: quicksilver-zone/quicksilver#1821
File: icq-relayer/go.mod:214-214
Timestamp: 2025-02-16T19:50:23.555Z
Learning: The icq-relayer daemon in the Quicksilver project requires using the local version of the quicksilver module (`../`) via the `replace` directive in its go.mod, as it needs to always use the current version from the same repository.
x/participationrewards/keeper/distribution.go (1)
Learnt from: arhamchordia
PR: quicksilver-zone/quicksilver#1803
File: x/supply/keeper/keeper_test.go:31-66
Timestamp: 2025-01-28T19:03:57.668Z
Learning: Avoid suggesting test cases that duplicate functionality already tested in msg_server_test.go, particularly for module account operations and balance transfers. Focus on unique keeper functionality instead.
go.mod (1)
Learnt from: joe-bowman
PR: quicksilver-zone/quicksilver#1821
File: icq-relayer/go.mod:214-214
Timestamp: 2025-02-16T19:50:23.555Z
Learning: The icq-relayer daemon in the Quicksilver project requires using the local version of the quicksilver module (`../`) via the `replace` directive in its go.mod, as it needs to always use the current version from the same repository.
🧬 Code Graph Analysis (5)
x/participationrewards/types/proposals.go (1)
utils/error.go (1)
ErrorMapToSlice(8-14)
x/participationrewards/types/submodule_liquid.go (1)
utils/error.go (1)
ErrorMapToSlice(8-14)
x/participationrewards/keeper/distribution.go (1)
utils/error.go (1)
ErrorMapToSlice(8-14)
utils/error.go (1)
utils/sort.go (1)
Keys(12-22)
x/participationrewards/types/participationrewards.go (3)
utils/error.go (1)
ErrorMapToSlice(8-14)x/participationrewards/types/errors.go (2)
ErrUndefinedAttribute(7-7)ErrUnknownProtocolDataType(12-12)x/participationrewards/types/participationrewards.pb.go (6)
ProtocolData(235-238)ProtocolData(242-242)ProtocolData(243-245)ProtocolDataType(29-29)ProtocolDataType(96-98)ProtocolDataType_value(72-90)
⏰ 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). (20)
- GitHub Check: build (1.24.5, ubuntu-latest)
- GitHub Check: test (1.24.5, ubuntu-latest)
- GitHub Check: Analyze
- GitHub Check: lint
- GitHub Check: build quicksilver (amd64, darwin)
- GitHub Check: test (1.24.5, ubuntu-latest)
- GitHub Check: test quicksilver (darwin, arm64)
- GitHub Check: build (1.24.5, ubuntu-latest)
- GitHub Check: build (1.24.5, macos-latest)
- GitHub Check: test quicksilver (amd64, windows)
- GitHub Check: build quicksilver (amd64, linux)
- GitHub Check: build quicksilver (amd64, windows)
- GitHub Check: build quicksilver (darwin, arm64)
- GitHub Check: test quicksilver (amd64, linux)
- GitHub Check: build (1.24.5, macos-latest)
- GitHub Check: test (1.24.5, macos-latest)
- GitHub Check: build (1.24.5, ubuntu-latest)
- GitHub Check: build (1.24.5, macos-latest)
- GitHub Check: test (1.24.5, macos-latest)
- GitHub Check: test (1.24.5, ubuntu-latest)
🔇 Additional comments (1)
go.mod (1)
36-36: Confirm dependency hygiene.After promoting
go.uber.org/multierrto a direct dependency, rungo mod tidyandgo vet -mod=modto ensure:
- No residual references to the removed ingenuity-build multierror remain.
- The dependency graph is minimal and consistent.
1. Summary
Fixes #1918
Fixes #1915
Fixes #1919
Fixes #1922
Fixes #1923
Fixes #1924
Fixes #1925
Fixes #1926
2.Type of change
Summary by CodeRabbit
New Features
Bug Fixes
Refactor
Documentation