diff --git a/wallet/elementsrpcwallet.go b/wallet/elementsrpcwallet.go index 6f36cf41..c22e87a8 100644 --- a/wallet/elementsrpcwallet.go +++ b/wallet/elementsrpcwallet.go @@ -3,6 +3,7 @@ package wallet import ( "errors" "fmt" + "math" "strings" "github.com/elementsproject/glightning/gelements" @@ -25,7 +26,7 @@ type RpcClient interface { CreateWallet(walletname string) (string, error) SetRpcWallet(walletname string) ListWallets() ([]string, error) - FundRawTx(txHex string) (*gelements.FundRawResult, error) + FundRawWithOptions(txstring string, options *gelements.FundRawOptions, iswitness *bool) (*gelements.FundRawResult, error) BlindRawTransaction(txHex string) (string, error) SignRawTransactionWithWallet(txHex string) (gelements.SignRawTransactionWithWalletRes, error) SendRawTx(txHex string) (string, error) @@ -89,7 +90,10 @@ func (r *ElementsRpcWallet) CreateAndBroadcastTransaction(swapParams *swap.Openi if err != nil { return "", "", 0, err } - fundedTx, err := r.rpcClient.FundRawTx(txHex) + fundedTx, err := r.rpcClient.FundRawWithOptions(txHex, &gelements.FundRawOptions{ + FeeRate: fmt.Sprintf("%f", r.getFeeRate()), + }, nil) + if err != nil { return "", "", 0, err } @@ -104,6 +108,33 @@ func (r *ElementsRpcWallet) CreateAndBroadcastTransaction(swapParams *swap.Openi return txid, finalized, gelements.ConvertBtc(fundedTx.Fee), nil } +const ( + // minFeeRateBTCPerKb defines the minimum fee rate in BTC/kB. + // This value is equivalent to 0.1 sat/byte. + minFeeRateBTCPerKb = 0.000001 +) + +// getFeeRate retrieves the optimal fee rate based on the current Liquid network conditions. +// This function does the following: +// 1. Uses the EstimateFee RPC to estimate a fee rate targeting confirmation within a specified number of blocks. +// 2. Returns the minimum fee rate if an error occurs or if the estimation result contains errors. +// 3. Returns the minimum fee rate if the estimated fee rate is below the minimum. +// +// Returns: +// - float64: The recommended fee rate in BTC/kB +func (r *ElementsRpcWallet) getFeeRate() float64 { + feeRes, err := r.rpcClient.EstimateFee(LiquidTargetBlocks, "ECONOMICAL") + + // Error check: RPC error or errors in the estimation result + if err != nil || len(feeRes.Errors) > 0 { + // Return the minimum fee rate in case of an error + return minFeeRateBTCPerKb + } + + // Return the larger of the estimated fee rate and the minimum fee rate + return math.Max(feeRes.FeeRate, minFeeRateBTCPerKb) +} + // setupWallet checks if the swap wallet is already loaded in elementsd, if not it loads/creates it func (r *ElementsRpcWallet) setupWallet() error { loadedWallets, err := r.rpcClient.ListWallets()