Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

(fix) Fix read only examples #246

Closed
wants to merge 7 commits into from
Closed

Conversation

PavelInjective
Copy link
Contributor

@PavelInjective PavelInjective commented Sep 26, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced block data retrieval by dynamically fetching the latest block height.
    • Improved market ID assignment by fetching data from the exchange client instead of using a hardcoded value.
    • Introduced a limit on the number of transactions requested in the explorer.
  • Bug Fixes

    • Updated network configurations to ensure proper connections to the relevant environments (testnet).
  • Chores

    • Cleaned up transaction ID queries to reflect new IDs for better testing and accuracy.

Copy link

coderabbitai bot commented Sep 26, 2024

Warning

Rate limit exceeded

@PavelInjective has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 26 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Files that changed from the base of the PR and between fd43148 and fa9e283.

Walkthrough

The changes involve modifications to various Go example files, primarily focusing on how data is retrieved and processed. Key alterations include dynamic fetching of block heights and market IDs instead of using hardcoded values, as well as updates to network configurations and transaction IDs. Additionally, there are changes to the request parameters for fetching transactions, emphasizing limiting the number of results instead of specifying historical points.

Changes

Files Grouped by Similar Changes Change Summary
examples/chain/7_GetBlock/example.go Modified block data retrieval to use the latest block height dynamically instead of a hardcoded value. Added error handling for fetching the latest block height.
examples/chain/8_OfflineSigning/example.go Introduced dynamic assignment of marketId by fetching available spot markets instead of using a hardcoded string.
examples/chain/auth/query/1_Account/example.go Changed network configuration loading from "sentry0" to "lb", affecting the application’s network connection.
examples/chain/tx/query/1_GetTx/example.go Updated network configuration from "mainnet" to "testnet" and changed the transaction ID being queried.
examples/explorer/1_GetTxByHash/example.go Altered network configuration from "mainnet" with "sentry" to "testnet" with "lb" and updated the transaction hash being queried.
examples/explorer/5_TxsRequest/example.go Removed the Before field from GetTxsRequest structure and added a Limit field set to 10 for transaction requests.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Example
    participant ExchangeClient
    participant ChainClient

    User->>Example: Start example
    Example->>ChainClient: GetLatestBlockHeight()
    ChainClient-->>Example: Return latest block height
    Example->>ChainClient: GetBlock(blockHeight)
    ChainClient-->>Example: Return block data
    Example->>User: Display transactions
Loading

🐇 "In the code where rabbits hop,
New heights we fetch, we never stop.
From hardcoded paths, we now take flight,
With dynamic calls, our future is bright!
With limits set, we dance and play,
Fetching data in a clever way!" 🐇


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

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

@PavelInjective PavelInjective removed the request for review from aarmoa September 26, 2024 17:28
@PavelInjective PavelInjective marked this pull request as draft September 26, 2024 17:28
@aarmoa
Copy link
Collaborator

aarmoa commented Sep 26, 2024

Why are we changing the examples? Were they broken?

@PavelInjective PavelInjective marked this pull request as ready for review September 26, 2024 17:32
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (3)
examples/explorer/5_TxsRequest/example.go (1)

Line range hint 1-38: Suggestions for improving the example

While the example demonstrates the basic usage of the explorer client, consider the following improvements to make it more robust and flexible:

  1. Error handling: Handle the error from json.MarshalIndent. For example:
str, err := json.MarshalIndent(res, "", " ")
if err != nil {
    fmt.Printf("Error marshaling JSON: %v\n", err)
    return
}
  1. Context: Instead of using context.Background(), consider adding a timeout to prevent the request from hanging indefinitely:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
  1. Configurability: Make the network and limit configurable. For example:
network := common.LoadNetwork(os.Getenv("NETWORK_TYPE"), os.Getenv("NETWORK_ENDPOINT"))
limit, _ := strconv.Atoi(os.Getenv("TX_LIMIT"))
if limit == 0 {
    limit = 10 // Default value
}

req := explorerPB.GetTxsRequest{
    Limit: uint64(limit),
}

These changes would make the example more flexible and closer to production-ready code.

