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

chore: improving floating point math accuracy while dealing with atomic amounts #54

Merged
merged 1 commit into from
Feb 28, 2025
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Coinbase Go SDK Changelog

## [0.0.21] - 2025-02-28

### Changed

- Improved precision of `FromAtomicAmount` and `ToAtomicAmount` calculations. Fixed an issue where the amount "32006467556000000000" wei was interpreted as "32.006467555999999999" due to lossy floating point math. Updated precision to 128 bits to resolve this.

## [0.0.20] - 2025-02-27

### Added
Expand Down
2 changes: 1 addition & 1 deletion pkg/auth/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func (t *transport) RoundTrip(req *http.Request) (*http.Response, error) {
"Correlation-Context",
fmt.Sprintf(
"%s,%s",
fmt.Sprintf("%s=%s", "sdk_version", "0.0.20"),
fmt.Sprintf("%s=%s", "sdk_version", "0.0.21"),
fmt.Sprintf("%s=%s", "sdk_language", "go"),
),
)
Expand Down
8 changes: 4 additions & 4 deletions pkg/coinbase/asset.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,22 @@ func (a Asset) FromAtomicAmount(wholeAmount *big.Int) *big.Float {
divisor := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(exponent)), nil)

// Convert the divisor to *big.Float for division.
divisorFloat := new(big.Float).SetInt(divisor)
divisorFloat := new(big.Float).SetInt(divisor).SetPrec(128)

// Convert the wholeAmount to *big.Float.
amountFloat := new(big.Float).SetInt(wholeAmount)
amountFloat := new(big.Float).SetInt(wholeAmount).SetPrec(128)

return new(big.Float).Quo(amountFloat, divisorFloat)
}

func (a Asset) toAtomicAmount(wholeAmount *big.Float) *big.Int {
func (a Asset) ToAtomicAmount(wholeAmount *big.Float) *big.Int {
exponent := a.decimals

// Calculate the 10^exponent as *big.Int.
multiplier := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(exponent)), nil)

// Convert the multiplier to *big.Float for multiplication.
multiplierFloat := new(big.Float).SetInt(multiplier)
multiplierFloat := new(big.Float).SetInt(multiplier).SetPrec(128)

// Perform the multiplication.
resultFloat := new(big.Float).Mul(wholeAmount, multiplierFloat)
Expand Down
142 changes: 142 additions & 0 deletions pkg/coinbase/asset_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
package coinbase

import (
"math/big"
"testing"

"github.com/stretchr/testify/assert"
)

func TestFromAtomicAmount(t *testing.T) {
asset := Asset{
networkId: "testnet",
assetId: "test-asset",
contractAddress: "0x123",
decimals: 18,
}

tests := []struct {
name string
amountString string
expectedAmountStringUpto18Decimals string
}{
{
name: "Test with 0 eth",
amountString: "0",
expectedAmountStringUpto18Decimals: "0.000000000000000000",
},
{
name: "Test with negative value",
amountString: "-1000000000000000000",
expectedAmountStringUpto18Decimals: "-1.000000000000000000",
},
{
name: "Test with 1 eth",
amountString: "1000000000000000000",
expectedAmountStringUpto18Decimals: "1.000000000000000000",
},
{
name: "Test with very small fractional value",
amountString: "1",
expectedAmountStringUpto18Decimals: "0.000000000000000001",
},
{
name: "Test with maximum uint128 value",
amountString: "340282366920938463463374607431768211456",
expectedAmountStringUpto18Decimals: "340282366920938463463.374607431768211456",
},
{
name: "Test with large fractional value",
amountString: "123456789012345678901234567890",
expectedAmountStringUpto18Decimals: "123456789012.345678901234567890",
},
{
name: "Test with random fractional eth",
amountString: "32006467556000000000",
expectedAmountStringUpto18Decimals: "32.006467556000000000",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := asset.FromAtomicAmount(getTestBigInt(t, tt.amountString))
assert.Equal(t, tt.expectedAmountStringUpto18Decimals, result.Text('f', 18))
})
}
}

func TestToAtomicAmount(t *testing.T) {
asset := Asset{
networkId: "testnet",
assetId: "test-asset",
contractAddress: "0x123",
decimals: 18,
}

tests := []struct {
name string
amountString string
expectedAmountStringUpto18Decimals string
}{
{
name: "Test with 0 eth",
amountString: "0.000000000000000000",
expectedAmountStringUpto18Decimals: "0",
},
{
name: "Test with negative value",
amountString: "-1.000000000000000000",
expectedAmountStringUpto18Decimals: "-1000000000000000000",
},
{
name: "Test with 1 eth",
amountString: "1.000000000000000000",
expectedAmountStringUpto18Decimals: "1000000000000000000",
},
{
name: "Test with very small fractional value",
amountString: "0.000000000000000001",
expectedAmountStringUpto18Decimals: "1",
},
{
name: "Test with maximum uint128 value",
amountString: "340282366920938463463.374607431768211456",
expectedAmountStringUpto18Decimals: "340282366920938463463374607431768211456",
},
{
name: "Test with large fractional value",
amountString: "123456789012.345678901234567890",
expectedAmountStringUpto18Decimals: "123456789012345678901234567890",
},
{
name: "Test with random fractional eth",
amountString: "32.006467556000000000",
expectedAmountStringUpto18Decimals: "32006467556000000000",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := asset.ToAtomicAmount(getTestBigFloat(t, tt.amountString))
assert.Equal(t, tt.expectedAmountStringUpto18Decimals, result.String())
})
}
}

func getTestBigInt(t *testing.T, input string) *big.Int {
t.Helper()

result, ok := new(big.Int).SetString(input, 10)
assert.True(t, ok)

return result
}

func getTestBigFloat(t *testing.T, input string) *big.Float {
t.Helper()

result, _, err := big.ParseFloat(input, 10, 128, big.ToNearestEven)
assert.NoError(t, err)

return result
}
2 changes: 1 addition & 1 deletion pkg/coinbase/staking_operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func (c *Client) BuildStakingOperation(
Action: action,
Options: map[string]string{
"mode": StakingOperationModeDefault,
"amount": asset.toAtomicAmount(amount).String(),
"amount": asset.ToAtomicAmount(amount).String(),
},
}
for _, f := range o {
Expand Down
Loading