diff --git a/dash-backend.go b/dash-backend.go index 43739ec..f950499 100644 --- a/dash-backend.go +++ b/dash-backend.go @@ -3,6 +3,7 @@ package main import ( "context" "fmt" + "github.com/spacemeshos/dash-backend/utils" "io" "math/rand" "net/http" @@ -105,6 +106,18 @@ func main() { } }) + http.HandleFunc("/circulating", func(w http.ResponseWriter, r *http.Request) { + stats := history.GetStats() + var circulation int64 = 0 + for _, val := range stats.Circulation { + circulation += val.Amt + } + c := utils.ParseSmidge(float64(circulation)) + + w.WriteHeader(http.StatusOK) + w.Write([]byte(c.Value)) + }) + err = http.ListenAndServe(listenStringFlag, nil) if err != nil { log.Err(fmt.Errorf("Create HTTP ssrver error: %v", err)) diff --git a/history/history.go b/history/history.go index f6302eb..abda5d4 100644 --- a/history/history.go +++ b/history/history.go @@ -91,6 +91,15 @@ func getObject(d *bson.D, name string) *bson.E { } func (h *History) pushStatistics() { + message := h.GetStats() + h.bus.Notify <- message.ToJson() +} + +func (h *History) push(m *api.Message) { + h.bus.Notify <- m.ToJson() +} + +func (h *History) GetStats() *api.Message { var i int now := uint32(time.Now().Unix()) @@ -166,9 +175,5 @@ func (h *History) pushStatistics() { } } - h.bus.Notify <- message.ToJson() -} - -func (h *History) push(m *api.Message) { - h.bus.Notify <- m.ToJson() + return message } diff --git a/utils/converter.go b/utils/converter.go new file mode 100644 index 0000000..d33496a --- /dev/null +++ b/utils/converter.go @@ -0,0 +1,42 @@ +package utils + +import ( + "math" + "strconv" +) + +type CoinUnits struct { + SMH string + Smidge string +} + +var coinUnits = CoinUnits{ + SMH: "SMH", + Smidge: "Smidge", +} + +type Coin struct { + Value string + Unit string +} + +func packValueAndUnit(value float64, unit string) Coin { + return Coin{ + Value: strconv.FormatFloat(value, 'f', 3, 64), + Unit: unit, + } +} + +func ParseSmidge(amount float64) Coin { + if amount <= 0 || math.IsNaN(amount) { + return packValueAndUnit(0, coinUnits.SMH) + } + if amount >= math.Pow10(6) { + return packValueAndUnit(toSMH(amount), coinUnits.SMH) + } + return packValueAndUnit(amount, coinUnits.Smidge) +} + +func toSMH(smidge float64) float64 { + return smidge / math.Pow10(9) +}