Skip to content

Commit

Permalink
exchange: expose GetCredentials() and split GetAuthenticatedAPISuppor…
Browse files Browse the repository at this point in the history
…t() (thrasher-corp#954)

* exchange/wrapper: expose GetCredentials func to IBotInterface

* exchanges: split up GetAuthenticatedAPISupport into specific function calls, organize IBotExchange functionality getter functions

* interface: change name - RPCSercer: rm GetBase func call.

* glorious: nits (fix panic)

Co-authored-by: Ryan O'Hara-Reid <[email protected]>
  • Loading branch information
shazbert and Ryan O'Hara-Reid authored May 18, 2022
1 parent a9126f6 commit 14cde7b
Show file tree
Hide file tree
Showing 24 changed files with 93 additions and 96 deletions.
4 changes: 2 additions & 2 deletions docs/ADD_NEW_EXCHANGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -716,7 +716,7 @@ func (f *FTX) WsConnect() error {
// This reader routine is called prior to initiating a subscription for
// efficient processing.
go f.wsReadData()
if f.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if f.IsWebsocketAuthenticationSupported() {
err = f.WsAuth(context.TODO())
if err != nil {
f.Websocket.DataHandler <- err
Expand Down Expand Up @@ -766,7 +766,7 @@ func (f *FTX) GenerateDefaultSubscriptions() ([]stream.ChannelSubscription, erro
}
}
// Appends authenticated channels to the subscription list
if f.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if f.IsWebsocketAuthenticationSupported() {
var authchan = []string{wsOrders, wsFills}
for x := range authchan {
subscriptions = append(subscriptions, stream.ChannelSubscription{
Expand Down
24 changes: 12 additions & 12 deletions engine/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -328,8 +328,8 @@ func (bot *Engine) GetAuthAPISupportedExchanges() []string {
exchanges := bot.GetExchanges()
exchangeNames := make([]string, 0, len(exchanges))
for x := range exchanges {
if !exchanges[x].GetAuthenticatedAPISupport(exchange.RestAuthentication) &&
!exchanges[x].GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if !exchanges[x].IsRESTAuthenticationSupported() &&
!exchanges[x].IsWebsocketAuthenticationSupported() {
continue
}
exchangeNames = append(exchangeNames, exchanges[x].GetName())
Expand Down Expand Up @@ -696,10 +696,10 @@ func (bot *Engine) GetAllExchangeCryptocurrencyDepositAddresses() map[string]map
depositSyncer.Add(len(exchanges))
var m sync.Mutex
for x := range exchanges {
go func(x int) {
go func(exch exchange.IBotExchange) {
defer depositSyncer.Done()
exchName := exchanges[x].GetName()
if !exchanges[x].GetAuthenticatedAPISupport(exchange.RestAuthentication) {
exchName := exch.GetName()
if !exch.IsRESTAuthenticationSupported() {
if bot.Settings.Verbose {
log.Debugf(log.ExchangeSys, "GetAllExchangeCryptocurrencyDepositAddresses: Skippping %s due to disabled authenticated API support.\n", exchName)
}
Expand All @@ -711,15 +711,15 @@ func (bot *Engine) GetAllExchangeCryptocurrencyDepositAddresses() map[string]map
log.Errorf(log.ExchangeSys, "%s failed to get cryptocurrency deposit addresses. Err: %s\n", exchName, err)
return
}
supportsMultiChain := exchanges[x].GetBase().Features.Supports.RESTCapabilities.MultiChainDeposits
requiresChainSet := exchanges[x].GetBase().Features.Supports.RESTCapabilities.MultiChainDepositRequiresChainSet
supportsMultiChain := exch.GetBase().Features.Supports.RESTCapabilities.MultiChainDeposits
requiresChainSet := exch.GetBase().Features.Supports.RESTCapabilities.MultiChainDepositRequiresChainSet
cryptoAddr := make(map[string][]deposit.Address)
for y := range cryptoCurrencies {
cryptocurrency := cryptoCurrencies[y]
isSingular := false
var depositAddrs []deposit.Address
if supportsMultiChain {
availChains, err := exchanges[x].GetAvailableTransferChains(context.TODO(), currency.NewCode(cryptocurrency))
availChains, err := exch.GetAvailableTransferChains(context.TODO(), currency.NewCode(cryptocurrency))
if err != nil {
log.Errorf(log.Global, "%s failed to get cryptocurrency available transfer chains. Err: %s\n", exchName, err)
continue
Expand All @@ -728,7 +728,7 @@ func (bot *Engine) GetAllExchangeCryptocurrencyDepositAddresses() map[string]map
// store the default non-chain specified address for a specified crypto
chainContainsItself := common.StringDataCompareInsensitive(availChains, cryptocurrency)
if !chainContainsItself && !requiresChainSet {
depositAddr, err := exchanges[x].GetDepositAddress(context.TODO(), currency.NewCode(cryptocurrency), "", "")
depositAddr, err := exch.GetDepositAddress(context.TODO(), currency.NewCode(cryptocurrency), "", "")
if err != nil {
log.Errorf(log.Global, "%s failed to get cryptocurrency deposit address for %s. Err: %s\n",
exchName,
Expand All @@ -740,7 +740,7 @@ func (bot *Engine) GetAllExchangeCryptocurrencyDepositAddresses() map[string]map
depositAddrs = append(depositAddrs, *depositAddr)
}
for z := range availChains {
depositAddr, err := exchanges[x].GetDepositAddress(context.TODO(), currency.NewCode(cryptocurrency), "", availChains[z])
depositAddr, err := exch.GetDepositAddress(context.TODO(), currency.NewCode(cryptocurrency), "", availChains[z])
if err != nil {
log.Errorf(log.Global, "%s failed to get cryptocurrency deposit address for %s [chain %s]. Err: %s\n",
exchName,
Expand All @@ -759,7 +759,7 @@ func (bot *Engine) GetAllExchangeCryptocurrencyDepositAddresses() map[string]map
}

if !supportsMultiChain || isSingular {
depositAddr, err := exchanges[x].GetDepositAddress(context.TODO(), currency.NewCode(cryptocurrency), "", "")
depositAddr, err := exch.GetDepositAddress(context.TODO(), currency.NewCode(cryptocurrency), "", "")
if err != nil {
log.Errorf(log.Global, "%s failed to get cryptocurrency deposit address for %s. Err: %s\n",
exchName,
Expand All @@ -774,7 +774,7 @@ func (bot *Engine) GetAllExchangeCryptocurrencyDepositAddresses() map[string]map
m.Lock()
result[exchName] = cryptoAddr
m.Unlock()
}(x)
}(exchanges[x])
}
depositSyncer.Wait()
if len(result) > 0 {
Expand Down
8 changes: 4 additions & 4 deletions engine/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1006,10 +1006,6 @@ func (f fakeDepositExchange) GetName() string {
return "fake"
}

func (f fakeDepositExchange) GetAuthenticatedAPISupport(endpoint uint8) bool {
return f.SupportsAuth
}

func (f fakeDepositExchange) GetBase() *exchange.Base {
return &exchange.Base{
Features: exchange.Features{Supports: exchange.FeaturesSupported{
Expand All @@ -1021,6 +1017,10 @@ func (f fakeDepositExchange) GetBase() *exchange.Base {
}
}

func (f fakeDepositExchange) IsRESTAuthenticationSupported() bool {
return f.SupportsAuth
}

func (f fakeDepositExchange) GetAvailableTransferChains(_ context.Context, c currency.Code) ([]string, error) {
if f.ThrowTransferChainError {
return nil, errors.New("unable to get available transfer chains")
Expand Down
2 changes: 1 addition & 1 deletion engine/order_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@ func (m *OrderManager) processOrders() {
}
var wg sync.WaitGroup
for i := range exchanges {
if !exchanges[i].GetAuthenticatedAPISupport(exchange.RestAuthentication) {
if !exchanges[i].IsRESTAuthenticationSupported() {
continue
}
log.Debugf(log.OrderMgr,
Expand Down
2 changes: 1 addition & 1 deletion engine/portfolio_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ func (m *portfolioManager) getExchangeAccountInfo(exchanges []exchange.IBotExcha
if !exchanges[x].IsEnabled() {
continue
}
if !exchanges[x].GetAuthenticatedAPISupport(exchange.RestAuthentication) {
if !exchanges[x].IsRESTAuthenticationSupported() {
if m.base.Verbose {
log.Debugf(log.PortfolioMgr,
"skipping %s due to disabled authenticated API support.\n",
Expand Down
6 changes: 3 additions & 3 deletions engine/rpcserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -1570,7 +1570,7 @@ func (s *RPCServer) GetCryptocurrencyDepositAddresses(ctx context.Context, r *gc
return nil, err
}

if !exch.GetAuthenticatedAPISupport(exchange.RestAuthentication) {
if !exch.IsRESTAuthenticationSupported() {
return nil, fmt.Errorf("%s, %w", r.Exchange, exchange.ErrAuthenticationSupportNotEnabled)
}

Expand Down Expand Up @@ -1603,7 +1603,7 @@ func (s *RPCServer) GetCryptocurrencyDepositAddress(ctx context.Context, r *gctr
return nil, err
}

if !exch.GetAuthenticatedAPISupport(exchange.RestAuthentication) {
if !exch.IsRESTAuthenticationSupported() {
return nil, fmt.Errorf("%s, %w", r.Exchange, exchange.ErrAuthenticationSupportNotEnabled)
}

Expand Down Expand Up @@ -4362,7 +4362,7 @@ func (s *RPCServer) GetCollateral(ctx context.Context, r *gctrpc.GetCollateralRe
if err != nil {
return nil, err
}
creds, err := exch.GetBase().GetCredentials(ctx)
creds, err := exch.GetCredentials(ctx)
if err != nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions exchanges/bittrex/bittrex_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ func (b *Bittrex) WsConnect() error {
Tickers: make(map[string]*TickerData),
}

if b.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if b.IsWebsocketAuthenticationSupported() {
err = b.WsAuth(context.TODO())
if err != nil {
b.Websocket.DataHandler <- err
Expand Down Expand Up @@ -217,7 +217,7 @@ func (b *Bittrex) GenerateDefaultSubscriptions() ([]stream.ChannelSubscription,
}

channels := defaultSpotSubscribedChannels
if b.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if b.IsWebsocketAuthenticationSupported() {
channels = append(channels, defaultSpotSubscribedChannelsAuth...)
}

Expand Down
3 changes: 1 addition & 2 deletions exchanges/btse/btse_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/gorilla/websocket"
"github.com/thrasher-corp/gocryptotrader/common/crypto"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
Expand Down Expand Up @@ -45,7 +44,7 @@ func (b *BTSE) WsConnect() error {
b.Websocket.Wg.Add(1)
go b.wsReadData()

if b.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if b.IsWebsocketAuthenticationSupported() {
err = b.WsAuthenticate(context.TODO())
if err != nil {
b.Websocket.DataHandler <- err
Expand Down
4 changes: 2 additions & 2 deletions exchanges/coinbasepro/coinbasepro_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ func (c *CoinbasePro) GenerateDefaultSubscriptions() ([]stream.ChannelSubscripti
var subscriptions []stream.ChannelSubscription
for i := range channels {
if (channels[i] == "user" || channels[i] == "full") &&
!c.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
!c.IsWebsocketAuthenticationSupported() {
continue
}
for j := range enabledCurrencies {
Expand All @@ -403,7 +403,7 @@ func (c *CoinbasePro) GenerateDefaultSubscriptions() ([]stream.ChannelSubscripti
func (c *CoinbasePro) Subscribe(channelsToSubscribe []stream.ChannelSubscription) error {
var creds *exchange.Credentials
var err error
if c.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if c.IsWebsocketAuthenticationSupported() {
creds, err = c.GetCredentials(context.TODO())
if err != nil {
return err
Expand Down
20 changes: 10 additions & 10 deletions exchanges/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -412,14 +412,14 @@ func (b *Base) SetAPICredentialDefaults() {
}
}

// GetAuthenticatedAPISupport returns whether the exchange supports
// authenticated API requests
func (b *Base) GetAuthenticatedAPISupport(endpoint uint8) bool {
switch endpoint {
case RestAuthentication:
return b.API.AuthenticatedSupport
case WebsocketAuthentication:
return b.API.AuthenticatedWebsocketSupport
}
return false
// IsWebsocketAuthenticationSupported returns whether the exchange supports
// websocket authenticated API requests
func (b *Base) IsWebsocketAuthenticationSupported() bool {
return b.API.AuthenticatedWebsocketSupport
}

// IsRESTAuthenticationSupported returns whether the exchange supports REST authenticated
// API requests
func (b *Base) IsRESTAuthenticationSupported() bool {
return b.API.AuthenticatedSupport
}
13 changes: 7 additions & 6 deletions exchanges/credentials_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -456,19 +456,20 @@ func TestGetAuthenticatedAPISupport(t *testing.T) {
},
}

if !base.GetAuthenticatedAPISupport(RestAuthentication) {
if !base.IsRESTAuthenticationSupported() {
t.Fatal("Expected RestAuthentication to return true")
}
if base.GetAuthenticatedAPISupport(WebsocketAuthentication) {
base.API.AuthenticatedSupport = false
if base.IsRESTAuthenticationSupported() {
t.Fatal("Expected RestAuthentication to return false")
}
if base.IsWebsocketAuthenticationSupported() {
t.Fatal("Expected WebsocketAuthentication to return false")
}
base.API.AuthenticatedWebsocketSupport = true
if !base.GetAuthenticatedAPISupport(WebsocketAuthentication) {
if !base.IsWebsocketAuthenticationSupported() {
t.Fatal("Expected WebsocketAuthentication to return true")
}
if base.GetAuthenticatedAPISupport(2) {
t.Fatal("Expected default case of 'false' to be returned")
}
}

func TestIsEmpty(t *testing.T) {
Expand Down
2 changes: 0 additions & 2 deletions exchanges/exchange_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ import (

// Endpoint authentication types
const (
RestAuthentication uint8 = 0
WebsocketAuthentication uint8 = 1
// Repeated exchange strings
// FeeType custom type for calculating fees based on method
WireTransfer InternationalBankTransactionType = iota
Expand Down
4 changes: 2 additions & 2 deletions exchanges/ftx/ftx.go
Original file line number Diff line number Diff line change
Expand Up @@ -1290,7 +1290,7 @@ func (f *FTX) SendAuthHTTPRequest(ctx context.Context, ep exchange.URL, method,
// GetFee returns an estimate of fee based on type of transaction
func (f *FTX) GetFee(ctx context.Context, feeBuilder *exchange.FeeBuilder) (float64, error) {
var fee float64
if !f.GetAuthenticatedAPISupport(exchange.RestAuthentication) {
if !f.IsRESTAuthenticationSupported() {
feeBuilder.FeeType = exchange.OfflineTradeFee
}
switch feeBuilder.FeeType {
Expand Down Expand Up @@ -1697,7 +1697,7 @@ func (f *FTX) LoadCollateralWeightings(ctx context.Context) error {
f.collateralWeight.load("ZM", 0.9, 0.85, 0.01)
f.collateralWeight.load("ZRX", 0.85, 0.8, 0.001)

if !f.GetAuthenticatedAPISupport(exchange.RestAuthentication) {
if !f.IsRESTAuthenticationSupported() {
return nil
}
coins, err := f.GetCoins(ctx)
Expand Down
5 changes: 2 additions & 3 deletions exchanges/ftx/ftx_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/crypto"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/fill"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
Expand Down Expand Up @@ -64,7 +63,7 @@ func (f *FTX) WsConnect() error {
f.Websocket.Wg.Add(1)
go f.wsReadData()

if f.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if f.IsWebsocketAuthenticationSupported() {
err = f.WsAuth(context.TODO())
if err != nil {
f.Websocket.DataHandler <- err
Expand Down Expand Up @@ -206,7 +205,7 @@ func (f *FTX) GenerateDefaultSubscriptions() ([]stream.ChannelSubscription, erro
}
}
}
if f.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if f.IsWebsocketAuthenticationSupported() {
var authchan = []string{wsOrders, wsFills}
for x := range authchan {
subscriptions = append(subscriptions, stream.ChannelSubscription{
Expand Down
3 changes: 1 addition & 2 deletions exchanges/gateio/gateio_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (
"github.com/thrasher-corp/gocryptotrader/common/convert"
"github.com/thrasher-corp/gocryptotrader/common/crypto"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
Expand Down Expand Up @@ -43,7 +42,7 @@ func (g *Gateio) WsConnect() error {
g.Websocket.Wg.Add(1)
go g.wsReadData()

if g.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if g.IsWebsocketAuthenticationSupported() {
err = g.wsServerSignIn(context.TODO())
if err != nil {
g.Websocket.DataHandler <- err
Expand Down
2 changes: 1 addition & 1 deletion exchanges/gemini/gemini_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ func (g *Gemini) Unsubscribe(channelsToUnsubscribe []stream.ChannelSubscription)

// WsAuth will connect to Gemini's secure endpoint
func (g *Gemini) WsAuth(ctx context.Context, dialer *websocket.Dialer) error {
if !g.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if !g.IsWebsocketAuthenticationSupported() {
return fmt.Errorf("%v AuthenticatedWebsocketAPISupport not enabled", g.Name)
}
creds, err := g.GetCredentials(ctx)
Expand Down
3 changes: 1 addition & 2 deletions exchanges/hitbtc/hitbtc_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/common/crypto"
"github.com/thrasher-corp/gocryptotrader/currency"
exchange "github.com/thrasher-corp/gocryptotrader/exchanges"
"github.com/thrasher-corp/gocryptotrader/exchanges/asset"
"github.com/thrasher-corp/gocryptotrader/exchanges/order"
"github.com/thrasher-corp/gocryptotrader/exchanges/orderbook"
Expand Down Expand Up @@ -566,7 +565,7 @@ func (h *HitBTC) Unsubscribe(channelsToUnsubscribe []stream.ChannelSubscription)

// Unsubscribe sends a websocket message to stop receiving data from the channel
func (h *HitBTC) wsLogin(ctx context.Context) error {
if !h.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if !h.IsWebsocketAuthenticationSupported() {
return fmt.Errorf("%v AuthenticatedWebsocketAPISupport not enabled", h.Name)
}
creds, err := h.GetCredentials(ctx)
Expand Down
4 changes: 2 additions & 2 deletions exchanges/huobi/huobi_websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func (h *HUOBI) wsDial(dialer *websocket.Dialer) error {
}

func (h *HUOBI) wsAuthenticatedDial(dialer *websocket.Dialer) error {
if !h.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if !h.IsWebsocketAuthenticationSupported() {
return fmt.Errorf("%v AuthenticatedWebsocketAPISupport not enabled",
h.Name)
}
Expand Down Expand Up @@ -636,7 +636,7 @@ func (h *HUOBI) wsGenerateSignature(creds *exchange.Credentials, timestamp, endp
}

func (h *HUOBI) wsLogin(ctx context.Context) error {
if !h.GetAuthenticatedAPISupport(exchange.WebsocketAuthentication) {
if !h.IsWebsocketAuthenticationSupported() {
return fmt.Errorf("%v AuthenticatedWebsocketAPISupport not enabled", h.Name)
}
creds, err := h.GetCredentials(ctx)
Expand Down
Loading

0 comments on commit 14cde7b

Please sign in to comment.