examples/chain/auth/query/1_Account/example.go (1)

Line range hint 1-71: Consider enhancing the example for better usability and error handling.

While the example effectively demonstrates how to query an account using the Injective SDK, there are a few suggestions to improve it:

  1. Replace hardcoded values with environment variables or command-line flags for better flexibility.
  2. Improve error handling, especially for the account query result.
  3. Add comments to explain key steps in the process.

Here's a suggested refactor for the main function:

func main() {
	network := common.LoadNetwork("mainnet", "lb")
	tmClient, err := rpchttp.New(network.TmEndpoint, "/websocket")
	if err != nil {
		log.Fatalf("Failed to create tendermint client: %v", err)
	}

	// Use environment variables for sensitive information
	home := os.Getenv("HOME")
	chainId := os.Getenv("CHAIN_ID")
	privateKey := os.Getenv("PRIVATE_KEY")
	address := os.Getenv("QUERY_ADDRESS")

	senderAddress, cosmosKeyring, err := chainclient.InitCosmosKeyring(
		home+"/.injectived",
		"injectived",
		"file",
		"inj-user",
		"12345678",
		privateKey,
		false,
	)
	if err != nil {
		log.Fatalf("Failed to initialize Cosmos keyring: %v", err)
	}

	clientCtx, err := chainclient.NewClientContext(
		chainId,
		senderAddress.String(),
		cosmosKeyring,
	)
	if err != nil {
		log.Fatalf("Failed to create client context: %v", err)
	}

	clientCtx = clientCtx.WithNodeURI(network.TmEndpoint).WithClient(tmClient)

	queryClient := authtypes.NewQueryClient(clientCtx)

	ctx, cancelFn := context.WithCancel(context.Background())
	defer cancelFn()

	res, err := queryClient.Account(ctx, &authtypes.QueryAccountRequest{
		Address: address,
	})
	if err != nil {
		log.Fatalf("Failed to query account: %v", err)
	}

	var account types.EthAccount
	err = clientCtx.Codec.UnmarshalInterface(res.GetAccount(), &account)
	if err != nil {
		log.Fatalf("Failed to unmarshal account: %v", err)
	}

	fmt.Printf("Account details for %s:\n%s\n", address, account.String())
}

This refactored version:

  • Uses environment variables for sensitive information.
  • Improves error handling with more descriptive messages.
  • Uses log.Fatalf for critical errors to provide stack traces.
  • Adds comments to explain the purpose of key steps.
  • Uses UnmarshalInterface instead of MustUnmarshal for safer deserialization.

Remember to set the necessary environment variables before running the example:

export CHAIN_ID="your-chain-id"
export PRIVATE_KEY="your-private-key"
export QUERY_ADDRESS="address-to-query"
examples/chain/8_OfflineSigning/example.go (1)

90-98: Approve with suggestions: Dynamic market ID retrieval implemented.

The change to dynamically fetch the market ID is a good improvement over hardcoding. However, consider the following suggestions:

  1. Add a comment explaining why you're using the first market ID.
  2. Consider adding a fallback or error handling if no markets are returned.
  3. For a more robust example, you might want to filter for a specific market or allow the user to choose one.

Here's a suggested improvement:

marketResponse, err := exchangeClient.GetSpotMarkets(ctx, &spotExchangePB.MarketsRequest{})
if err != nil {
    panic(err)
}
if len(marketResponse.Markets) == 0 {
    panic("No markets available")
}

// For this example, we're using the first available market
marketId := marketResponse.Markets[0].MarketId
fmt.Printf("Using market ID: %s\n", marketId)

This change adds better error handling and a comment explaining the choice of market ID.

🛑 Comments failed to post (5)
examples/exchange/derivatives/1_Market/example.go (2)

19-19: 🛠️ Refactor suggestion

Consider using a dynamic approach for obtaining the market ID.

While the market ID has been updated, using a hardcoded value in example code can lead to maintenance issues if the specific market becomes invalid or changes. Consider implementing a more dynamic approach to obtain a valid market ID, such as:

  1. Fetching a list of available markets and using the first one.
  2. Allowing the user to input a market ID as a command-line argument.
  3. Using environment variables to configure the market ID.

