Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add exchange rates #158

Merged
merged 18 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"go.sia.tech/explored/build"
"go.sia.tech/explored/config"
"go.sia.tech/explored/explorer"
"go.sia.tech/explored/internal/exchangerates"
"go.sia.tech/explored/internal/testutil"
"go.sia.tech/explored/persist/sqlite"
"go.uber.org/zap/zaptest"
Expand Down Expand Up @@ -69,7 +70,11 @@ func newExplorer(t *testing.T, network *consensus.Network, genesisBlock types.Bl
}

func newServer(t *testing.T, cm *chain.Manager, e *explorer.Explorer, listenAddr string) (*http.Server, error) {
api := api.NewServer(e, cm, &syncer.Syncer{})
ctx, cancel := context.WithCancel(context.Background())
ex := exchangerates.NewKraken(exchangerates.KrakenSiacoinPair, time.Second)
go ex.Start(ctx)

api := api.NewServer(e, cm, &syncer.Syncer{}, ex)
server := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api") {
Expand All @@ -90,6 +95,7 @@ func newServer(t *testing.T, cm *chain.Manager, e *explorer.Explorer, listenAddr
t.Cleanup(func() {
server.Close()
httpListener.Close()
cancel()
})
go func() {
server.Serve(httpListener)
Expand Down Expand Up @@ -467,6 +473,16 @@ func TestAPI(t *testing.T) {
}
testutil.Equal(t, "search type", explorer.SearchTypeContract, resp)
}},
{"Exchange rate", func(t *testing.T) {
resp, err := client.ExchangeRate()
if err != nil {
t.Fatal(err)
}
if resp <= 0 {
t.Fatal("exchange rate should be positive")
}
t.Logf("Exchange rate: %f", resp)
}},
}

for _, subtest := range subtests {
Expand Down
6 changes: 6 additions & 0 deletions api/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,3 +277,9 @@ func (c *Client) HostsList(params explorer.HostQuery, sortBy explorer.HostSortCo
err = c.c.POST("/hosts?"+v.Encode(), params, &resp)
return
}

// ExchangeRate returns the value of 1 SC in USD.
func (c *Client) ExchangeRate() (resp float64, err error) {
err = c.c.GET("/exchangerate", &resp)
return
}
15 changes: 14 additions & 1 deletion api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"go.sia.tech/coreutils/syncer"
"go.sia.tech/explored/build"
"go.sia.tech/explored/explorer"
"go.sia.tech/explored/internal/exchangerates"
)

