InjectiveLabs / cw-injective

Apache License 2.0
22 stars 24 forks source link

[FPDecimal] Handling sdk.Dec <nil> case #29

Open albertchon opened 2 years ago

albertchon commented 2 years ago

The Cosmos-SDK's empty sdk.Dec (e.g. sdk.Dec{}) string form is represented as "<nil>" (proof below).

However, FPDecimals' from_str method won't be able to convert this value. https://github.com/InjectiveLabs/cw-injective/blob/09b1925bfbeae42321edef1828a61b0599d5f1f9/packages/injective-math/src/fp_decimal/from_str.rs#L10-L45

Should we handle this case? If so, how? @DrunkRandomWalker @gorgos

Proof:

type Dec struct {
    i *big.Int
}

func (d Dec) String() string {
    if d.i == nil {
        return d.i.String()
    }
    ...
}

and big.Int's String method is simply

// String returns the decimal representation of x as generated by
// x.Text(10).
func (x *Int) String() string {
    return x.Text(10)
}

// Text returns the string representation of x in the given base.
// Base must be between 2 and 62, inclusive. The result uses the
// lower-case letters 'a' to 'z' for digit values 10 to 35, and
// the upper-case letters 'A' to 'Z' for digit values 36 to 61.
// No prefix (such as "0x") is added to the string. If x is a nil
// pointer it returns "<nil>".
func (x *Int) Text(base int) string {
    if x == nil {
        return "<nil>"
    }
    return string(x.abs.itoa(x.neg, base))
}
gorgos commented 2 years ago

Never understood the reasoning for sdk.Dec{} to begin with. If empty values are allowed, we should use *sdk.Dec leading to Option<FPDecimal>.