github.com/wtfutil/wtf@v0.43.0/modules/cryptocurrency/mempool/widget.go (about)

     1  package mempool
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/rivo/tview"
     8  	"github.com/wtfutil/wtf/logger"
     9  	"github.com/wtfutil/wtf/utils"
    10  	"github.com/wtfutil/wtf/view"
    11  )
    12  
    13  // Widget is the container for your module's data
    14  type Widget struct {
    15  	view.TextWidget
    16  	settings *Settings
    17  }
    18  
    19  // NewWidget creates and returns an instance of Widget
    20  func NewWidget(tviewApp *tview.Application, redrawChan chan bool, pages *tview.Pages, settings *Settings) *Widget {
    21  	widget := Widget{
    22  		TextWidget: view.NewTextWidget(tviewApp, redrawChan, pages, settings.common),
    23  
    24  		settings: settings,
    25  	}
    26  	return &widget
    27  }
    28  
    29  type feeStruct struct {
    30  	FastFee     int `json:"fastestFee"`
    31  	HalfHourFee int `json:"halfHourFee"`
    32  	HourFee     int `json:"hourFee"`
    33  	EcoFee      int `json:"economyFee"`
    34  }
    35  
    36  /* -------------------- Exported Functions -------------------- */
    37  
    38  // Refresh updates the onscreen contents of the widget
    39  func (widget *Widget) Refresh() {
    40  	// The last call should always be to the display function
    41  	widget.display()
    42  }
    43  
    44  /* -------------------- Unexported Functions -------------------- */
    45  
    46  func (widget *Widget) content() string {
    47  	return getBTCTxFees()
    48  }
    49  
    50  func getBTCTxFees() string {
    51  	url := "https://mempool.space/api/v1/fees/recommended"
    52  	resp, err := http.Get(url)
    53  	if err != nil {
    54  		logger.Log(fmt.Sprintf("[mempool] Error: Failed to make request to mempool. Reason: %s", err))
    55  		return "[mempool] error callng mempool API"
    56  	}
    57  	defer resp.Body.Close()
    58  
    59  	parsed := feeStruct{}
    60  	err = utils.ParseJSON(&parsed, resp.Body)
    61  	if err != nil {
    62  		logger.Log(fmt.Sprintf("[mempool] Error: Failed to decode JSON data from mempool. Reason: %s", err))
    63  		return "[mempool] error parsing JSON from mempool API"
    64  	}
    65  
    66  	finalStr := ""
    67  	finalStr += fmt.Sprintf("%-7s %2d sat/vB\n", "Fast", parsed.FastFee)
    68  	finalStr += fmt.Sprintf("%-7s %2d sat/vB\n", "30 min", parsed.HalfHourFee)
    69  	finalStr += fmt.Sprintf("%-7s %2d sat/vB\n", "60 min", parsed.HourFee)
    70  	finalStr += fmt.Sprintf("%-7s %2d sat/vB\n", "Eco", parsed.EcoFee)
    71  
    72  	return finalStr
    73  }
    74  
    75  func (widget *Widget) display() {
    76  	widget.Redraw(func() (string, string, bool) {
    77  		return widget.CommonSettings().Title, widget.content(), false
    78  	})
    79  }