Skip to content

Conversation

@aarmoa
Copy link
Collaborator

@aarmoa aarmoa commented Mar 3, 2025

  • Added quantization in the functions that convert notional values to chain format

Summary by CodeRabbit

  • Refactor
    • Updated the conversion of market notional values so that chain representations now consistently round values upward across all market types. This change ensures a uniform and predictable presentation of converted values, improving overall consistency when viewing market data.

@coderabbitai
Copy link

coderabbitai bot commented Mar 3, 2025

Walkthrough

The changes update the NotionalToChainFormat method implementations for the Spot, Derivative, and Binary Option markets. Instead of directly converting the existing chain formatted value to a string, these methods now compute a quantized value by applying the Ceil() function. This ensures that the notional value is always rounded up before its conversion and further processing. The modifications standardize the approach across the market types.

Changes

Files Change Summary
client/core/market.go Updated NotionalToChainFormat for SpotMarket, DerivativeMarket, and BinaryOptionMarket to replace direct string conversion of chainFormattedValue with conversion of a quantized value obtained by applying the Ceil() function.

Sequence Diagram(s)

sequenceDiagram
    participant M as Market
    participant F as NotionalToChainFormat Method
    participant Q as Ceil Operation

    M->>F: Call NotionalToChainFormat(humanReadableValue)
    F->>Q: Compute quantizedValue = Ceil(chainFormattedValue)
    Q-->>F: Return quantizedValue
    F->>M: Return string(quantizedValue)
Loading

Poem

In a burrow deep, I found a code so neat,
Where numbers hopped with an upward beat.
With a Ceil so bold and quantized delight,
Our markets now shine in the chain’s bright light.
A rabbit’s cheer for precision, oh so sweet!

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

Documentation and Community

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
client/core/market.go (2)

42-49: Consider adding a comment explaining the rationale for using Ceil()

While the implementation is technically sound, it's worth noting that the quantization approach for notional values (using Ceil()) differs from the approach used in other conversion methods like PriceToChainFormat and QuantityToChainFormat, which use DivRound with tick sizes. Adding a comment explaining why ceiling rounding is specifically chosen for notional values would improve code maintainability.

func (spotMarket SpotMarket) NotionalToChainFormat(humanReadableValue decimal.Decimal) sdkmath.LegacyDec {
	decimals := spotMarket.QuoteToken.Decimals
	chainFormattedValue := humanReadableValue.Mul(decimal.New(1, decimals))
+	// Using Ceil() ensures the notional value always meets minimum requirements by rounding up
	quantizedValue := chainFormattedValue.Ceil()
	valueInChainFormat, _ := sdkmath.LegacyNewDecFromStr(quantizedValue.String())

	return valueInChainFormat
}

45-46: Consider adding tests for edge cases

The quantization using Ceil() might have unexpected effects for certain edge cases, particularly values very close to integers or very small values. Consider adding tests that verify the behavior with these edge cases.

// Example test to add (this would go in the appropriate test file, not in this file)
func TestNotionalToChainFormatEdgeCases(t *testing.T) {
	// Setup a test market
	market := SpotMarket{
		QuoteToken: Token{
			Decimals: 6,
		},
	}
	
	testCases := []struct {
		name          string
		input         string
		expectedValue string
	}{
		{
			name:          "Value just below integer",
			input:         "10.999999",
			expectedValue: "11000000", // Expecting ceiling to 11 * 10^6
		},
		{
			name:          "Exact integer value",
			input:         "10.000000",
			expectedValue: "10000000", // Should remain at 10 * 10^6
		},
		{
			name:          "Very small value",
			input:         "0.000001",
			expectedValue: "1", // Should ceiling to 1
		},
	}
	
	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			input := decimal.RequireFromString(tc.input)
			result := market.NotionalToChainFormat(input)
			
			if result.String() != tc.expectedValue {
				t.Errorf("Expected %s, got %s", tc.expectedValue, result.String())
			}
		})
	}
}

Also applies to: 133-134, 230-231

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4d282a9 and 42b469e.

📒 Files selected for processing (1)
  • client/core/market.go (3 hunks)
🔇 Additional comments (4)
client/core/market.go (4)

45-46: Consistent implementation for notional quantization

The changes use Ceil() to quantize the notional value, which ensures the value is always rounded up to the nearest integer. This is a consistent pattern across all market types and provides a standardized approach for handling notional values.


133-134: Consistent implementation for derivative market

This implementation correctly applies the same quantization pattern used in the SpotMarket implementation. The change is appropriate and maintains consistency across market types.


230-231: Consistent implementation for binary option market

This implementation correctly applies the same quantization pattern used in the other market types. The approach is consistent and appropriate.


42-49:

Details

❓ Verification inconclusive

Verify impact on existing transactions

The change from using raw values to ceiling-rounded values for notional calculations will result in slightly higher notional values in some cases. Since MarginToChainFormat delegates to NotionalToChainFormat, this will also affect margin calculations.

Also applies to: 130-137, 227-234


🏁 Script executed:

#!/bin/bash
# Description: Search for tests or client code that depends on NotionalToChainFormat to understand the impact

# Check for tests that verify NotionalToChainFormat behavior
echo "Searching for tests that might be affected by the change:"
rg -A 3 -B 3 "NotionalToChainFormat" --type go --type test

# Check for other dependencies on NotionalToChainFormat 
echo "Searching for code that uses NotionalToChainFormat:"
rg -A 2 "\.(NotionalToChainFormat|MarginToChainFormat)" --type go | grep -v "func.*NotionalToChainFormat" | grep -v "func.*MarginToChainFormat"

Length of output: 2143


Action: Verify Transactional Impact of Rounding Change

The updated implementation of NotionalToChainFormat now applies ceiling rounding to the scaled value, meaning that in some cases, notional (and hence margin) values may be slightly higher than before. Since MarginToChainFormat delegates to NotionalToChainFormat, this change affects margin calculations as well. Please ensure that:

  • Dependent Calculations: All client code and tests (e.g., in client/core/market_test.go) that rely on the previous raw multiplication behavior are updated to expect the ceiling-rounded values.
  • Consistency Checks: Verify that test cases accurately reflect this rounding behavior to prevent inadvertent discrepancies in transaction processing.
  • Additional Affected Areas: Confirm similar changes and impacts in the code segments at lines 130–137 and 227–234.

@aarmoa aarmoa merged commit a1e1834 into master Mar 3, 2025
4 of 5 checks passed
@aarmoa aarmoa deleted the fix/add_notional_quantization branch March 3, 2025 16:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants