- 
                Notifications
    
You must be signed in to change notification settings  - Fork 1
 
Feat/bitget #5
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/bitget #5
Conversation
          
WalkthroughThe changes introduce new provider integrations and update existing ones within an API and WebSocket provider registry. Specifically, Bitget and Curve DeFi providers are added, including their API handlers, configuration structures, and registration within the provider factory. The Curve DeFi API handler is refactored to process only a single ticker and expects the response data as an object rather than an array. A new documentation guide is included to instruct users on custom endpoint configuration. Test cases and utility files are updated accordingly to match the revised handler logic and response formats. Changes
 Sequence Diagram(s)sequenceDiagram
    participant User
    participant ProviderFactory
    participant BitgetAPIHandler
    participant CurveAPIHandler
    User->>ProviderFactory: Request API handler for 'bitget' or 'curve'
    alt bitget
        ProviderFactory->>BitgetAPIHandler: Initialize with config
        BitgetAPIHandler-->>ProviderFactory: Return handler
    else curve
        ProviderFactory->>CurveAPIHandler: Initialize with config
        CurveAPIHandler-->>ProviderFactory: Return handler
    end
    ProviderFactory-->>User: Return requested API handler
    sequenceDiagram
    participant User
    participant BitgetAPIHandler
    participant BitgetAPI
    User->>BitgetAPIHandler: CreateURL([ticker])
    BitgetAPIHandler->>BitgetAPI: Format endpoint with ticker symbol
    BitgetAPI-->>BitgetAPIHandler: Return URL
    User->>BitgetAPIHandler: ParseResponse([ticker], http.Response)
    BitgetAPIHandler->>BitgetAPI: Decode JSON, extract price
    BitgetAPI-->>BitgetAPIHandler: Return price data
    BitgetAPIHandler-->>User: PriceResponse
    Poem
 Note ⚡️ AI Code Reviews for VS Code, Cursor, WindsurfCodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback. Note ⚡️ Faster reviews with cachingCodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure  📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (2)
 🚧 Files skipped from review as they are similar to previous changes (2)
 🪧 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: 6
🧹 Nitpick comments (20)
pkg/math/math.go (1)
169-174: Add documentation and unit tests forFloat64ToBigFloat: Please include a doc comment detailing its behavior (e.g., default mantissa size) and add unit tests covering typical and edge-case conversions (e.g., large/small floats, NaN/±Inf scenarios) to ensure correctness.providers/apis/defi/curve/types.go (1)
1-8: Add documentation and consider renaming to avoid stutter: The exported typeCurveMetadatalacks a doc comment; please add one above it. Additionally, since it will be referenced ascurve.CurveMetadata, consider renaming it toMetadatato reduce redundancy in usage.providers/apis/bitget/utils.go (1)
51-75: Avoid stuttering in exported types: In Go,bitget.BitgetResponseandbitget.BitgetDatastutter when used asbitget.BitgetResponse/bitget.BitgetData. Consider renaming them toResponseandDatawithin this package for improved readability. Also, update the inline JSON example comment to end sentences with periods to satisfy Go doc conventions.🧰 Tools
🪛 golangci-lint (1.64.8)
[warning] 51-51: exported: type name will be used as bitget.BitgetResponse by other packages, and that stutters; consider calling this Response
(revive)
[warning] 58-58: exported: type name will be used as bitget.BitgetData by other packages, and that stutters; consider calling this Data
(revive)
providers/apis/geckoterminal/types.go (1)
1-5: Add documentation and consider renaming to avoid stutter: The exported typeGeckoterminalMetadatashould have a doc comment explaining its purpose. Additionally, consider renaming it toMetadatasince it will be referenced asgeckoterminal.Metadata, reducing redundancy.🧰 Tools
🪛 golangci-lint (1.64.8)
[warning] 3-3: exported: type name will be used as geckoterminal.GeckoterminalMetadata by other packages, and that stutters; consider calling this Metadata
(revive)
providers/factories/oracle/api.go (1)
6-7: Fix import formatting.The imports need proper spacing between the standard library imports and third-party packages.
- "go.uber.org/zap" + "go.uber.org/zap" "net/http" "strings" +Also applies to: 9-9
🧰 Tools
🪛 golangci-lint (1.64.8)
6-6: File is not properly formatted
(gofumpt)
guide_oracle.md (3)
1-3: Add blank line after heading.According to Markdown best practices, headings should be surrounded by blank lines for better readability and proper rendering.
# Configuration for custom endpoints + This file describes how to configure and use custom endpoints in your Connect connection setup.🧰 Tools
🪛 markdownlint-cli2 (0.17.2)
1-1: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below(MD022, blanks-around-headings)
130-134: Fix Markdown formatting.The code blocks should be surrounded by blank lines and the file should end with a newline character.
with the
oracle.jsonfile path, enther the following command to run connect.
+connect --oracle-config path/to/oracle.json
<details> <summary>🧰 Tools</summary> <details> <summary>🪛 markdownlint-cli2 (0.17.2)</summary> 130-130: Fenced code blocks should be surrounded by blank lines null (MD031, blanks-around-fences) --- 132-132: Fenced code blocks should be surrounded by blank lines null (MD031, blanks-around-fences) --- 134-134: Files should end with a single newline character null (MD047, single-trailing-newline) </details> </details> --- `131-131`: **Fix typo in command instruction.** There's a typo in the explanation for the command. ```diff -with the `oracle.json` file path, enther the following command to run connect. +with the `oracle.json` file path, enter the following command to run connect.providers/websockets/bitget/utils.go (1)
3-6: Fix import orderStandard library imports should come before third-party imports.
-import ( - "github.com/skip-mev/connect/v2/oracle/config" - "time" -) +import ( + "time" + + "github.com/skip-mev/connect/v2/oracle/config" +)🧰 Tools
🪛 golangci-lint (1.64.8)
4-4: File is not properly formatted
(gofumpt)
5-5: File is not properly formatted
(gofumpt)
providers/apis/defi/curve/utils.go (1)
31-49: Well-structured response types with example documentationThe response type definitions (CurveResponse and CurveData) are clear and include helpful documentation showing the expected JSON response format.
One suggestion: Consider adding validation for the LastUpdated timestamp field when parsing the response, as it appears to be in ISO-8601 format.
In the corresponding API handler, consider adding timestamp validation:
// In the response parsing code timeValue, err := time.Parse("2006-01-02T15:04:05", curveResponse.Data.LastUpdated) if err != nil { return nil, fmt.Errorf("failed to parse timestamp: %w", err) } // Use timeValue or add it to the returned data if neededproviders/websockets/bitget/parse.go (1)
21-23: Consider using exact channel matchUsing
strings.Containsfor channel validation might be too permissive. If the channel should be exactly "ticker", consider using equality check instead.- if !strings.Contains(resp.Arg.Channel, string(TickerChannel)) { + if resp.Arg.Channel != string(TickerChannel) {providers/apis/bitget/api_handler.go (2)
17-18: Incorrect comment referenceThe comment mistakenly refers to "Coinbase API" instead of "Bitget API".
- // api is the config for the Coinbase API. + // api is the config for the Bitget API.
3-12: Import formatting issuesThe static analysis tool has flagged formatting issues with the imports.
Format the imports following Go conventions by grouping standard library imports separate from third-party imports:
import ( "encoding/json" "fmt" + "net/http" + "time" + "github.com/skip-mev/connect/v2/oracle/config" "github.com/skip-mev/connect/v2/oracle/types" "github.com/skip-mev/connect/v2/pkg/math" providertypes "github.com/skip-mev/connect/v2/providers/types" - "net/http" - "time" )🧰 Tools
🪛 golangci-lint (1.64.8)
5-5: File is not properly formatted
(gofumpt)
10-10: File is not properly formatted
(gofumpt)
providers/apis/defi/curve/api_handler.go (1)
45-66: Consider handling multiple tickers more robustly.The
CreateURLmethod only uses the first ticker and ignores the rest. While this might be the intended behavior for the Curve API, it could lead to confusion if multiple different tickers are provided.Consider adding a comment explaining why only the first ticker is used, or enhance the implementation to handle multiple tickers if the Curve API supports batch requests.
providers/websockets/bitget/ws_data_handler.go (2)
53-53: Fix commented-out unused variable.There's a commented-out variable declaration that should be removed.
- //baseResp BaseResponseAlternatively, if this variable might be needed in the future, add a comment explaining why it's commented out.
🧰 Tools
🪛 golangci-lint (1.64.8)
53-53: commentFormatting: put a space between
//and comment text(gocritic)
47-83: Review error handling in HandleMessage method.The error handling in the
HandleMessagemethod could be improved to provide more context about what went wrong during unmarshaling, especially since you're already logging the error.} else { h.logger.Debug("failed to unmarshal ticker update message", zap.Error(err), zap.Binary("message", message)) - return resp, nil, err + return resp, nil, fmt.Errorf("failed to unmarshal message: %w", err) }🧰 Tools
🪛 golangci-lint (1.64.8)
53-53: commentFormatting: put a space between
//and comment text(gocritic)
providers/websockets/bitget/messages.go (4)
32-42: Improve JSON example comment formatting.The JSON example comment would be more readable as a block comment.
- //{ - // "op":"subscribe", - // "args":[ - // { - // "instType":"SPOT", - // "channel":"ticker", - // "instId":"BTCUSDT" - // } - // ] - //} + /* + { + "op":"subscribe", + "args":[ + { + "instType":"SPOT", + "channel":"ticker", + "instId":"BTCUSDT" + } + ] + } + */Apply similar changes to the other JSON example comments in the file.
49-52: Follow Go naming conventions for acronyms.According to Go naming conventions, acronyms in field names should be capitalized consistently.
type ArgsData struct { InstType string `json:"instType"` Channel string `json:"channel"` - InstId string `json:"instId"` + InstID string `json:"instId"` }🧰 Tools
🪛 golangci-lint (1.64.8)
[warning] 51-51: var-naming: struct field InstId should be InstID
(revive)
145-159: Follow Go naming conventions for acronyms in TickerUpdateData.Similar to the previous comment, the
InstIdfield should be renamed toInstIDto follow Go naming conventions for acronyms. Additional fields likeOpenUtccould also be updated toOpenUTC.type TickerUpdateData struct { - InstId string `json:"instId"` + InstID string `json:"instId"` LastPr string `json:"lastPr"` Open24H string `json:"open24h"` High24H string `json:"high24h"` Low24H string `json:"low24h"` Change24H string `json:"change24h"` BidPr string `json:"bidPr"` AskPr string `json:"askPr"` BidSz string `json:"bidSz"` AskSz string `json:"askSz"` BaseVolume string `json:"baseVolume"` QuoteVolume string `json:"quoteVolume"` - OpenUtc string `json:"openUtc"` - ChangeUtc24H string `json:"changeUtc24h"` + OpenUTC string `json:"openUtc"` + ChangeUTC24H string `json:"changeUtc24h"` Ts int64 `json:"ts,string"` // this is quoted string in JSON }🧰 Tools
🪛 golangci-lint (1.64.8)
[warning] 145-145: var-naming: struct field InstId should be InstID
(revive)
159-159: Consider using a more descriptive field name for timestamp.The field
Tscould be renamed to be more descriptive, such asTimestampMsto indicate it's a timestamp in milliseconds.- Ts int64 `json:"ts,string"` // this is quoted string in JSON + TimestampMs int64 `json:"ts,string"` // this is quoted string in JSON
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (20)
cmd/constants/providers.go(5 hunks)guide_oracle.md(1 hunks)pkg/math/math.go(1 hunks)pkg/math/oracle/aggregator.go(1 hunks)providers/apis/bitget/api_handler.go(1 hunks)providers/apis/bitget/utils.go(1 hunks)providers/apis/defi/curve/api_handler.go(1 hunks)providers/apis/defi/curve/api_handler_test.go(1 hunks)providers/apis/defi/curve/types.go(1 hunks)providers/apis/defi/curve/utils.go(1 hunks)providers/apis/geckoterminal/api_handler.go(2 hunks)providers/apis/geckoterminal/api_handler_test.go(1 hunks)providers/apis/geckoterminal/types.go(1 hunks)providers/apis/geckoterminal/utils.go(2 hunks)providers/factories/oracle/api.go(2 hunks)providers/factories/oracle/websocket.go(2 hunks)providers/websockets/bitget/messages.go(1 hunks)providers/websockets/bitget/parse.go(1 hunks)providers/websockets/bitget/utils.go(1 hunks)providers/websockets/bitget/ws_data_handler.go(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (9)
providers/factories/oracle/api.go (4)
providers/apis/bitget/utils.go (1)
Name(9-9)providers/apis/defi/curve/utils.go (1)
Name(14-14)providers/apis/bitget/api_handler.go (1)
NewAPIHandler(21-39)providers/apis/defi/curve/api_handler.go (1)
NewAPIHandler(24-43)
providers/apis/geckoterminal/api_handler.go (2)
providers/apis/geckoterminal/types.go (1)
GeckoterminalMetadata(3-5)providers/apis/geckoterminal/utils.go (1)
URL(20-20)
providers/apis/geckoterminal/utils.go (1)
oracle/config/api.go (1)
Endpoint(52-59)
providers/websockets/bitget/parse.go (6)
providers/websockets/bitget/ws_data_handler.go (1)
WebSocketHandler(16-22)providers/websockets/bitget/messages.go (3)
TickerUpdateMessage(139-142)Channel(15-15)TickerChannel(21-21)oracle/types/oracle.go (5)
PriceResponse(73-73)ResolvedPrices(76-76)UnResolvedPrices(79-79)NewPriceResponse(93-93)NewPriceResult(87-87)pkg/math/math.go (1)
Float64StringToBigFloat(89-96)providers/types/response.go (1)
UnresolvedResult(62-64)providers/types/errors.go (3)
ErrorWithCode(75-78)NewErrorWithCode(90-95)ErrorFailedToParsePrice(21-21)
providers/websockets/bitget/utils.go (2)
oracle/config/websocket.go (8)
WebSocketConfig(72-144)DefaultReconnectionTimeout(15-15)DefaultReadBufferSize(24-24)DefaultWriteBufferSize(29-29)DefaultEnableCompression(36-36)DefaultReadTimeout(40-40)DefaultMaxReadErrorCount(59-59)DefaultMaxSubscriptionsPerBatch(68-68)providers/websockets/okx/utils.go (3)
ReadTimeout(45-45)WriteInterval(32-32)MaxSubscriptionsPerBatch(42-42)
providers/apis/bitget/api_handler.go (6)
oracle/types/oracle.go (6)
PriceAPIDataHandler(43-43)PriceResponse(73-73)NewPriceResponseWithErr(96-96)NewPriceResponse(93-93)ResolvedPrices(76-76)NewPriceResult(87-87)oracle/config/api.go (1)
APIConfig(9-48)providers/apis/bitget/utils.go (3)
Name(9-9)URL(11-11)BitgetResponse(51-56)oracle/types/provider.go (1)
ProviderTicker(15-22)providers/types/errors.go (4)
NewErrorWithCode(90-95)ErrorInvalidResponse(19-19)ErrorFailedToDecode(23-23)ErrorFailedToParsePrice(21-21)pkg/math/math.go (1)
Float64StringToBigFloat(89-96)
providers/factories/oracle/websocket.go (2)
providers/websockets/bitget/utils.go (1)
Name(9-9)providers/websockets/bitget/ws_data_handler.go (1)
NewWebSocketDataHandler(24-45)
providers/websockets/bitget/ws_data_handler.go (6)
oracle/types/oracle.go (2)
PriceWebSocketDataHandler(62-62)PriceResponse(73-73)oracle/config/websocket.go (1)
WebSocketConfig(72-144)oracle/types/provider.go (3)
ProviderTickers(33-37)NewProviderTickers(66-76)ProviderTicker(15-22)providers/websockets/bitget/utils.go (1)
Name(9-9)providers/base/websocket/handlers/ws_conn_handler.go (1)
WebsocketEncodedMessage(16-16)providers/websockets/bitget/messages.go (4)
SubscriptionResponse(105-108)TickerUpdateMessage(139-142)OperationPing(23-23)OperationSubscribe(19-19)
providers/websockets/bitget/messages.go (4)
providers/websockets/bitget/ws_data_handler.go (1)
WebSocketHandler(16-22)providers/base/websocket/handlers/ws_conn_handler.go (1)
WebsocketEncodedMessage(16-16)providers/websockets/okx/utils.go (1)
MaxSubscriptionsPerBatch(42-42)pkg/math/math.go (1)
Min(13-25)
🪛 golangci-lint (1.64.8)
providers/apis/geckoterminal/types.go
[warning] 3-3: exported: type name will be used as geckoterminal.GeckoterminalMetadata by other packages, and that stutters; consider calling this Metadata
(revive)
providers/factories/oracle/api.go
6-6: File is not properly formatted
(gofumpt)
9-9: File is not properly formatted
(gofumpt)
providers/websockets/bitget/utils.go
4-4: File is not properly formatted
(gofumpt)
5-5: File is not properly formatted
(gofumpt)
providers/apis/bitget/utils.go
[warning] 51-51: exported: type name will be used as bitget.BitgetResponse by other packages, and that stutters; consider calling this Response
(revive)
[warning] 58-58: exported: type name will be used as bitget.BitgetData by other packages, and that stutters; consider calling this Data
(revive)
26-26: Comment should end in a period
(godot)
4-4: File is not properly formatted
(gofumpt)
5-5: File is not properly formatted
(gofumpt)
providers/apis/bitget/api_handler.go
5-5: File is not properly formatted
(gofumpt)
10-10: File is not properly formatted
(gofumpt)
providers/websockets/bitget/ws_data_handler.go
53-53: commentFormatting: put a space between // and comment text
(gocritic)
providers/websockets/bitget/messages.go
[warning] 51-51: var-naming: struct field InstId should be InstID
(revive)
[warning] 145-145: var-naming: struct field InstId should be InstID
(revive)
🪛 markdownlint-cli2 (0.17.2)
guide_oracle.md
1-1: Headings should be surrounded by blank lines
Expected: 1; Actual: 0; Below
(MD022, blanks-around-headings)
130-130: Fenced code blocks should be surrounded by blank lines
null
(MD031, blanks-around-fences)
132-132: Fenced code blocks should be surrounded by blank lines
null
(MD031, blanks-around-fences)
134-134: Files should end with a single newline character
null
(MD047, single-trailing-newline)
🔇 Additional comments (31)
pkg/math/oracle/aggregator.go (1)
212-217: Trivial formatting improvement: The added blank line after the error check inCalculateAdjustedPriceenhances readability without changing behavior.providers/factories/oracle/websocket.go (2)
17-17: Import organization looks good.The import for the Bitget WebSocket package has been added appropriately to support the new provider integration.
104-105: Well-structured Bitget WebSocket handler integration.The Bitget WebSocket provider has been properly integrated into the switch statement, following the same pattern as other providers. This implementation correctly initializes the WebSocket data handler using the configuration provided.
providers/factories/oracle/api.go (2)
13-14: Import organization for new providers looks good.The imports for Bitget API and Curve DeFi API have been added in appropriate positions.
Also applies to: 18-19
102-105: Proper integration of Curve and Bitget API handlers.The Curve and Bitget API providers have been successfully integrated into the provider switch statement, following the established pattern of other providers in the factory function.
guide_oracle.md (1)
25-33: Good documentation of Bitget WebSocket configuration.The documentation properly includes the Bitget WebSocket endpoint configuration, which aligns with the newly added support in the code.
providers/apis/geckoterminal/api_handler.go (2)
55-66: Good implementation of network extraction from metadata.The code now properly extracts the network information from ticker metadata to dynamically support multiple networks. This is a good improvement over a hardcoded approach and makes the provider more flexible.
68-68: URL creation with network parameter.The URL creation now properly incorporates the dynamic network parameter extracted from ticker metadata, making the provider more flexible across different blockchain networks.
providers/apis/geckoterminal/utils.go (2)
20-20: Updated URL to support multiple networksGood improvement! The URL was changed from an Ethereum-specific URL to a format that accepts a network identifier as a parameter, enabling support for multiple blockchain networks.
35-35:✅ Verification successful
Endpoint configuration updated to use the generic URL
This change correctly updates the DefaultETHAPIConfig to use the new generic URL template. Make sure that the code that constructs API requests now properly extracts network information from ticker metadata.
🏁 Script executed:
#!/bin/bash # Check if the CreateURL method in api_handler.go extracts network information from metadata rg -A 10 "func.*CreateURL" --glob "providers/apis/geckoterminal/*.go"Length of output: 1676
🏁 Script executed:
#!/bin/bash # Retrieve the full CreateURL function for review rg -n "func (h \*APIHandler) CreateURL" -A 200 providers/apis/geckoterminal/api_handler.goLength of output: 92
🏁 Script executed:
#!/bin/bash # Retrieve the full CreateURL implementation rg -n "CreateURL(" -A200 providers/apis/geckoterminal/api_handler.go # Locate the GeckoterminalMetadata struct to inspect its fields rg -n "type GeckoterminalMetadata" -A20 providers/apis/geckoterminalLength of output: 403
🏁 Script executed:
#!/bin/bash # Retry locating the full CreateURL implementation with proper escaping rg -n "func (h \*APIHandler) CreateURL" -A200 providers/apis/geckoterminal/api_handler.go || true rg "CreateURL\\(" -A200 providers/apis/geckoterminal/api_handler.go || true # Fallback to plain grep if ripgrep patterns fail grep -R -n "CreateURL(" providers/apis/geckoterminal/api_handler.go || trueLength of output: 3151
Verified CreateURL correctly extracts and uses network metadata
The
CreateURLmethod inproviders/apis/geckoterminal/api_handler.gounmarshalsmetadata.Networkfrom each ticker’s JSON and applies it in thefmt.Sprintfcall for the endpoint URL. No further changes are needed.providers/websockets/bitget/utils.go (1)
8-14: Well-defined constants for Bitget WebSocketGood job defining clear constants for the Bitget WebSocket provider, including the provider name, WebSocket URL, and ping interval.
cmd/constants/providers.go (5)
8-8: New provider imports addedThe imports for the new providers (Bitget API, Curve Finance, GeckoTerminal, and Bitget WebSocket) have been correctly added.
Also applies to: 13-13, 18-18, 25-25
62-66: New Curve Finance API provider registeredCurve Finance DeFi API provider is correctly registered with appropriate configuration.
88-92: GeckoTerminal API provider registeredGeckoTerminal Exchange API provider is correctly registered with the updated default Ethereum API configuration.
108-112: Bitget API provider registeredBitget Exchange API provider is correctly registered with the default API configuration.
175-179: Bitget WebSocket provider registeredBitget Exchange WebSocket provider is correctly registered with the default WebSocket configuration.
providers/apis/defi/curve/utils.go (2)
9-18: Well-documented API specification with clear constantsThe file includes proper documentation referencing the Curve API specification and defines clear constants for the provider name and URL format.
20-29: Appropriate default API configurationThe DefaultAPIConfig is well structured with reasonable timeout and interval values. The API configuration follows the pattern established by other providers in the codebase.
providers/apis/geckoterminal/api_handler_test.go (2)
22-38: Test cases are comprehensiveThe test cases for URL creation correctly cover both the happy path and error cases. The use of metadata in JSON format effectively tests the real-world scenario.
The tests properly check both successful URL creation and error handling for invalid JSON metadata.
152-163: Well-structured response parsing testsThe response parsing tests thoroughly check both success and failure cases with clear expectations. The checks for specific error codes provide good coverage of error handling paths.
The test verifies both the resolved price value and timestamp freshness which is a good practice.
providers/apis/defi/curve/api_handler_test.go (2)
16-56: Comprehensive initialization testsThe
TestNewAPIHandlerfunction covers all important scenarios for handler initialization: success with default config and failures with wrong name or disabled API.
182-191: Well-designed helper functionThe
createTickerWithMetadatahelper function is well-designed and improves test readability by encapsulating the metadata JSON marshaling logic.providers/apis/defi/curve/api_handler.go (4)
1-15: LGTM: Appropriate imports and package structure for the Curve API handler.The imports include standard Go packages and necessary dependencies from the connect project, setting up a well-structured API handler for the Curve DeFi protocol.
16-22: Good practice: Interface compliance verification.The variable declaration ensures that
APIHandlerimplements thetypes.PriceAPIDataHandlerinterface at compile time, which is a good Go practice for interface compliance checking.
24-43: LGTM: Well-structured constructor with appropriate validation.The
NewAPIHandlerconstructor properly validates the API configuration before creating a new handler, checking for the correct name, enabled status, and basic validity. The returned handler is properly initialized with a new cache.
68-120: LGTM: Thorough response parsing with proper error handling.The
ParseResponsemethod comprehensively handles the Curve API response, including error cases for JSON decoding failures, empty data responses, and unknown tickers. It correctly maps resolved and unresolved prices.providers/websockets/bitget/ws_data_handler.go (3)
1-15: LGTM: Appropriate imports and interface compliance check.The file properly imports required packages and includes an interface compliance check to ensure the
WebSocketHandlerimplementstypes.PriceWebSocketDataHandler.
16-45: Well-structured WebSocketHandler with proper validation.The
WebSocketHandlerstruct and its constructorNewWebSocketDataHandlerare well-implemented with appropriate validation checks for the WebSocket configuration.
85-108: LGTM: Well-implemented methods for message creation and handler management.The
CreateMessages,HeartBeatMessages, andCopymethods are well-implemented, providing clear functionality for subscription requests, heartbeat signals, and handler cloning.providers/websockets/bitget/messages.go (2)
12-26: LGTM: Clear type and constant definitions.The types and constants for operations and channels are well-defined and properly named, providing clarity for the message handling logic.
54-89: LGTM: Well-implemented subscription message creation with batching.The
NewSubscriptionRequestMessagemethod correctly handles batching of tickers according to the configured limit, with proper validation and error handling.
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
🧹 Nitpick comments (1)
providers/apis/defi/curve/api_handler_test.go (1)
158-158: Consider Updating Test Data DescriptionThe test data description "whole list of ethereum ..." seems to be a remnant from the previous array-based response format. Consider updating it to better reflect the new single-object structure, even though this is an error test case.
- response: testutils.CreateResponseFromJSON(`{"data": {whole list of ethereum ...}}`), + response: testutils.CreateResponseFromJSON(`{"data": {invalid or incomplete data structure}}`),
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Lite
📒 Files selected for processing (3)
providers/apis/defi/curve/api_handler.go(2 hunks)providers/apis/defi/curve/api_handler_test.go(4 hunks)providers/apis/defi/curve/utils.go(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- providers/apis/defi/curve/utils.go
 - providers/apis/defi/curve/api_handler.go
 
🧰 Additional context used
🧬 Code Graph Analysis (1)
providers/apis/defi/curve/api_handler_test.go (1)
providers/apis/defi/curve/types.go (1)
CurveMetadata(3-8)
🔇 Additional comments (4)
providers/apis/defi/curve/api_handler_test.go (4)
77-87: URL Construction Updates Correctly VerifiedThe test case has been properly updated to reflect the new URL construction that uses token addresses instead of symbols. The expected URL now correctly includes the network and token address in the path format.
133-137: Response Structure Change Properly TestedThe test correctly updates the expected JSON response structure from an array to a single object under the "data" field, matching the refactored API handler logic.
170-170: Error Code Appropriately UpdatedThe expected error code for unresolved tickers has been updated from
ErrorNoResponsetoErrorUnknownPair, providing more accurate error classification.
126-171: Test Coverage is GoodThe test cases provide good coverage for the refactored API handler, including both success scenarios and various error cases (invalid JSON, empty data, unresolved tickers). This follows best practices and addresses the previous review comment requesting additional error test cases.
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.
one minor comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
other parts LGTM
Summary by CodeRabbit
New Features
Documentation
Bug Fixes
Refactor