This would make the example more robust and easier to maintain.

Here's a sample implementation using a command-line argument:

import (
	// ... existing imports ...
	"os"
)

func main() {
	// ... existing code ...

	var marketID string
	if len(os.Args) > 1 {
		marketID = os.Args[1]
	} else {
		marketID = "0x95698a9d8ba11660f44d7001d8c6fb191552ece5d9141a05c5d9128711cdc2e0" // fallback to default
	}

	res, err := exchangeClient.GetDerivativeMarket(ctx, marketID)
	// ... rest of the code ...
}

21-21: 🛠️ Refactor suggestion

Improve error handling for better user feedback.

The current error handling prints the error but allows the program to continue executing, which may lead to unexpected behavior or confusing output. Consider enhancing the error handling to provide more context and exit the program when an error occurs.

Here's a suggested improvement:

if err != nil {
	fmt.Fprintf(os.Stderr, "Error fetching derivative market: %v\n", err)
	os.Exit(1)
}

This change will:

  1. Print the error message to stderr with context.
  2. Exit the program with a non-zero status code, indicating an error occurred.
examples/chain/7_GetBlock/example.go (2)

21-21: 🛠️ Refactor suggestion

Simplify block height calculation

The current implementation calculates 99% of the latest block height using floating-point arithmetic, which might lead to unnecessary precision loss.

Consider simplifying the calculation to use integer arithmetic:

-res, err := tmClient.GetBlock(clientCtx, int64(float64(latestBlockHeight)*0.99))
+res, err := tmClient.GetBlock(clientCtx, latestBlockHeight - latestBlockHeight/100)

This change maintains the intent of fetching a block slightly before the latest one while avoiding potential floating-point precision issues.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	res, err := tmClient.GetBlock(clientCtx, latestBlockHeight - latestBlockHeight/100)

18-20: ⚠️ Potential issue

Consider improving error handling

While the added error handling is a good start, the code continues to execute even if an error occurs when fetching the latest block height. This could lead to unexpected behavior or errors in the subsequent code.

Consider modifying the error handling to return from the function if an error occurs:

 if err != nil {
-    fmt.Println(err)
+    fmt.Println("Error fetching latest block height:", err)
+    return
 }

This change ensures that the example doesn't attempt to use an invalid block height if the initial fetch fails.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

	if err != nil {
		fmt.Println("Error fetching latest block height:", err)
		return
	}
examples/explorer/5_TxsRequest/example.go (1)

24-24: 🛠️ Refactor suggestion

Shift from historical filtering to result limiting

The change from using Before: 7158400 to Limit: 10 in the GetTxsRequest structure represents a significant shift in how transactions are requested:

  1. Removal of Before: This eliminates the ability to specify a historical point (block height or timestamp) for transaction retrieval. This might impact users who relied on this for accessing specific historical data.

  2. Addition of Limit: This introduces a way to control the number of transactions returned, which is a common practice for pagination and managing response sizes.

While this change simplifies the API usage and is suitable for many use cases, it's worth considering the following:

  • Does this change align with the intended use cases for this example?
  • Are there scenarios where users might still need to specify a historical point?
  • Is the limit of 10 transactions sufficient for demonstrating the API's capabilities?

Consider adding a comment explaining the purpose of the Limit field and its implications. For example:

req := explorerPB.GetTxsRequest{
    // Limit the number of transactions returned to 10.
    // Adjust this value based on your specific requirements.
    Limit: 10,
}

This will help users understand how to modify the example for their specific needs.

@PavelInjective
Copy link
Contributor Author

Yes, they are not functional (e.g. some market does not exist, some height is too old or some settings have changed). I would expect all the read-only examples to work.

@aarmoa
Copy link
Collaborator

aarmoa commented Sep 26, 2024

No, that is not the case. The examples are there to show how to use the SDK, but the users are expected to configure the parameters correctly. We prefer to have examples with simple code and out of date parameters rather than complex examples because we are requesting values from the chain to use as the parameters for the example, shifting the focus of the script and maybe confusing the user

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants