exchange

package
v0.20.10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2026 License: GPL-3.0 Imports: 8 Imported by: 0

Documentation

Overview

Package exchange converts service-earnings amounts between currencies for the CashPilot Desktop dashboard.

It mirrors the CashPilot server's app/exchange_rates.py logic: crypto-to-USD rates come from CoinGecko (free, no key) and USD-to-fiat rates come from the Frankfurter API (free, no key). Rates are cached in memory and refreshed periodically. The cache is stale-graceful: a failed refresh keeps the last good rates rather than blanking them, and callers can check Stale to avoid silently summing balances against rates that may be badly out of date.

The service is injectable (no package globals) and safe for concurrent use.

Index

Constants

View Source
const (
	CacheTTL       = 15 * time.Minute
	StaleThreshold = 30 * time.Minute
)

CacheTTL is how long cached rates are considered fresh; EnsureFresh triggers a refresh once the cache is older than this. StaleThreshold (2x the TTL) is how long rates may survive failing refreshes before Stale reports true.

Variables

View Source
var DefaultCryptoIDs = map[string]string{
	"MYST":   "mysterium",
	"ANYONE": "airtor-protocol",
	"STORJ":  "storj",
	"HNT":    "helium",
	"GLM":    "golem",
	"PRE":    "presearch",
	"DVPN":   "sentinel",
	"DPR":    "deeper-network",
	"NOS":    "nosana",
	"FLUX":   "zelcash",
	"KOII":   "koii",
	"NODL":   "nodle-network",
	"TFUEL":  "theta-fuel",
}

DefaultCryptoIDs maps CashPilot's internal currency codes to CoinGecko coin ids. Grass *points* are intentionally absent: they are an internal reward that converts to the GRASS token only during airdrops at unknown ratios, so they are never priced here (see PointsCurrencies).

View Source
var PointsCurrencies = map[string]bool{
	"GRASS": true,
}

PointsCurrencies lists reward "points" that are deliberately non-convertible (they have no market price), so they are never summed into fiat/USD totals.

Functions

This section is empty.

Types

type Option

type Option func(*Service)

Option customises a Service at construction time.

func WithBaseURLs

func WithBaseURLs(coingecko, frankfurter string) Option

WithBaseURLs overrides the CoinGecko and Frankfurter base URLs (handy for tests). Empty strings leave the corresponding default in place. Trailing slashes are trimmed so path joining stays correct.

func WithCryptoIDs

func WithCryptoIDs(m map[string]string) Option

WithCryptoIDs overrides the currency-code -> CoinGecko-id map. A nil map is ignored so DefaultCryptoIDs is preserved.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient overrides the HTTP client used for rate fetches. A nil client is ignored so the default (15s timeout) is preserved.

type Rates

type Rates struct {
	Fiat        map[string]float64 `json:"fiat"`
	CryptoUSD   map[string]float64 `json:"cryptoUsd"`
	LastUpdated string             `json:"lastUpdated"`
}

Rates is a JSON-friendly snapshot of the cache for the frontend.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service holds the cached rates and the configuration needed to refresh them. The zero value is not usable; construct one with NewService.

func NewService

func NewService(opts ...Option) *Service

NewService builds a Service with sensible defaults, applying any options.

func (*Service) Convertible

func (s *Service) Convertible(currency string) bool

Convertible reports whether a currency can be converted (it is USD, a known fiat currency, or a priced crypto token).

func (*Service) EnsureFresh

func (s *Service) EnsureFresh(ctx context.Context)

EnsureFresh triggers a refresh when the cache is older than CacheTTL (or has never been fetched), but is NON-blocking: it kicks the refresh onto a background goroutine and returns immediately, so the awaited dashboard path (computeEarningsSummary / GetAppState) never stalls on up to ~30s of sequential HTTP GETs. A single-flight guard (refreshing) means concurrent or repeatedly-awaited callers never stack refreshes or block on one another; they keep serving the last snapshot, and Stale reports whether that data is trustworthy. Refresh errors are swallowed (the cache is stale-graceful).

func (*Service) FromUSD

func (s *Service) FromUSD(usd float64, display string) (float64, bool)

FromUSD converts a USD amount into the display currency. ok is false when the display currency has no known rate.

func (*Service) IsPoints

func (s *Service) IsPoints(cur string) bool

IsPoints reports whether a currency is a declared reward "point" (it has no market price by design). Classification is by INTENT — membership in PointsCurrencies — not by whether a live rate happens to be available, so a priceable token that is momentarily unpriced (a rate outage) is never misclassified as a reward point. The lookup is case-insensitive.

func (*Service) Refresh

func (s *Service) Refresh(ctx context.Context) error

Refresh fetches the latest crypto and fiat rates. It is stale-graceful: on a non-200 response or a transport error from either source the old cache is left untouched and the error is returned. The cache and lastFetch are only replaced when both fetches succeed, so lastFetch marks the last fully successful refresh.

func (*Service) Snapshot

func (s *Service) Snapshot() Rates

Snapshot returns a deep copy of the current cache for serialisation.

func (*Service) Stale

func (s *Service) Stale() bool

Stale reports whether more than StaleThreshold has elapsed since the last successful refresh (a never-fetched cache is always stale).

func (*Service) ToDisplay

func (s *Service) ToDisplay(amount float64, from, display string) (float64, bool)

ToDisplay converts amount from one currency straight into the display currency, routing through USD. ok is false if either leg is non-convertible.

func (*Service) ToUSD

func (s *Service) ToUSD(amount float64, currency string) (usd float64, ok bool)

ToUSD converts amount in currency to USD. ok is false for USD-unpriceable inputs (unknown tokens, reward points, or a missing/zero rate) so the caller can avoid silently summing them.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL