abstract providers behind a common interface
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2023-11-12 21:40:00 -07:00
parent 82f9c94d10
commit 7284545571
15 changed files with 292 additions and 218 deletions

View File

@ -25,13 +25,12 @@ type Address struct {
// GetAddress returns an Address struct populated with data from blockstream.info
// for a given BTC address
func (c *Client) GetAddress(address string) (*Address, error) {
func (c *client) GetAddress(address string) (*Address, error) {
addressResponse := &Address{}
err := c.get(fmt.Sprintf("address/%s", address), addressResponse, url.Values{})
if err != nil {
return nil, err
}
return addressResponse, nil
}

View File

@ -14,13 +14,13 @@ const apiBaseURL = "https://blockstream.info/api/"
// A client is the structure that will be used to consume the API
// endpoints. It holds the login credentials, http client/transport,
// rate limit information, and the login session timer.
type Client struct {
type client struct {
httpClient *http.Client
transport *http.Transport
}
// Send an HTTP GET request, and return the processed response
func (c *Client) get(endpoint string, out interface{}, query url.Values) error {
func (c *client) get(endpoint string, out interface{}, query url.Values) error {
req, err := http.NewRequest("GET", apiBaseURL+endpoint+"?"+query.Encode(), nil)
if err != nil {
return fmt.Errorf("failed to create new GET request: %v", err)
@ -42,7 +42,7 @@ func (c *Client) get(endpoint string, out interface{}, query url.Values) error {
// the error code, or unmarshalls the JSON response, extracts
// rate limit info, and places it into the object
// output parameter. This function closes the response body after reading it.
func (c *Client) processResponse(res *http.Response, out interface{}) error {
func (c *client) processResponse(res *http.Response, out interface{}) error {
body, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
@ -57,25 +57,23 @@ func (c *Client) processResponse(res *http.Response, out interface{}) error {
if err != nil {
return fmt.Errorf("failed to unmarshal response body: %v", err)
}
return nil
}
// NewClient is the factory function for clients
func NewClient() (*Client, error) {
// newClient is the factory function for clients
func newClient() (*client, error) {
transport := &http.Transport{
ResponseHeaderTimeout: 5 * time.Second,
}
client := &http.Client{
httpClient := &http.Client{
Transport: transport,
}
// Create a new client
c := &Client{
httpClient: client,
c := &client{
httpClient: httpClient,
transport: transport,
}
return c, nil
}

View File

@ -16,8 +16,7 @@ type FiatConversion struct {
// BTC to CAD FIAT conversion - accepts an
// amount in satoshi's and returns a CAD amount * 1000
func (c *Client) ConvertBTCToCAD(amount int) (int, error) {
func (c *client) ConvertBTCToCAD(amount int) (int, error) {
fiatConversion := &FiatConversion{}
req, err := http.NewRequest("GET", fiatConvertURL+"?amount=1", nil)
@ -38,6 +37,5 @@ func (c *Client) ConvertBTCToCAD(amount int) (int, error) {
if fiatConversion.Status != "success" {
return 0, fmt.Errorf("fiat conversion status was '%s' but expected 'success'", fiatConversion.Status)
}
return (amount * int(fiatConversion.CAD*1000)) / 100000000, nil // one BTC = one hundred million satoshi's
}

70
bitcoin/providerImpl.go Normal file
View File

@ -0,0 +1,70 @@
package bitcoin
import (
"fmt"
"os"
)
type Provider struct {
bitcoinAddresses []string // Slice of bitcoin addresses this provider monitors
ynabAccountID string // YNAB account ID this provider updates - all bitcoin addresses are summed up and mapped to this YNAB account
client *client // HTTP client for interacting with Questrade API
}
func (p *Provider) Name() string {
return "Bitcoin - Blockstream.info"
}
// Configures the provider for usage via environment variables and persistentData
// If an error is returned, the provider will not be used
func (p *Provider) Configure() error {
var err error
// Load environment variables in continous series with suffix starting at 0
// Multiple addresses can be configured, (eg _1, _2)
// As soon as the series is interrupted, we assume we're done
p.bitcoinAddresses = make([]string, 0)
for i := 0; true; i++ {
bitcoinAddress := os.Getenv(fmt.Sprintf("bitcoin_address_%d", i))
if bitcoinAddress == "" {
if i == 0 {
return fmt.Errorf("this account provider is not configured")
}
break
}
p.bitcoinAddresses = append(p.bitcoinAddresses, bitcoinAddress)
}
p.ynabAccountID = os.Getenv("bitcoin_ynab_account")
// Create new HTTP client
p.client, err = newClient()
if err != nil {
return fmt.Errorf("failed to create new bitcoin client: %v", err)
}
return nil
}
// Returns slices of account balances and mapped YNAB account IDs, along with an error
func (p *Provider) GetBalances() ([]int, []string, error) {
balances := make([]int, 0)
ynabAccountIDs := make([]string, 0)
var satoshiBalance int
for _, bitcoinAddress := range p.bitcoinAddresses {
addressResponse, err := p.client.GetAddress(bitcoinAddress)
if err != nil {
return balances, ynabAccountIDs, fmt.Errorf("failed to get bitcoin address '%s': %v", bitcoinAddress, err)
}
satoshiBalance += addressResponse.ChainStats.FundedTxoSum - addressResponse.ChainStats.SpentTxoSum
}
fiatBalance, err := p.client.ConvertBTCToCAD(satoshiBalance)
if err != nil {
return balances, ynabAccountIDs, fmt.Errorf("failed to convert satoshi balance to fiat balance: %v", err)
}
balances = append(balances, fiatBalance)
ynabAccountIDs = append(ynabAccountIDs, p.ynabAccountID)
return balances, ynabAccountIDs, nil
}