Files
m2pool_payment/internal/utils/utils.go
2025-11-18 11:10:16 +08:00

117 lines
2.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package utils
import (
"log"
"math"
"math/big"
)
func BigIntETHToFloat64(value *big.Int) float64 {
f := new(big.Float).SetInt(value)
scale := new(big.Float).SetFloat64(1e18) // USDT 精度 6 位
f.Quo(f, scale)
result, _ := f.Float64()
return result
}
func BigIntUSDTToFloat64(value *big.Int) float64 {
f := new(big.Float).SetInt(value)
scale := new(big.Float).SetFloat64(1e6) // USDT 精度 6 位
f.Quo(f, scale)
result, _ := f.Float64()
return result
}
// USDT 一般精度是 6 位小数
const USDTDecimals = 6
// Float64ToBigIntUSDT 将 float64 金额转换成 *big.Int
func Float64ToBigIntUSDT(amount float64) *big.Int {
// 乘上精度系数
scale := math.Pow10(USDTDecimals)
bigAmount := new(big.Int)
bigAmount.SetInt64(int64(amount * scale))
return bigAmount
}
const ETHDecimals = 18
func Float64ToBigIntETH(amount float64) *big.Int {
// 乘上精度系数
scale := math.Pow10(ETHDecimals)
bigAmount := new(big.Int)
bigAmount.SetInt64(int64(amount * scale))
return bigAmount
}
func Slice_delete(arr []any, index int) []any {
if index < 0 || index >= len(arr) {
// 处理越界
log.Fatalf("slice arr error: index=%d, arr length=%d", index, len(arr))
return nil
}
if index >= 0 && index < len(arr) {
copy(arr[index:], arr[index+1:]) // 后面的元素往前移动
arr = arr[:len(arr)-1] // 去掉最后一个多余元素
}
return arr
}
// 函数:检查一个切片是否包含某个字符串
func Contains(slice []string, str string) bool {
for _, s := range slice {
if s == str {
return true
}
}
return false
}
func Float64ToBigInt(symbol string, amount float64) *big.Int {
var scale float64
switch symbol {
case "ETH":
scale = math.Pow10(ETHDecimals)
case "USDT":
scale = math.Pow10(USDTDecimals)
default:
log.Printf("don`t support symbol: %s", symbol)
return nil
}
// 检查 amount 是否为负数
if amount < 0 {
log.Printf("Warning: negative amount for symbol %s: %f", symbol, amount)
amount = 0 // 可以选择将负数设置为 0 或返回错误
}
// 将 amount 转换为 big.Float 来避免溢出
bigAmount := new(big.Float)
bigAmount.SetFloat64(amount)
// 乘以 scale小数位数避免精度丢失
bigAmount = bigAmount.Mul(bigAmount, big.NewFloat(scale))
// 将 big.Float 转换为 big.Int取整
intAmount, _ := bigAmount.Int(nil)
return intAmount
}
func BigIntToFloat64(symbol string, amount *big.Int) float64 {
var scale *big.Float
f := new(big.Float).SetInt(amount)
switch symbol {
case "ETH":
scale = new(big.Float).SetFloat64(1e18)
case "USDT":
scale = new(big.Float).SetFloat64(1e6)
default:
log.Printf("don`t support symbol: %s", symbol)
return 0
}
f.Quo(f, scale)
result, _ := f.Float64()
return result
}