chore_: review comments applied (part1)

This commit is contained in:
Sale Djenic 2024-05-16 09:37:36 +02:00 committed by saledjenic
parent 08fef4afde
commit 4894808839
6 changed files with 110 additions and 117 deletions

View File

@ -445,23 +445,9 @@ func (api *API) GetSuggestedRoutes(
disabledToChaindIDs, preferedChainIDs, gasFeeMode, fromLockedAmount) disabledToChaindIDs, preferedChainIDs, gasFeeMode, fromLockedAmount)
} }
func (api *API) GetSuggestedRoutesV2( func (api *API) GetSuggestedRoutesV2(ctx context.Context, input *RouteInputParams) (*SuggestedRoutesV2, error) {
ctx context.Context,
sendType SendType,
addrFrom common.Address,
addrTo common.Address,
amountIn *hexutil.Big,
tokenID string,
toTokenID string,
disabledFromChainIDs,
disabledToChaindIDs,
preferedChainIDs []uint64,
gasFeeMode GasFeeMode,
fromLockedAmount map[uint64]*hexutil.Big,
) (*SuggestedRoutesV2, error) {
log.Debug("call to GetSuggestedRoutesV2") log.Debug("call to GetSuggestedRoutesV2")
return api.router.suggestedRoutesV2(ctx, sendType, addrFrom, addrTo, amountIn.ToInt(), tokenID, toTokenID, disabledFromChainIDs, return api.router.suggestedRoutesV2(ctx, input)
disabledToChaindIDs, preferedChainIDs, gasFeeMode, fromLockedAmount)
} }
// Generates addresses for the provided paths, response doesn't include `HasActivity` value (if you need it check `GetAddressDetails` function) // Generates addresses for the provided paths, response doesn't include `HasActivity` value (if you need it check `GetAddressDetails` function)

View File

@ -6,7 +6,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"math/big" "math/big"
netUrl "net/url" "net/url"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -68,7 +68,7 @@ func (s *CBridge) estimateAmt(from, to *params.Network, amountIn *big.Int, symbo
base = testBaseURL base = testBaseURL
} }
params := netUrl.Values{} params := url.Values{}
params.Add("src_chain_id", strconv.Itoa(int(from.ChainID))) params.Add("src_chain_id", strconv.Itoa(int(from.ChainID)))
params.Add("dst_chain_id", strconv.Itoa(int(to.ChainID))) params.Add("dst_chain_id", strconv.Itoa(int(to.ChainID)))
params.Add("token_symbol", symbol) params.Add("token_symbol", symbol)

View File

