Skip to content

Commit

Permalink
Fix bug FloatToWei for Inf and NaN value (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
hiepnv90 authored Nov 25, 2023
1 parent e366bcf commit dd8cf2a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
10 changes: 9 additions & 1 deletion pkg/convert/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,18 @@ package convert

import (
"errors"
"fmt"
"math"
"math/big"

"github.com/ethereum/go-ethereum/common"
"github.com/shopspring/decimal"
)

var ErrMaxExponent = errors.New("reach max exponent")
var (
ErrMaxExponent = errors.New("reach max exponent")
ErrInvalidNumber = errors.New("number is not valid")
)

const (
maxBPS = 10000
Expand Down Expand Up @@ -47,6 +51,10 @@ func WeiToFloat(amount *big.Int, decimals int64) float64 {

// FloatToWei ...
func FloatToWei(amount float64, decimals int64) (*big.Int, error) {
if math.IsNaN(amount) || math.IsInf(amount, 0) {
return nil, fmt.Errorf("%w: %f", ErrInvalidNumber, amount)
}

if decimals > math.MaxInt32 {
return nil, ErrMaxExponent
}
Expand Down
10 changes: 10 additions & 0 deletions pkg/convert/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,16 @@ func TestFloatToWei(t *testing.T) {
decimals: 0xfffffffff,
expectErr: convert.ErrMaxExponent,
},
{
amount: math.Inf(0),
decimals: 18,
expectErr: convert.ErrInvalidNumber,
},
{
amount: math.NaN(),
decimals: 18,
expectErr: convert.ErrInvalidNumber,
},
}

for _, test := range tests {
Expand Down

0 comments on commit dd8cf2a

Please sign in to comment.