Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(math): Upstream GDA based decimal type #20085

Closed
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from 17 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 129 additions & 0 deletions docs/build/building-modules/18-decimal-handling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
---
sidebar_position: 1
---
# Decimal Handling in Cosmos SDK

## Introduction

In the Cosmos SDK, there are two types of decimals: `LegacyDec` and `Dec`. `LegacyDec` is the older decimal type that is still available for use, while `Dec` is the newer, more performant decimal type. The implementation of `Dec` is adapted from Regen Network's `regen-ledger`, specifically from [this module](https://github.com/regen-network/regen-ledger/tree/main/types/math). Migrating from `LegacyDec` to `Dec` involves state-breaking changes, specifically:
samricotta marked this conversation as resolved.
Show resolved Hide resolved

* **Data Format**: The internal representation of decimals changes, affecting how data is stored and processed.
* **Precision Handling**: `Dec` supports flexible precision up to 34 decimal places, unlike `LegacyDec` which has a fixed precision of 18 decimal places.

These changes require a state migration to update existing decimal values to the new format. It is recommended to use `Dec` for new modules to leverage its enhanced performance and flexibility.

## Why the Change?

* **Enhanced Precision**: `Dec` uses the [apd](https://github.com/cockroachdb/apd) library for arbitrary precision decimals, suitable for accurate financial calculations.
* **Immutable Operations**: `Dec` operations are safer for concurrent use, as they do not mutate the original values.
* **Better Performance**: `Dec` operations are faster and more efficient than `LegacyDec`.`

## Using `Dec` in Modules that haven't used `LegacyDec`

If you are creating a new module or updating an existing module that has not used `LegacyDec`, you can directly use `Dec` without any changes.

As an example, we will use `DecCoin` which is a common type used in the Cosmos SDK.


samricotta marked this conversation as resolved.
Show resolved Hide resolved
```protobuf
message DecCoin {
option (gogoproto.equal) = true;

string denom = 1;
string amount = 2 [
(cosmos_proto.scalar) = "cosmos.Dec",
(gogoproto.customtype) = "cosmossdk.io/math.Dec",
(gogoproto.nullable) = false
];
}
```

How you can implement `Dec` in your module:

```go
import (
"cosmossdk.io/math"
Copy link
Contributor

Choose a reason for hiding this comment

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

Use spaces instead of tabs for indentation to maintain consistency in Markdown formatting.

-	"cosmossdk.io/math"
+    "cosmossdk.io/math"

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.

Suggested change
"cosmossdk.io/math"
"cosmossdk.io/math"

)

example := math.NewDecFromInt64(100)
```

## Modules migrating from `LegacyDec` to `Dec`

When migrating from `LegacyDec` to `Dec`, you need to update your module to use the new decimal type. **These types are state breaking changes and require a migration.**

## Precision Handling

The reason for the state breaking change is the difference in precision handling between the two decimal types:

* **LegacyDec**: Fixed precision of 18 decimal places.
* **Dec**: Flexible precision up to 34 decimal places using the apd library.

## Byte Representation Changes Example

The change in precision handling directly impacts the byte representation of decimal values:

**Legacy Dec Byte Representation:**
`2333435363738393030303030303030303030303030303030303030`

This example includes the value 123456789 followed by 18 zeros to maintain the fixed precision.

**New Dec Byte Representation:**
`0a03617364121031323334353637383900000000000000`

This example shows the value 123456789 without additional padding, reflecting the flexible precision handling of the new Dec type.

## Impact of Precision Change

The increase in precision from 18 to 34 decimal places allows for more detailed decimal values but requires data migration. This change in how data is formatted and stored is a key aspect of why the transition is considered state-breaking.

## Example of State-Breaking Change

The protobuf definitions for DecCoin illustrate the change in the custom type for the amount field.

**Before:**

```protobuf
message DecCoin {
option (gogoproto.equal) = true;

string denom = 1;
string amount = 2 [
(cosmos_proto.scalar) = "cosmos.Dec",
(gogoproto.customtype) = "cosmossdk.io/math.LegacyDec",
(gogoproto.nullable) = false
];
}
```

**After:**

```protobuf
message DecCoin {
option (gogoproto.equal) = true;

string denom = 1;
string amount = 2 [
(cosmos_proto.scalar) = "cosmos.Dec",
(gogoproto.customtype) = "cosmossdk.io/math.Dec",
(gogoproto.nullable) = false
];
}
```

## Converting `LegacyDec` to `Dec` without storing the data

If you would like to convert a `LegacyDec` to a `Dec` without a state migration changing how the data is handled internally within the application logic and not how it's stored or represented. You can use the following methods.

```go
func LegacyDecToDec(ld LegacyDec) (Dec, error) {
return NewDecFromString(ld.String())
}
```

```go
func DecToLegacyDec(ld Dec) (LegacyDec, error) {
return LegacyDecFromString(ld.String())
}
```

2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ require (
github.com/cenkalti/backoff/v4 v4.1.3 // indirect
github.com/cespare/xxhash v1.1.0 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/cockroachdb/apd/v2 v2.0.2 // indirect
Copy link

Choose a reason for hiding this comment

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

Curious why we landed on apd v2 instead of v3? Didn't see a discussion in either of #7773 (comment) or #11783 , just a brief mention. In some testing we did it showed 20-30% better performance improvements in overall runtime.

Copy link
Member

@aaronc aaronc May 13, 2024

Choose a reason for hiding this comment

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

This just looks like an oversight. The reference code was written a while ago (before v3) and this code should be updated to use the latest version

Copy link

Choose a reason for hiding this comment

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

Cool, thanks for the insight.

github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect
github.com/cockroachdb/pebble v1.1.0 // indirect
github.com/cockroachdb/redact v1.1.5 // indirect
Expand Down Expand Up @@ -183,6 +184,7 @@ replace (
cosmossdk.io/api => ./api
cosmossdk.io/core => ./core
cosmossdk.io/depinject => ./depinject
cosmossdk.io/math => ./math
cosmossdk.io/x/accounts => ./x/accounts
cosmossdk.io/x/auth => ./x/auth
cosmossdk.io/x/bank => ./x/bank
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWH
github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/cockroachdb/apd/v2 v2.0.2 h1:weh8u7Cneje73dDh+2tEVLUvyBc89iwepWCD8b8034E=
github.com/cockroachdb/apd/v2 v2.0.2/go.mod h1:DDxRlzC2lo3/vSlmSoS7JkqbbrARPuFOGr0B9pvN3Gw=
github.com/cockroachdb/datadriven v0.0.0-20190809214429-80d97fb3cbaa/go.mod h1:zn76sxSg3SzpJ0PPJaLDCu+Bu0Lg3sKTORVIj19EIF8=
github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f h1:otljaYPt5hWxV3MUfO5dFPFiOXg9CyG5/kCfayTqsJ4=
github.com/cockroachdb/datadriven v1.0.3-0.20230413201302-be42291fc80f/go.mod h1:a9RdTaap04u637JoCzcUoIcDmvwSUtcUFtT/C3kJlTU=
Expand Down
Loading
Loading