Sale Djenic 1bb9cbc573 chore_: router response moved to wallet responses location
Following the approach we did for keeping requests at the same location, these changes introduce
new location for responses. `SuggestedRoutesResponse` is moved there and renamed to
`RouterSuggestedRoutes` and code is updated accordingly.

New type `Route` defined (since a single route is composed of zero or more paths).

Types `Route`, `Path`, `Graph` and `Node` belong to a new `routs` package now.
2024-09-11 13:51:51 +02:00

68 lines
2.2 KiB
Go

package routes
import (
"math"
"math/big"
"github.com/status-im/status-go/services/wallet/common"
"github.com/status-im/status-go/services/wallet/router/pathprocessor"
)
type Route []*Path
func FindBestRoute(routes []Route, tokenPrice float64, nativeTokenPrice float64) Route {
var best Route
bestCost := big.NewFloat(math.Inf(1))
for _, route := range routes {
currentCost := big.NewFloat(0)
for _, path := range route {
tokenDenominator := big.NewFloat(math.Pow(10, float64(path.FromToken.Decimals)))
// calculate the cost of the path
nativeTokenPrice := new(big.Float).SetFloat64(nativeTokenPrice)
// tx fee
txFeeInEth := common.GweiToEth(common.WeiToGwei(path.TxFee.ToInt()))
pathCost := new(big.Float).Mul(txFeeInEth, nativeTokenPrice)
if path.TxL1Fee.ToInt().Cmp(pathprocessor.ZeroBigIntValue) > 0 {
txL1FeeInEth := common.GweiToEth(common.WeiToGwei(path.TxL1Fee.ToInt()))
pathCost.Add(pathCost, new(big.Float).Mul(txL1FeeInEth, nativeTokenPrice))
}
if path.TxBonderFees != nil && path.TxBonderFees.ToInt().Cmp(pathprocessor.ZeroBigIntValue) > 0 {
pathCost.Add(pathCost, new(big.Float).Mul(
new(big.Float).Quo(new(big.Float).SetInt(path.TxBonderFees.ToInt()), tokenDenominator),
new(big.Float).SetFloat64(tokenPrice)))
}
if path.TxTokenFees != nil && path.TxTokenFees.ToInt().Cmp(pathprocessor.ZeroBigIntValue) > 0 && path.FromToken != nil {
pathCost.Add(pathCost, new(big.Float).Mul(
new(big.Float).Quo(new(big.Float).SetInt(path.TxTokenFees.ToInt()), tokenDenominator),
new(big.Float).SetFloat64(tokenPrice)))
}
if path.ApprovalRequired {
// tx approval fee
approvalFeeInEth := common.GweiToEth(common.WeiToGwei(path.ApprovalFee.ToInt()))
pathCost.Add(pathCost, new(big.Float).Mul(approvalFeeInEth, nativeTokenPrice))
if path.ApprovalL1Fee.ToInt().Cmp(pathprocessor.ZeroBigIntValue) > 0 {
approvalL1FeeInEth := common.GweiToEth(common.WeiToGwei(path.ApprovalL1Fee.ToInt()))
pathCost.Add(pathCost, new(big.Float).Mul(approvalL1FeeInEth, nativeTokenPrice))
}
}
currentCost = new(big.Float).Add(currentCost, pathCost)
}
if currentCost.Cmp(bestCost) == -1 {
best = route
bestCost = currentCost
}
}
return best
}