-
Notifications
You must be signed in to change notification settings - Fork 2
/
rates.go
111 lines (89 loc) · 2.34 KB
/
rates.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"encoding/json"
"io"
"log"
"math"
"net/http"
"strings"
"time"
)
const satsPerBitcoin = 100_000_000
type Currency string
const (
CAD Currency = "cad"
CHF Currency = "chf"
CZK Currency = "czk"
EUR Currency = "eur"
GBP Currency = "gbp"
USD Currency = "usd"
)
func supportedCurrencies() []Currency {
return []Currency{CAD, CHF, CZK, EUR, GBP, USD}
}
func currencyCode(currency Currency) string {
return strings.ToUpper(string(currency))
}
type RatesService struct {
currencies string
rates map[Currency]float64
}
func newRatesService(refreshPeriod time.Duration) *RatesService {
var currencies string
for _, currency := range supportedCurrencies() {
currencies += "," + string(currency)
}
service := RatesService{currencies: currencies[1:]}
if err := service.fetchRates(); err != nil {
log.Fatalln("error fetching rates:", err)
}
go func() {
for true {
time.Sleep(refreshPeriod)
err := service.fetchRates()
if err != nil {
log.Println("error updating rates:", err)
}
}
}()
return &service
}
func (service *RatesService) fetchRates() error {
url := "https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=" + service.currencies
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
request.Header.Set("User-Agent", "lnurld/1.0")
response, err := http.DefaultClient.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
bodyBytes, _ := io.ReadAll(response.Body)
var ratesResponse struct {
Bitcoin map[Currency]float64 `json:"bitcoin"`
}
if err := json.Unmarshal(bodyBytes, &ratesResponse); err != nil {
return err
}
service.rates = ratesResponse.Bitcoin
return nil
}
func (service *RatesService) getExchangeRates() map[Currency]float64 {
exchangeRates := map[Currency]float64{}
for currency, exchangeRate := range service.rates {
exchangeRates[currency] = exchangeRate / satsPerBitcoin
}
return exchangeRates
}
func (service *RatesService) fiatToSats(currency Currency, amount float64) uint32 {
exchangeRate := service.rates[currency]
sats := math.Round(satsPerBitcoin / exchangeRate * amount)
return uint32(sats)
}
func (service *RatesService) satsToFiat(currency Currency, sats int64) float64 {
exchangeRate := service.rates[currency]
amount := float64(sats) * exchangeRate / satsPerBitcoin
return amount
}