@ -343,24 +343,20 @@ func (h *HopBridge) swapAndSend(chainID uint64, hopArgs *HopTxArgs, signerFn bin
} }
func (h *HopBridge) CalculateFees(from, to *params.Network, token *token.Token, amountIn *big.Int) (*big.Int, *big.Int, error) { func (h *HopBridge) CalculateFees(from, to *params.Network, token *token.Token, amountIn *big.Int) (*big.Int, *big.Int, error) {
const ( hopChainsMap := map[uint64]string{
HopMainnetChainName = "ethereum" walletCommon.EthereumMainnet: "ethereum",
HopOptimismChainName = "optimism" walletCommon.OptimismMainnet: "optimism",
HopArbitrumChainName = "arbitrum" walletCommon.ArbitrumMainnet: "arbitrum",
)
fromChainName := HopMainnetChainName
if from.ChainID == walletCommon.OptimismMainnet {
fromChainName = HopOptimismChainName
} else if from.ChainID == walletCommon.ArbitrumMainnet {
fromChainName = HopArbitrumChainName
} }
toChainName := HopMainnetChainName fromChainName, ok := hopChainsMap[from.ChainID]
if from.ChainID == walletCommon.OptimismMainnet { if !ok {
toChainName = HopOptimismChainName return nil, nil, errors.New("from chain not supported")
} else if from.ChainID == walletCommon.ArbitrumMainnet { }
toChainName = HopArbitrumChainName
toChainName, ok := hopChainsMap[to.ChainID]
if !ok {
return nil, nil, errors.New("to chain not supported")
} }
params := netUrl.Values{} params := netUrl.Values{}

View File

@ -14,6 +14,7 @@ import (
gaspriceoracle "github.com/status-im/status-go/contracts/gas-price-oracle" gaspriceoracle "github.com/status-im/status-go/contracts/gas-price-oracle"
"github.com/status-im/status-go/rpc" "github.com/status-im/status-go/rpc"
"github.com/status-im/status-go/rpc/chain" "github.com/status-im/status-go/rpc/chain"
"github.com/status-im/status-go/services/wallet/common"
) )
type GasFeeMode int type GasFeeMode int
@ -101,6 +102,9 @@ func gweiToWei(val *big.Float) *big.Int {
// ////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////
// TODO: remove `suggestedFees` function once new router is in place // TODO: remove `suggestedFees` function once new router is in place
//
// But we should check the client since this function is exposed to API as `GetSuggestedFees` call.
// Maybe we should keep it and remove it later when the client is ready for that change.
// ////////////////////////////////////////////////////////////////////////////// // //////////////////////////////////////////////////////////////////////////////
func (f *FeeManager) SuggestedFees(ctx context.Context, chainID uint64) (*SuggestedFees, error) { func (f *FeeManager) SuggestedFees(ctx context.Context, chainID uint64) (*SuggestedFees, error) {
backend, err := f.RPCClient.EthClient(chainID) backend, err := f.RPCClient.EthClient(chainID)
@ -124,14 +128,11 @@ func (f *FeeManager) SuggestedFees(ctx context.Context, chainID uint64) (*Sugges
}, nil }, nil
} }
header, err := backend.HeaderByNumber(ctx, nil) baseFee, err := f.getBaseFee(ctx, backend)
if err != nil { if err != nil {
return nil, err return nil, err
} }
config := params.MainnetChainConfig
baseFee := misc.CalcBaseFee(config, header)
fees, err := f.getFeeHistorySorted(chainID) fees, err := f.getFeeHistorySorted(chainID)
if err != nil { if err != nil {
return &SuggestedFees{ return &SuggestedFees{
@ -176,15 +177,25 @@ func (f *FeeManager) SuggestedFees(ctx context.Context, chainID uint64) (*Sugges
}, nil }, nil
} }
func (f *FeeManager) getBaseFee(ctx context.Context, client chain.ClientInterface, testnetMode bool) (*big.Int, error) { func (f *FeeManager) getBaseFee(ctx context.Context, client chain.ClientInterface) (*big.Int, error) {
header, err := client.HeaderByNumber(ctx, nil) header, err := client.HeaderByNumber(ctx, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
chainID := client.NetworkID()
config := params.MainnetChainConfig config := params.MainnetChainConfig
if testnetMode { switch chainID {
case common.EthereumSepolia:
case common.OptimismSepolia:
case common.ArbitrumSepolia:
config = params.SepoliaChainConfig config = params.SepoliaChainConfig
case common.EthereumGoerli:
case common.OptimismGoerli:
case common.ArbitrumGoerli:
config = params.GoerliChainConfig
} }
baseFee := misc.CalcBaseFee(config, header) baseFee := misc.CalcBaseFee(config, header)

View File

@ -88,39 +88,39 @@ func (s SendType) needL1Fee() bool {
} }
func (s SendType) canUseBridge(b bridge.Bridge) bool { func (s SendType) canUseBridge(b bridge.Bridge) bool {
if s == ERC721Transfer && b.Name() != ERC721TransferString { bridgeName := b.Name()
return false switch s {
case ERC721Transfer:
return bridgeName == ERC721TransferString
case ERC1155Transfer:
return bridgeName == ERC1155TransferString
default:
return true
} }
if s != ERC721Transfer && b.Name() == ERC721TransferString {
return false
}
if s == ERC1155Transfer && b.Name() != ERC1155TransferString {
return false
}
if s != ERC1155Transfer && b.Name() == ERC1155TransferString {
return false
}
return true
} }
func (s SendType) isAvailableFor(network *params.Network) bool { func (s SendType) isAvailableFor(network *params.Network) bool {
// Set of network ChainIDs allowed for any type of transaction
allAllowedNetworks := map[uint64]bool{
walletCommon.EthereumMainnet: true,
walletCommon.EthereumGoerli: true,
walletCommon.EthereumSepolia: true,
}
// Additional specific networks for the Swap SendType
swapAllowedNetworks := map[uint64]bool{
walletCommon.EthereumMainnet: true,
walletCommon.OptimismMainnet: true,
walletCommon.ArbitrumMainnet: true,
}
// Check for Swap specific networks
if s == Swap { if s == Swap {
return network.ChainID == walletCommon.EthereumMainnet || return swapAllowedNetworks[network.ChainID]
network.ChainID == walletCommon.OptimismMainnet ||
network.ChainID == walletCommon.ArbitrumMainnet
} }
if s == Transfer || s == Bridge || s.IsCollectiblesTransfer() { // Check for any SendType available for all networks
return true if s == Transfer || s == Bridge || s.IsCollectiblesTransfer() || allAllowedNetworks[network.ChainID] {
}
if network.ChainID == walletCommon.EthereumMainnet ||
network.ChainID == walletCommon.EthereumGoerli ||
network.ChainID == walletCommon.EthereumSepolia {
return true return true
} }
@ -132,38 +132,37 @@ func (s SendType) EstimateGas(service *Service, network *params.Network, from co
From: (types.Address)(from), From: (types.Address)(from),
Value: (*hexutil.Big)(zero), Value: (*hexutil.Big)(zero),
} }
if s == ENSRegister { switch s {
case ENSRegister:
estimate, err := service.ens.API().RegisterEstimate(context.Background(), network.ChainID, tx, EstimateUsername, EstimatePubKey) estimate, err := service.ens.API().RegisterEstimate(context.Background(), network.ChainID, tx, EstimateUsername, EstimatePubKey)
if err != nil { if err != nil {
return 400000 return 400000
} }
return estimate return estimate
}
if s == ENSRelease { case ENSRelease:
estimate, err := service.ens.API().ReleaseEstimate(context.Background(), network.ChainID, tx, EstimateUsername) estimate, err := service.ens.API().ReleaseEstimate(context.Background(), network.ChainID, tx, EstimateUsername)
if err != nil { if err != nil {
return 200000 return 200000
} }
return estimate return estimate
}
if s == ENSSetPubKey { case ENSSetPubKey:
estimate, err := service.ens.API().SetPubKeyEstimate(context.Background(), network.ChainID, tx, fmt.Sprint(EstimateUsername, ".stateofus.eth"), EstimatePubKey) estimate, err := service.ens.API().SetPubKeyEstimate(context.Background(), network.ChainID, tx, fmt.Sprint(EstimateUsername, ".stateofus.eth"), EstimatePubKey)
if err != nil { if err != nil {
return 400000 return 400000
} }
return estimate return estimate
}
if s == StickersBuy { case StickersBuy:
packID := &bigint.BigInt{Int: big.NewInt(2)} packID := &bigint.BigInt{Int: big.NewInt(2)}
estimate, err := service.stickers.API().BuyEstimate(context.Background(), network.ChainID, (types.Address)(from), packID) estimate, err := service.stickers.API().BuyEstimate(context.Background(), network.ChainID, (types.Address)(from), packID)
if err != nil { if err != nil {
return 400000 return 400000
} }
return estimate return estimate
}
return 0 default:
return 0
}
} }

View File

@ -15,6 +15,20 @@ import (
walletToken "github.com/status-im/status-go/services/wallet/token" walletToken "github.com/status-im/status-go/services/wallet/token"
) )
type RouteInputParams struct {
SendType SendType `json:"sendType"`
AddrFrom common.Address `json:"addrFrom"`
AddrTo common.Address `json:"addrTo"`
AmountIn *hexutil.Big `json:"amountIn"`
TokenID string `json:"tokenID"`
ToTokenID string `json:"toTokenID"`
DisabledFromChainIDs []uint64 `json:"disabledFromChainIDs"`
DisabledToChaindIDs []uint64 `json:"disabledToChaindIDs"`
PreferedChainIDs []uint64 `json:"preferedChainIDs"`
GasFeeMode GasFeeMode `json:"gasFeeMode"`
FromLockedAmount map[uint64]*hexutil.Big `json:"fromLockedAmount"`
}
type PathV2 struct { type PathV2 struct {
BridgeName string BridgeName string
From *params.Network // Source chain From *params.Network // Source chain
@ -325,20 +339,7 @@ func findBestV2(routes [][]*PathV2, tokenPrice float64, nativeChainTokenPrice fl
return best return best
} }
func (r *Router) suggestedRoutesV2( func (r *Router) suggestedRoutesV2(ctx context.Context, input *RouteInputParams) (*SuggestedRoutesV2, error) {
ctx context.Context,
sendType SendType,
addrFrom common.Address,
addrTo common.Address,
amountIn *big.Int,
tokenID string,
toTokenID string,
disabledFromChainIDs,
disabledToChaindIDs,
preferedChainIDs []uint64,
gasFeeMode GasFeeMode,
fromLockedAmount map[uint64]*hexutil.Big,
) (*SuggestedRoutesV2, error) {
areTestNetworksEnabled, err := r.s.accountsDB.GetTestNetworksEnabled() areTestNetworksEnabled, err := r.s.accountsDB.GetTestNetworksEnabled()
if err != nil { if err != nil {
@ -362,32 +363,32 @@ func (r *Router) suggestedRoutesV2(
continue continue
} }
if containsNetworkChainID(network, disabledFromChainIDs) { if containsNetworkChainID(network, input.DisabledFromChainIDs) {
continue continue
} }
if !sendType.isAvailableFor(network) { if !input.SendType.isAvailableFor(network) {
continue continue
} }
token := sendType.FindToken(r.s, addrFrom, network, tokenID) token := input.SendType.FindToken(r.s, input.AddrFrom, network, input.TokenID)
if token == nil { if token == nil {
continue continue
} }
var toToken *walletToken.Token var toToken *walletToken.Token
if sendType == Swap { if input.SendType == Swap {
toToken = sendType.FindToken(r.s, common.Address{}, network, toTokenID) toToken = input.SendType.FindToken(r.s, common.Address{}, network, input.ToTokenID)
} }
amountLocked := false amountLocked := false
amountToSend := amountIn amountToSend := input.AmountIn.ToInt()
if lockedAmount, ok := fromLockedAmount[network.ChainID]; ok { if lockedAmount, ok := input.FromLockedAmount[network.ChainID]; ok {
amountToSend = lockedAmount.ToInt() amountToSend = lockedAmount.ToInt()
amountLocked = true amountLocked = true
} }
if len(fromLockedAmount) > 0 { if len(input.FromLockedAmount) > 0 {
for chainID, lockedAmount := range fromLockedAmount { for chainID, lockedAmount := range input.FromLockedAmount {
if chainID == network.ChainID { if chainID == network.ChainID {
continue continue
} }
@ -402,7 +403,7 @@ func (r *Router) suggestedRoutesV2(
} }
for _, bridge := range r.bridges { for _, bridge := range r.bridges {
if !sendType.canUseBridge(bridge) { if !input.SendType.canUseBridge(bridge) {
continue continue
} }
@ -411,11 +412,11 @@ func (r *Router) suggestedRoutesV2(
continue continue
} }
if len(preferedChainIDs) > 0 && !containsNetworkChainID(dest, preferedChainIDs) { if len(input.PreferedChainIDs) > 0 && !containsNetworkChainID(dest, input.PreferedChainIDs) {
continue continue
} }
if containsNetworkChainID(dest, disabledToChaindIDs) { if containsNetworkChainID(dest, input.DisabledToChaindIDs) {
continue continue
} }
@ -430,25 +431,25 @@ func (r *Router) suggestedRoutesV2(
} }
gasLimit := uint64(0) gasLimit := uint64(0)
if sendType.isTransfer() { if input.SendType.isTransfer() {
gasLimit, err = bridge.EstimateGas(network, dest, addrFrom, addrTo, token, toToken, amountToSend) gasLimit, err = bridge.EstimateGas(network, dest, input.AddrFrom, input.AddrTo, token, toToken, amountToSend)
if err != nil { if err != nil {
continue continue
} }
} else { } else {
gasLimit = sendType.EstimateGas(r.s, network, addrFrom, tokenID) gasLimit = input.SendType.EstimateGas(r.s, network, input.AddrFrom, input.TokenID)
} }
approvalContractAddress := bridge.GetContractAddress(network, token) approvalContractAddress := bridge.GetContractAddress(network, token)
approvalRequired, approvalAmountRequired, approvalGasLimit, l1ApprovalFee, err := r.requireApproval(ctx, sendType, approvalContractAddress, addrFrom, network, token, amountToSend) approvalRequired, approvalAmountRequired, approvalGasLimit, l1ApprovalFee, err := r.requireApproval(ctx, input.SendType, approvalContractAddress, input.AddrFrom, network, token, amountToSend)
if err != nil { if err != nil {
continue continue
} }
var l1FeeWei uint64 var l1FeeWei uint64
if sendType.needL1Fee() { if input.SendType.needL1Fee() {
tx, err := bridge.BuildTx(network, dest, addrFrom, addrTo, token, amountToSend, bonderFees) tx, err := bridge.BuildTx(network, dest, input.AddrFrom, input.AddrTo, token, amountToSend, bonderFees)
if err != nil { if err != nil {
continue continue
} }
@ -456,7 +457,7 @@ func (r *Router) suggestedRoutesV2(
l1FeeWei, _ = r.s.feesManager.GetL1Fee(ctx, network.ChainID, tx) l1FeeWei, _ = r.s.feesManager.GetL1Fee(ctx, network.ChainID, tx)
} }
baseFee, err := r.s.feesManager.getBaseFee(ctx, client, areTestNetworksEnabled) baseFee, err := r.s.feesManager.getBaseFee(ctx, client)
if err != nil { if err != nil {
continue continue
} }
@ -466,9 +467,9 @@ func (r *Router) suggestedRoutesV2(
continue continue
} }
selctedPriorityFee := priorityFees.Medium selctedPriorityFee := priorityFees.Medium
if gasFeeMode == GasFeeHigh { if input.GasFeeMode == GasFeeHigh {
selctedPriorityFee = priorityFees.High selctedPriorityFee = priorityFees.High
} else if gasFeeMode == GasFeeLow { } else if input.GasFeeMode == GasFeeLow {
selctedPriorityFee = priorityFees.Low selctedPriorityFee = priorityFees.Low
} }
@ -523,25 +524,25 @@ func (r *Router) suggestedRoutesV2(
group.Wait() group.Wait()
prices, err := sendType.FetchPrices(r.s, tokenID) prices, err := input.SendType.FetchPrices(r.s, input.TokenID)
if err != nil { if err != nil {
return nil, err return nil, err
} }
suggestedRoutes := newSuggestedRoutesV2(amountIn, candidates, fromLockedAmount, prices[tokenID], prices["ETH"]) suggestedRoutes := newSuggestedRoutesV2(input.AmountIn.ToInt(), candidates, input.FromLockedAmount, prices[input.TokenID], prices["ETH"])
// check the best route for the required balances // check the best route for the required balances
for _, path := range suggestedRoutes.Best { for _, path := range suggestedRoutes.Best {
if path.requiredTokenBalance != nil && path.requiredTokenBalance.Cmp(big.NewInt(0)) > 0 { if path.requiredTokenBalance != nil && path.requiredTokenBalance.Cmp(big.NewInt(0)) > 0 {
tokenBalance := big.NewInt(1) tokenBalance := big.NewInt(1)
if sendType == ERC1155Transfer { if input.SendType == ERC1155Transfer {
tokenBalance, err = r.getERC1155Balance(ctx, path.From, path.FromToken, addrFrom) tokenBalance, err = r.getERC1155Balance(ctx, path.From, path.FromToken, input.AddrFrom)
if err != nil { if err != nil {
return nil, err return nil, err
} }
} else if sendType != ERC721Transfer { } else if input.SendType != ERC721Transfer {
tokenBalance, err = r.getBalance(ctx, path.From, path.FromToken, addrFrom) tokenBalance, err = r.getBalance(ctx, path.From, path.FromToken, input.AddrFrom)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -557,7 +558,7 @@ func (r *Router) suggestedRoutesV2(
return nil, errors.New("native token not found") return nil, errors.New("native token not found")
} }
nativeBalance, err := r.getBalance(ctx, path.From, nativeToken, addrFrom) nativeBalance, err := r.getBalance(ctx, path.From, nativeToken, input.AddrFrom)
if err != nil { if err != nil {
return nil, err return nil, err
} }