Skip to content

Commit

Permalink
refactor(util.go): improve precision in conversion ratio calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
lmquang committed Feb 24, 2025
1 parent 0931158 commit cff6e7d
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions internal/oracle/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,39 @@ package oracle

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

"github.com/dwarvesf/icy-backend/internal/model"
)

// getConversionRatio calculates the ratio of circulated ICY tokens to BTC supply
// The ratio is scaled by 10^6 to preserve 6 decimal places of precision
func getConversionRatio(circulatedIcy, btcSupply *model.Web3BigInt) (*model.Web3BigInt, error) {
if circulatedIcy == nil || btcSupply == nil {
return nil, fmt.Errorf("circulatedIcy or btcSupply is nil")
}

icyFloat := circulatedIcy.ToFloat()
btcFloat := btcSupply.ToFloat()
// Convert inputs to big.Float for high-precision calculation
icyFloat := new(big.Float).SetFloat64(circulatedIcy.ToFloat())
btcFloat := new(big.Float).SetFloat64(btcSupply.ToFloat())

if btcFloat == 0 {
// Handle zero BTC supply case
if btcFloat.Cmp(new(big.Float).SetFloat64(0)) == 0 {
return &model.Web3BigInt{
Value: "0",
Decimal: 6,
}, nil
}

ratio := icyFloat / btcFloat

ratioFloat := new(big.Float).SetFloat64(ratio)

multiplier := new(big.Float).SetFloat64(math.Pow(10, 6))
ratioFloat.Mul(ratioFloat, multiplier)
// Calculate ratio and scale by 10^6
ratio := new(big.Float).Quo(icyFloat, btcFloat)
multiplier := new(big.Float).SetFloat64(1e6)
scaledRatio := new(big.Float).Mul(ratio, multiplier)

// Convert to integer representation
ratioInt := new(big.Int)
ratioFloat.Int(ratioInt)
scaledRatio.Int(ratioInt)

return &model.Web3BigInt{
Value: ratioInt.String(),
Decimal: 6,
Expand Down

0 comments on commit cff6e7d

Please sign in to comment.