type (
Expand Down Expand Up @@ -111,6 +112,7 @@ type server struct {
cm ChainManager
e Explorer
s Syncer
ex exchangerates.ExchangeRateSource

startTime time.Time
}
Expand Down Expand Up @@ -690,12 +692,21 @@ func (s *server) searchIDHandler(jc jape.Context) {
jc.Encode(result)
}

func (s *server) exchangeRateHandler(jc jape.Context) {
price, err := s.ex.Last()
if jc.Check("failed to get exchange rate", err) != nil {
return
}
jc.Encode(price)
}

// NewServer returns an HTTP handler that serves the explored API.
func NewServer(e Explorer, cm ChainManager, s Syncer) http.Handler {
func NewServer(e Explorer, cm ChainManager, s Syncer, ex exchangerates.ExchangeRateSource) http.Handler {
srv := server{
cm: cm,
e: e,
s: s,
ex: ex,
startTime: time.Now().UTC(),
}
return jape.Mux(map[string]jape.Handler{
Expand Down Expand Up @@ -753,5 +764,7 @@ func NewServer(e Explorer, cm ChainManager, s Syncer) http.Handler {
"POST /hosts": srv.hostsHandler,

"GET /search/:id": srv.searchIDHandler,

"GET /exchangerate": srv.exchangeRateHandler,
})
}
11 changes: 10 additions & 1 deletion cmd/explored/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"go.sia.tech/explored/build"
"go.sia.tech/explored/config"
"go.sia.tech/explored/explorer"
"go.sia.tech/explored/internal/exchangerates"
"go.sia.tech/explored/internal/syncerutil"
"go.sia.tech/explored/persist/sqlite"
"go.uber.org/zap"
Expand Down Expand Up @@ -262,7 +263,15 @@ func runRootCmd(ctx context.Context, log *zap.Logger) error {
defer timeoutCancel()
defer e.Shutdown(timeoutCtx)

api := api.NewServer(e, cm, s)
var sources []exchangerates.ExchangeRateSource
sources = append(sources, exchangerates.NewKraken(exchangerates.KrakenSiacoinPair, 3*time.Second))
if apiKey := os.Getenv("COINGECKO_API_KEY"); apiKey != "" {
sources = append(sources, exchangerates.NewCoinGecko(apiKey, exchangerates.CoinGeckoSicaoinPair, 3*time.Second))
}
ex := exchangerates.NewAverager(false, sources...)
go ex.Start(ctx)

api := api.NewServer(e, cm, s, ex)
server := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasPrefix(r.URL.Path, "/api") {
Expand Down
105 changes: 105 additions & 0 deletions internal/exchangerates/coingecko.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package exchangerates

import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"time"
)

const (
// CoinGeckoSicaoinPair is the ID of Siacoin in CoinGecko
CoinGeckoSicaoinPair = "siacoin"
)

type coinGeckoAPI struct {
apiKey string

client http.Client
}

func newcoinGeckoAPI(apiKey string) *coinGeckoAPI {
return &coinGeckoAPI{apiKey: apiKey}
}

type coinGeckoPriceResponse map[string]struct {
USD float64 `json:"usd"`
}

// See https://docs.coingecko.com/reference/simple-price
func (k *coinGeckoAPI) ticker(pair string) (float64, error) {
pair = strings.ToLower(pair)

request, err := http.NewRequest(http.MethodGet, "https://api.coingecko.com/api/v3/simple/price?vs_currencies=usd&ids="+url.PathEscape(pair), nil)
if err != nil {
return 0, err
}
request.Header.Set("accept", "application/json")
request.Header.Set("x-cg-demo-api-key", k.apiKey)

response, err := k.client.Do(request)
if err != nil {
return 0, err
}
var parsed coinGeckoPriceResponse
if err := json.NewDecoder(response.Body).Decode(&parsed); err != nil {
return 0, err
}

price, ok := parsed[pair]
if !ok {
return 0, fmt.Errorf("no asset %s", pair)
}
return price.USD, nil
}

type coinGecko struct {
pair string
refresh time.Duration
client *coinGeckoAPI

mu sync.Mutex
rate float64
err error
}

// NewCoinGecko returns an ExchangeRateSource that gets data from CoinGecko.
func NewCoinGecko(apiKey string, pair string, refresh time.Duration) ExchangeRateSource {
return &coinGecko{
pair: pair,
refresh: refresh,
client: newcoinGeckoAPI(apiKey),
}
}

// Start implements ExchangeRateSource.
func (c *coinGecko) Start(ctx context.Context) {
ticker := time.NewTicker(c.refresh)
defer ticker.Stop()

for {
select {
case <-ticker.C:
c.mu.Lock()
c.rate, c.err = c.client.ticker(c.pair)
c.mu.Unlock()
case <-ctx.Done():
c.mu.Lock()
c.err = ctx.Err()
c.mu.Unlock()
return
}
}
}

// Last implements ExchangeRateSource
func (c *coinGecko) Last() (rate float64, err error) {
c.mu.Lock()
rate, err = c.rate, c.err
c.mu.Unlock()
return
}
51 changes: 51 additions & 0 deletions internal/exchangerates/exchangerates.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package exchangerates

import (
"context"
"errors"
)

// An ExchangeRateSource returns the price of 1 unit of an asset in USD.
type ExchangeRateSource interface {
Last() (float64, error)
Start(ctx context.Context)
}

type averager struct {
ignoreOnError bool
sources []ExchangeRateSource
}

// NewAverager returns an exchange rate source that averages multiple exchange
// rates.
func NewAverager(ignoreOnError bool, sources ...ExchangeRateSource) ExchangeRateSource {
return &averager{
ignoreOnError: ignoreOnError,
sources: sources,
}
}

// Start implements ExchangeRateSource.
func (a *averager) Start(ctx context.Context) {
for i := range a.sources {
go a.sources[i].Start(ctx)
}
}

// Last implements ExchangeRateSource.
func (a *averager) Last() (float64, error) {
sum, count := 0.0, 0.0
for i := range a.sources {
if v, err := a.sources[i].Last(); err == nil {
sum += v
count++
} else if !a.ignoreOnError {
return 0, err
}
}

if count == 0 {
return 0, errors.New("no sources working")
}
return sum / count, nil
}
Loading
Loading