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 v2 #20536

Closed
wants to merge 25 commits into from
Closed
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
0c9b305
update dec w benchmark testing
samricotta Apr 18, 2024
1ac3316
fix version
samricotta Apr 18, 2024
dff520a
Update go.mod
samricotta Apr 18, 2024
d54f795
Create 18-decimal-handling.md
samricotta Apr 24, 2024
bd795e6
Update 18-decimal-handling.md
samricotta Apr 30, 2024
a40ab8e
update tests and convert func
samricotta May 2, 2024
1f4ed85
Update 18-decimal-handling.md
samricotta May 2, 2024
f2c294c
Refactor constructors
alpe May 6, 2024
b2b61dd
Add more numbers to quo benchmark
alpe May 14, 2024
aef9429
Apd v3 + sum benchmark
alpe May 14, 2024
aa90438
More benchs
alpe May 14, 2024
d8d1c39
Marshal/unmarshal
alpe May 14, 2024
8af8467
Fix test
alpe May 31, 2024
bb260f8
x
alpe Jun 4, 2024
e89e6ec
wip
samricotta Jun 5, 2024
a8cec85
wip
samricotta Jun 5, 2024
a03f52a
quo, quo exact, table tests, multiply tests
samricotta Jun 6, 2024
ed8ad41
feat(math): Testing Sub for GDA Dec Type (#20626)
samricotta Jun 17, 2024
5da8fc4
feat(math): Upstream GDA based decimal type - Add function coverage (…
samricotta Jun 24, 2024
cc09fe8
feat(math): Upstream GDA based decimal type testing (#20763)
samricotta Jul 3, 2024
b45aec2
feat(math): Upstream GDA based decimal type - errors (#20827)
samricotta Jul 3, 2024
777b298
Fix tests and minor refactoring (#20861)
alpe Jul 3, 2024
78937cc
feat(math): Upstream GDA based decimal type (docs) (#20950)
samricotta Jul 18, 2024
e3bd629
Merge branch 'main' into sam/dec-type
samricotta Jul 22, 2024
e96b382
Update 18-decimal-handling.md
samricotta Jul 24, 2024
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:

* **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.
Copy link
Contributor

Choose a reason for hiding this comment

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

Add a comma after the introductory phrase.

Consider adding a comma after the introductory phrase for better readability.

- As an example we will use `DecCoin` which is a common type used in the Cosmos SDK.
+ As an example, we will use `DecCoin`, which is a common type used in the Cosmos SDK.
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.

Suggested change
## 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.
## 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.
Tools
LanguageTool

[typographical] ~25-~25: Consider adding a comma after this introductory phrase.
Context: ...y use Dec without any changes. As an example we will use DecCoin which is a common...

(AS_A_NN_COMMA)



```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"
)

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`
samricotta marked this conversation as resolved.
Show resolved Hide resolved

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())
}
```

5 changes: 2 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cockroachdb/apd/v3 v3.2.1 // indirect
github.com/cockroachdb/errors v1.11.1 // indirect
github.com/cockroachdb/logtags v0.0.0-20230118201751-21c54148d20b // indirect
github.com/cockroachdb/pebble v1.1.0 // indirect
Expand Down Expand Up @@ -189,14 +190,12 @@ replace (
cosmossdk.io/core => ./core
cosmossdk.io/core/testing => ./core/testing
cosmossdk.io/depinject => ./depinject
cosmossdk.io/log => ./log
cosmossdk.io/store => ./store
cosmossdk.io/math => ./math
cosmossdk.io/x/accounts => ./x/accounts
cosmossdk.io/x/auth => ./x/auth
cosmossdk.io/x/bank => ./x/bank
cosmossdk.io/x/consensus => ./x/consensus
cosmossdk.io/x/staking => ./x/staking
cosmossdk.io/x/tx => ./x/tx
)

// Below are the long-lived replace of the Cosmos SDK
Expand Down
11 changes: 9 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2 h1:90/4O5QkHb8EZdA2SAhueRzYw6u5ZHCPKtReFqshnTY=
buf.build/gen/go/cometbft/cometbft/protocolbuffers/go v1.34.2-20240701160653-fedbb9acfd2f.2/go.mod h1:1+3gJj2NvZ1mTLAtHu+lMhOjGgQPiCKCeo+9MBww0Eo=
buf.build/gen/go/cosmos/gogo-proto/protocolbuffers/go v1.34.2-20240130113600-88ef6483f90f.2 h1:b7EEYTUHmWSBEyISHlHvXbJPqtKiHRuUignL1tsHnNQ=
Expand All @@ -6,10 +7,14 @@ cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMT
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cosmossdk.io/errors v1.0.1 h1:bzu+Kcr0kS/1DuPBtUFdWjzLqyUuCiyHjyJB6srBV/0=
cosmossdk.io/errors v1.0.1/go.mod h1:MeelVSZThMi4bEakzhhhE/CKqVv3nOJDA25bIqRDu/U=
cosmossdk.io/math v1.3.0 h1:RC+jryuKeytIiictDslBP9i1fhkVm6ZDmZEoNP316zE=
cosmossdk.io/math v1.3.0/go.mod h1:vnRTxewy+M7BtXBNFybkuhSH4WfedVAAnERHgVFhp3k=
cosmossdk.io/log v1.3.1 h1:UZx8nWIkfbbNEWusZqzAx3ZGvu54TZacWib3EzUYmGI=
cosmossdk.io/log v1.3.1/go.mod h1:2/dIomt8mKdk6vl3OWJcPk2be3pGOS8OQaLUM/3/tCM=
cosmossdk.io/schema v0.1.1 h1:I0M6pgI7R10nq+/HCQfbO6BsGBZA8sQy+duR1Y3aKcA=
cosmossdk.io/schema v0.1.1/go.mod h1:RDAhxIeNB4bYqAlF4NBJwRrgtnciMcyyg0DOKnhNZQQ=
cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc h1:R9O9d75e0qZYUsVV0zzi+D7cNLnX2JrUOQNoIPaF0Bg=
cosmossdk.io/store v1.1.1-0.20240418092142-896cdf1971bc/go.mod h1:amTTatOUV3u1PsKmNb87z6/galCxrRbz9kRdJkL0DyU=
cosmossdk.io/x/tx v0.13.3 h1:Ha4mNaHmxBc6RMun9aKuqul8yHiL78EKJQ8g23Zf73g=
cosmossdk.io/x/tx v0.13.3/go.mod h1:I8xaHv0rhUdIvIdptKIqzYy27+n2+zBVaxO6fscFhys=
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/99designs/go-keychain v0.0.0-20191008050251-8e49817e8af4 h1:/vQbFIOMbk2FiG/kXiLl8BRyzTWDw7gX/Hz7Dd5eDMs=
Expand Down Expand Up @@ -68,6 +73,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/v3 v3.2.1 h1:U+8j7t0axsIgvQUqthuNm82HIrYXodOV2iWLWtEaIwg=
github.com/cockroachdb/apd/v3 v3.2.1/go.mod h1:klXJcjp+FffLTHlhIG69tezTDvdP065naDsHzKhYSqc=
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=
github.com/cockroachdb/errors v1.11.1 h1:xSEW75zKaKCWzR3OfxXUxgrk/NtT4G1MiOv5lWZazG8=
Expand Down
Loading
Loading