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 support for getting spendable balance #9

Merged
merged 1 commit into from
Mar 25, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
4 changes: 2 additions & 2 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ linters-settings:
max-blank-identifiers: 2
dupl:
# tokens count to trigger issue, 150 by default
threshold: 100
threshold: 250
errcheck:
# report about not checking of errors in type assertions: `a := b.(MyStruct)`;
# default is false: such cases aren't reported by default.
Expand Down Expand Up @@ -462,4 +462,4 @@ severity:
rules:
- linters:
- dupl
severity: info
severity: info
31 changes: 0 additions & 31 deletions balance.go

This file was deleted.

4 changes: 2 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ const (
// endpointWallet is for accessing wallet information
endpointWallet = "/" + apiVersion + "/connect/wallet"

// endpointGetSpendableBalance will return a spendable balance amount
// endpointGetSpendableBalance = endpointProfile + "/spendableBalance"
// endpointGetSpendableBalanceRequest will return a spendable balance amount
endpointGetSpendableBalanceRequest = endpointWallet + "/spendableBalance"

// endpointGetPayRequest will create a new pay request
endpointGetPayRequest = endpointWallet + "/pay"
Expand Down
5 changes: 5 additions & 0 deletions definitions.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ type PaymentRequest struct {
TransactionID string `json:"transactionId"`
}

// BalanceRequest is used for GetSpendableBalance()
type BalanceRequest struct {
CurrencyCode CurrencyCode `json:"currencyCode"`
}

// AppAction enum
type AppAction string

Expand Down
75 changes: 75 additions & 0 deletions spendable_balance.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package handcash

import (
"context"
"encoding/json"
"fmt"
"net/http"
)

// SpendableBalanceResponse is the balance response
type SpendableBalanceResponse struct {
SpendableSatoshiBalance uint64 `json:"spendableSatoshiBalance"`
SpendableFiatBalance float64 `json:"spendableFiatBalance"`
CurrencyCode CurrencyCode `json:"currencyCode"`
}

// GetSpendableBalance gets the user's spendable balance from the handcash connect API
func (c *Client) GetSpendableBalance(ctx context.Context, authToken string, currencyCode CurrencyCode) (spendableBalanceResponse *SpendableBalanceResponse, err error) {

// Make sure we have an auth token
if len(authToken) == 0 {
return nil, fmt.Errorf("missing auth token")
}

if len(currencyCode) == 0 {
return nil, fmt.Errorf("missing currency code")
}

// Get the signed request
signed, err := c.getSignedRequest(
http.MethodGet,
endpointGetSpendableBalanceRequest,
authToken,
&BalanceRequest{CurrencyCode: currencyCode},
currentISOTimestamp(),
)
if err != nil {
return nil, fmt.Errorf("error creating signed request: %w", err)
}

// Convert into bytes
var params []byte
if params, err = json.Marshal(
&BalanceRequest{CurrencyCode: currencyCode},
); err != nil {
return nil, err
}

// Make the HTTP request
response := httpRequest(
ctx,
c,
&httpPayload{
Data: params,
ExpectedStatus: http.StatusOK,
Method: signed.Method,
URL: signed.URI,
},
signed,
)

if response.Error != nil {
return nil, response.Error
}

spendableBalanceResponse = new(SpendableBalanceResponse)

if err = json.Unmarshal(response.BodyContents, &spendableBalanceResponse); err != nil {
return nil, fmt.Errorf("failed unmarshal %w", err)
} else if spendableBalanceResponse == nil || spendableBalanceResponse.CurrencyCode == "" {
return nil, fmt.Errorf("failed to get balance")
}

return spendableBalanceResponse, nil
}
116 changes: 116 additions & 0 deletions spendable_balance_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package handcash

import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"testing"

"github.com/stretchr/testify/assert"
)

// mockHTTPGetSpendableBalance for mocking requests
type mockHTTPGetSpendableBalance struct{}

// Do is a mock http request
func (m *mockHTTPGetSpendableBalance) Do(req *http.Request) (*http.Response, error) {
resp := new(http.Response)

// No req found
if req == nil {
return resp, fmt.Errorf("missing request")
}

// Beta
if req.URL.String() == environments[EnvironmentBeta].APIURL+endpointGetSpendableBalanceRequest {
resp.StatusCode = http.StatusOK
resp.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(`{"spendableSatoshiBalance":1424992,"spendableFiatBalance":2.7792,"currencyCode":"USD"}`)))
}

// Default is valid
return resp, nil
}

// mockHTTPInvalidSpendableBalanceData for mocking requests
type mockHTTPInvalidSpendableBalanceData struct{}

// Do is a mock http request
func (m *mockHTTPInvalidSpendableBalanceData) Do(req *http.Request) (*http.Response, error) {
resp := new(http.Response)

// No req found
if req == nil {
return resp, fmt.Errorf("missing request")
}

resp.StatusCode = http.StatusOK
resp.Body = ioutil.NopCloser(bytes.NewBuffer([]byte(`{"invalid":"currencyCode"}`)))

// Default is valid
return resp, nil
}

func TestClient_GetSpendableBalance(t *testing.T) {
t.Parallel()

t.Run("missing auth token", func(t *testing.T) {
client := newTestClient(&mockHTTPGetSpendableBalance{}, EnvironmentBeta)
assert.NotNil(t, client)
balance, err := client.GetSpendableBalance(context.Background(), "", "")
assert.Error(t, err)
assert.Nil(t, balance)
})

t.Run("missing currency code", func(t *testing.T) {
client := newTestClient(&mockHTTPGetSpendableBalance{}, EnvironmentBeta)
assert.NotNil(t, client)
balance, err := client.GetSpendableBalance(context.Background(), "000000", "")
assert.Error(t, err)
assert.Nil(t, balance)
})

t.Run("invalid auth token", func(t *testing.T) {
client := newTestClient(&mockHTTPGetSpendableBalance{}, EnvironmentBeta)
assert.NotNil(t, client)
balance, err := client.GetSpendableBalance(context.Background(), "0", "USD")
assert.Error(t, err)
assert.Nil(t, balance)
})

t.Run("invalid currency code", func(t *testing.T) {
client := newTestClient(&mockHTTPGetSpendableBalance{}, EnvironmentBeta)
assert.NotNil(t, client)
balance, err := client.GetSpendableBalance(context.Background(), "0", "FOO")
assert.Error(t, err)
assert.Nil(t, balance)
})

t.Run("bad request", func(t *testing.T) {
client := newTestClient(&mockHTTPBadRequest{}, EnvironmentBeta)
assert.NotNil(t, client)
balance, err := client.GetSpendableBalance(context.Background(), "000000", "USD")
assert.Error(t, err)
assert.Nil(t, balance)
})

t.Run("invalid spendable balance data", func(t *testing.T) {
client := newTestClient(&mockHTTPInvalidSpendableBalanceData{}, EnvironmentBeta)
assert.NotNil(t, client)
balance, err := client.GetSpendableBalance(context.Background(), "000000", "USD")
assert.Error(t, err)
assert.Nil(t, balance)
})

t.Run("valid spendable balance response", func(t *testing.T) {
client := newTestClient(&mockHTTPGetSpendableBalance{}, EnvironmentBeta)
assert.NotNil(t, client)
balance, err := client.GetSpendableBalance(context.Background(), "000000", "USD")
assert.NoError(t, err)
assert.NotNil(t, balance)
assert.Equal(t, CurrencyUSD, balance.CurrencyCode)
assert.Equal(t, uint64(1424992), balance.SpendableSatoshiBalance)
assert.Equal(t, float64(2.7792), balance.SpendableFiatBalance)
})
}